Skip to main content

sunday_slate/entries/
service.rs

1//! The entry page's data: the structs the template renders and their
2//! construction.
3
4use crate::injuries::{self, InjuryChip};
5use crate::{assets, avatars};
6#[cfg(test)]
7use nfl_data::DfsPosition;
8use nfl_data::Snapshot;
9use std::collections::HashMap;
10#[cfg(test)]
11use std::sync::Arc;
12#[cfg(test)]
13use time::macros::datetime;
14
15use nfl_data::salaried_players::{SalariedPlayer, WeeklyStats};
16use nfl_data::slates::SlateId;
17use nfl_data::{
18    Game, InjuryDesignation, LiveGamePhase, PlayerIdentity, PlayerWeekStats as NflPlayerWeekStats,
19    TeamAbbr,
20};
21
22use crate::avatars::Avatars;
23use crate::contests::service as contests;
24use crate::entries::EntryId;
25use crate::entries::store;
26use crate::entries::{Lineup, NflPlayerId, PlayerOrDefenseId, RosterSlot};
27use crate::fantasy_teams as fantasy_teams_module;
28use crate::fantasy_teams::store as fantasy_teams;
29use crate::live::{self, ContestScores, Coverage, LiveContestSnapshot};
30use crate::media::Media;
31use crate::scoring;
32use crate::scoring::service as scoring_service;
33use crate::{AppError, AppState, User};
34use nfl_data::scoring::{self as nfl_scoring, Score, ScoreLine, WeekStats};
35use time::OffsetDateTime;
36
37/// Which lineup page a viewer gets.
38pub enum EntryView {
39    /// Scores: after kickoff, or the locked shell a non-owner sees before it.
40    Scored(EntryPage),
41    /// The owner's pre-kickoff review: salaries and schedule, no scores.
42    Preview(EntryPreview),
43}
44
45impl EntryView {
46    /// The `/contests/{id}` back target, shared by both pages.
47    pub fn contest_id(&self) -> SlateId {
48        match self {
49            EntryView::Scored(p) => p.contest_id,
50            EntryView::Preview(p) => p.contest_id,
51        }
52    }
53}
54
55pub struct EntryPage {
56    pub team_name: String,
57    pub owner_name: String,
58    pub logo_url: Option<String>,
59    pub contest_id: SlateId,
60    pub contest_name: String,
61    pub rank: Option<u32>,
62    pub score: ScoreMeta,
63    pub picks: Option<Picks>,
64}
65
66impl EntryPage {
67    /// Up to two initials from the fantasy team name, for the logo fallback.
68    pub fn monogram(&self) -> String {
69        fantasy_teams_module::monogram(&self.team_name)
70    }
71
72    /// The entry's total, or `None` while the picks stay hidden.
73    pub fn total_str(&self) -> Option<String> {
74        self.picks.as_ref().and_then(|p| p.total_str())
75    }
76
77    /// The rank as `"3"`, or `None` before results.
78    pub fn rank_str(&self) -> Option<String> {
79        self.rank.map(|r| r.to_string())
80    }
81}
82
83pub struct ScoreMeta {
84    pub coverage: Coverage,
85    pub events_url: Option<String>,
86    pub active: bool,
87    pub delayed: bool,
88    pub official: bool,
89}
90
91fn score_meta(
92    source: &ContestScores,
93    lineup: &Lineup,
94    entry_id: EntryId,
95    now: OffsetDateTime,
96    stream_eligible: bool,
97) -> ScoreMeta {
98    match source {
99        ContestScores::Official(_) => ScoreMeta {
100            coverage: Coverage::Complete,
101            events_url: None,
102            active: false,
103            delayed: false,
104            official: true,
105        },
106        ContestScores::Provisional(snapshot) => {
107            let total = live::score_live_lineup(lineup, snapshot, now);
108            let delayed = snapshot.is_delayed(now);
109            ScoreMeta {
110                coverage: total.coverage,
111                events_url: stream_eligible.then(|| format!("/entries/{}/events", entry_id.0)),
112                active: snapshot.has_active_game(),
113                delayed,
114                official: false,
115            }
116        }
117        ContestScores::Upcoming => ScoreMeta {
118            coverage: Coverage::Unavailable,
119            events_url: None,
120            active: false,
121            delayed: false,
122            official: false,
123        },
124        ContestScores::Unavailable => ScoreMeta {
125            coverage: Coverage::Unavailable,
126            events_url: stream_eligible.then(|| format!("/entries/{}/events", entry_id.0)),
127            active: false,
128            delayed: true,
129            official: false,
130        },
131    }
132}
133/// The nine scored lineup rows and their total.
134pub struct Picks {
135    pub rows: Vec<SlotRow>,
136    total: Option<f64>,
137}
138
139impl Picks {
140    /// The entry's total as `"20.00"`.
141    pub fn total_str(&self) -> Option<String> {
142        self.total.map(scoring::format_points)
143    }
144}
145
146/// The game-score line for a row: both teams with their (optional) scores and
147/// which side is the pick's team, for bolding.
148pub struct GameLine {
149    pub away: String,
150    pub away_score: Option<i32>,
151    pub home: String,
152    pub home_score: Option<i32>,
153    pub home_is_pick: bool,
154}
155
156impl GameLine {
157    /// `"BUF 13"`, or `"BUF"` before the game has a score.
158    pub fn away_str(&self) -> String {
159        side_str(&self.away, self.away_score)
160    }
161    pub fn home_str(&self) -> String {
162        side_str(&self.home, self.home_score)
163    }
164}
165
166fn side_str(team: &str, score: Option<i32>) -> String {
167    match score {
168        Some(s) => format!("{team} {s}"),
169        None => team.to_string(),
170    }
171}
172
173/// The slate game the given team plays in, as a display line. `None` when no
174/// slate game features the team — the row falls back to its matchup text.
175pub fn game_line(slate: &[Game], team: &str) -> Option<GameLine> {
176    slate
177        .iter()
178        .find(|g| g.home_team.as_str() == team || g.away_team.as_str() == team)
179        .map(|g| GameLine {
180            away: g.away_team.as_str().to_owned(),
181            away_score: g.away_score,
182            home: g.home_team.as_str().to_owned(),
183            home_score: g.home_score,
184            home_is_pick: g.home_team.as_str() == team,
185        })
186}
187
188/// How a row shows its subject: a player photo, a DST team logo, or the
189/// silhouette placeholder when a player has no photo.
190enum Avatar {
191    Headshot(String),
192    TeamLogo(String),
193    Silhouette,
194}
195
196impl Avatar {
197    fn url(&self) -> String {
198        match self {
199            Avatar::Headshot(url) | Avatar::TeamLogo(url) => assets::versioned(url),
200            Avatar::Silhouette => assets::versioned(SILHOUETTE),
201        }
202    }
203}
204
205pub(crate) const SILHOUETTE: &str = "/static/img/headshot-placeholder.svg";
206
207/// The salary cap for a nine-slot FanDuel-style lineup.
208pub const SALARY_CAP: i64 = 60_000;
209
210/// The placeholder image for a row with no avatar.
211pub(crate) fn silhouette_url() -> String {
212    assets::versioned(SILHOUETTE)
213}
214
215pub struct PickInfo {
216    salaried: SalariedPlayer,
217    avatar: Avatar,
218}
219
220impl PickInfo {
221    pub(crate) fn new(salaried: SalariedPlayer, media: Option<&Media>) -> Self {
222        let avatar = if salaried.position.is_defense() {
223            Avatar::TeamLogo(media.map_or_else(|| SILHOUETTE.to_string(), |media| media.url()))
224        } else {
225            match media {
226                Some(media) => Avatar::Headshot(media.url()),
227                None => Avatar::Silhouette,
228            }
229        };
230        Self { salaried, avatar }
231    }
232
233    pub fn injury(&self) -> Option<InjuryChip> {
234        self.salaried.injury.map(injuries::chip)
235    }
236
237    pub fn name(&self) -> &str {
238        &self.salaried.name
239    }
240
241    /// The pick's price for the slate.
242    pub fn salary(&self) -> i64 {
243        i64::from(self.salaried.salary)
244    }
245
246    /// The pick's game with scores stripped: nothing has been played from the
247    /// editor's or preview's point of view.
248    pub fn game(&self) -> GameLine {
249        let game = &self.salaried.game;
250        GameLine {
251            away: game.away_team.as_str().to_owned(),
252            away_score: None,
253            home: game.home_team.as_str().to_owned(),
254            home_score: None,
255            home_is_pick: game.home_team == self.salaried.team,
256        }
257    }
258
259    /// `"Sun 11/23 1:00pm"` Eastern, `None` while the game has no kickoff time.
260    pub fn kickoff(&self) -> Option<String> {
261        self.salaried.game.kickoff_eastern().map(short_kickoff)
262    }
263
264    /// The compact row name; DST names return unchanged.
265    pub fn abbreviated_name(&self) -> String {
266        if self.is_dst() {
267            self.name().to_owned()
268        } else {
269            abbreviated_name(self.name())
270        }
271    }
272
273    /// Whether the name exceeds the content heuristic for a row.
274    pub fn is_long_name(&self) -> bool {
275        is_long_name(self.name())
276    }
277
278    /// The row's image source.
279    pub fn avatar_url(&self) -> String {
280        self.avatar.url()
281    }
282
283    /// A team logo sits contained and padded; a photo fills the cell.
284    pub fn avatar_is_logo(&self) -> bool {
285        matches!(self.avatar, Avatar::TeamLogo(_))
286    }
287
288    /// Whether this pick represents a DST.
289    pub fn is_dst(&self) -> bool {
290        self.avatar_is_logo()
291    }
292
293    /// `"$5,700"` for the pick's slate price.
294    pub fn salary_str(&self) -> String {
295        format!("${}", scoring::format_thousands(self.salary()))
296    }
297
298    /// The picker's position caption: `"QB"`, `"DST"`, ...
299    pub fn badge(&self) -> String {
300        String::from(self.salaried.position)
301    }
302
303    /// What the picker submits for this pick.
304    pub fn value(&self) -> PlayerOrDefenseId {
305        match self.salaried.id.as_ref() {
306            Some(id) => PlayerOrDefenseId::Player(id.clone()),
307            None => PlayerOrDefenseId::Defense(self.salaried.team),
308        }
309    }
310
311    /// `"18.4"` for the info column.
312    pub fn fppg_str(&self) -> String {
313        format!("{:.1}", self.salaried.fppg)
314    }
315
316    /// `"10"` for the info column.
317    pub fn played_str(&self) -> String {
318        self.salaried.games_played.to_string()
319    }
320}
321
322/// The transient direction of a changed displayed score.
323#[derive(Clone, Copy, PartialEq, Eq)]
324enum ScoreDirection {
325    Increase,
326    Decrease,
327}
328
329/// One lineup row: a slot label, who filled it, and how they scored.
330pub struct SlotRow {
331    pub slot: &'static str,
332    dom_id: &'static str,
333    pub name: String,
334    avatar: Avatar,
335    team: Option<String>,
336    kickoff: Option<String>,
337    opponent: Option<String>,
338    game: Option<GameLine>,
339    /// The collapsed row's headline box score — position-specific for a
340    /// player (passing / rushing / receiving), the defensive line for a DST.
341    top_stats: String,
342    score: Score,
343    points: Option<f64>,
344    score_direction: Option<ScoreDirection>,
345    score_delta: Option<f64>,
346    pub coverage: Coverage,
347    pub phase: Option<LiveGamePhase>,
348    pub period: Option<String>,
349    pub clock: Option<String>,
350    pub stale: bool,
351    salary: Option<i64>,
352    ownership: Option<f64>,
353    injury: Option<InjuryDesignation>,
354}
355
356impl SlotRow {
357    pub fn name(&self) -> &str {
358        &self.name
359    }
360
361    pub fn dom_id(&self) -> String {
362        self.dom_id.to_owned()
363    }
364
365    pub fn injury(&self) -> Option<InjuryChip> {
366        self.injury.map(injuries::chip)
367    }
368
369    /// The compact row name; DST names return unchanged.
370    pub fn abbreviated_name(&self) -> String {
371        if self.slot == RosterSlot::Def.position_label() {
372            self.name.clone()
373        } else {
374            abbreviated_name(&self.name)
375        }
376    }
377
378    /// Whether the name exceeds the content heuristic for a row.
379    pub fn is_long_name(&self) -> bool {
380        is_long_name(&self.name)
381    }
382
383    /// The row's image source.
384    pub fn avatar_url(&self) -> String {
385        self.avatar.url()
386    }
387
388    /// A team logo sits contained and padded; a photo fills the cell.
389    pub fn avatar_is_logo(&self) -> bool {
390        matches!(self.avatar, Avatar::TeamLogo(_))
391    }
392
393    pub fn game(&self) -> Option<&GameLine> {
394        self.game.as_ref()
395    }
396
397    /// `"KC vs BUF"`, `"KC"`, or `"—"` — the fallback when no slate game
398    /// features the team.
399    pub fn matchup_str(&self) -> String {
400        match (&self.team, &self.opponent) {
401            (Some(t), Some(o)) => format!("{t} vs {o}"),
402            (Some(t), None) => t.clone(),
403            (None, _) => "—".into(),
404        }
405    }
406
407    /// The collapsed row's headline box score.
408    pub fn top_stats(&self) -> &str {
409        &self.top_stats
410    }
411
412    /// The compact fantasy-scoring line.
413    pub fn stat_line_str(&self) -> String {
414        or_dash(self.score.stat_line())
415    }
416
417    /// The per-stat scoring lines, for the expand panel.
418    pub fn breakdown(&self) -> &[ScoreLine] {
419        &self.score.lines
420    }
421
422    fn points_parts(&self) -> (String, String) {
423        let Some(points) = self.points else {
424            return (String::new(), String::new());
425        };
426        let formatted = scoring::format_points(points);
427        let (whole, dec) = formatted.rsplit_once('.').expect("format_points is n.nn");
428        (whole.to_string(), format!(".{dec}"))
429    }
430
431    pub fn points_whole(&self) -> String {
432        self.points_parts().0
433    }
434
435    pub fn points_dec(&self) -> String {
436        self.points_parts().1
437    }
438
439    pub fn has_points(&self) -> bool {
440        self.points.is_some()
441    }
442
443    pub fn score_increased(&self) -> bool {
444        self.score_direction == Some(ScoreDirection::Increase)
445    }
446
447    pub fn score_decreased(&self) -> bool {
448        self.score_direction == Some(ScoreDirection::Decrease)
449    }
450
451    /// The flash class a changed score carries on both score spans:
452    /// `" score-flash-increase"`, `" score-flash-decrease"`, or `""`.
453    pub fn score_flash_class(&self) -> &'static str {
454        if self.score_increased() {
455            " score-flash-increase"
456        } else if self.score_decreased() {
457            " score-flash-decrease"
458        } else {
459            ""
460        }
461    }
462
463    /// The changed-frame delta under the score: `"+2.00"`, `"-1.75"`, or `""`.
464    pub fn score_delta(&self) -> String {
465        self.score_delta.map_or_else(String::new, |delta| {
466            let formatted = scoring::format_points(delta);
467            if formatted.starts_with('-') {
468                formatted
469            } else {
470                format!("+{formatted}")
471            }
472        })
473    }
474
475    pub fn salary_str(&self) -> String {
476        match self.salary {
477            Some(v) => format!("${}", scoring::format_thousands(v)),
478            None => "—".into(),
479        }
480    }
481
482    pub fn ownership_str(&self) -> String {
483        match self.ownership {
484            Some(f) => format!("{:.1}%", f * 100.0),
485            None => "—".into(),
486        }
487    }
488
489    pub fn status(&self) -> &str {
490        if self.coverage == Coverage::Unavailable {
491            "Awaiting stats"
492        } else if self.stale {
493            "Updates delayed"
494        } else if self.coverage == Coverage::Partial {
495            "Points allowed pending"
496        } else if self.phase == Some(LiveGamePhase::Scheduled) {
497            self.kickoff.as_deref().unwrap_or("Upcoming")
498        } else {
499            ""
500        }
501    }
502
503    pub fn period_clock(&self) -> Option<String> {
504        match (&self.period, &self.clock) {
505            (Some(period), Some(clock)) => {
506                let period = period
507                    .parse::<u8>()
508                    .map(|period| format!("Q{period}"))
509                    .unwrap_or_else(|_| period.clone());
510                Some(format!("{period} · {clock}"))
511            }
512            (Some(period), None) => Some(period.clone()),
513            (None, Some(clock)) => Some(clock.clone()),
514            (None, None) => None,
515        }
516    }
517
518    pub fn has_status(&self) -> bool {
519        !self.status().is_empty()
520    }
521}
522
523/// An empty display string reads as a dash, never as a blank cell.
524fn or_dash(s: String) -> String {
525    if s.is_empty() { "—".into() } else { s }
526}
527
528/// Whether a pick shows the passing box score. The player's true position
529/// wins, so a FLEX resolves to what the player actually is. An unknown
530/// position falls back to the slot.
531fn is_passing(slot: RosterSlot, position: Option<&str>) -> bool {
532    match position.map(str::to_ascii_uppercase).as_deref() {
533        Some("QB") => true,
534        Some(_) => false,
535        None => slot == RosterSlot::Qb,
536    }
537}
538
539/// A player's headline box score. A QB shows `C/A, YDS, TD, INT`; every other
540/// player shows a combined rushing and receiving line with one total-touchdown
541/// count. A zero TD or INT count is dropped, matching the source screens.
542fn top_stats_line(slot: RosterSlot, position: Option<&str>, stats: &NflPlayerWeekStats) -> String {
543    if is_passing(slot, position) {
544        // Weeks ingested before completions and attempts existed report zero
545        // for both, so lead with the yards rather than a false "0/0".
546        let mut line = if stats.attempts > 0 {
547            format!(
548                "{}/{}, {} YDS",
549                stats.completions, stats.attempts, stats.passing_yards
550            )
551        } else {
552            format!("{} YDS", stats.passing_yards)
553        };
554        if stats.passing_tds > 0 {
555            line.push_str(&format!(", {} TD", stats.passing_tds));
556        }
557        if stats.passing_interceptions > 0 {
558            line.push_str(&format!(", {} INT", stats.passing_interceptions));
559        }
560        return line;
561    }
562
563    let receiving = || format!("{} REC, {} YDS", stats.receptions, stats.receiving_yards);
564    let tds = stats.rushing_tds
565        + stats.receiving_tds
566        + stats.special_teams_tds
567        + stats.fumble_recovery_tds;
568
569    let mut parts = Vec::new();
570    if stats.rushing_attempts > 0 || stats.rushing_yards != 0 {
571        parts.push(format!(
572            "{} CAR, {} YDS",
573            stats.rushing_attempts, stats.rushing_yards
574        ));
575    }
576    if stats.receptions > 0 || stats.receiving_yards != 0 {
577        parts.push(receiving());
578    }
579    if tds > 0 {
580        parts.push(format!("{tds} TD"));
581    }
582    if parts.is_empty() {
583        // Played, but recorded no rushing or receiving production.
584        parts.push(receiving());
585    }
586    parts.join(", ")
587}
588
589#[derive(Clone, Copy)]
590pub enum PickStats<'a> {
591    Raw(&'a WeekStats),
592    Stored {
593        snapshot: &'a Snapshot,
594        slate_id: SlateId,
595    },
596}
597
598#[derive(Default)]
599struct PickFacts {
600    team: Option<TeamAbbr>,
601    opponent: Option<TeamAbbr>,
602    top_stats: String,
603    score: Score,
604    // Distinguish a missing DST attachment from one with an empty scoring line.
605    present: bool,
606}
607
608fn player_facts(
609    stats: PickStats<'_>,
610    slot: RosterSlot,
611    id: &NflPlayerId,
612    position: Option<&str>,
613) -> PickFacts {
614    match stats {
615        PickStats::Raw(week) => match week.players.get(id) {
616            Some(row) => PickFacts {
617                team: Some(row.team),
618                opponent: row.opponent,
619                top_stats: top_stats_line(slot, position, row),
620                score: nfl_scoring::score_player(row),
621                present: true,
622            },
623            None => PickFacts::default(),
624        },
625        PickStats::Stored { snapshot, slate_id } => {
626            let value = PlayerOrDefenseId::Player(id.clone());
627            match stored_week(snapshot, slate_id, &value) {
628                Some((WeeklyStats::Player(row), score)) => PickFacts {
629                    team: Some(row.team),
630                    opponent: row.opponent,
631                    top_stats: top_stats_line(slot, position, row),
632                    score: score.clone(),
633                    present: true,
634                },
635                _ => PickFacts::default(),
636            }
637        }
638    }
639}
640
641fn defense_facts(stats: PickStats<'_>, team: TeamAbbr) -> PickFacts {
642    match stats {
643        PickStats::Raw(week) => match week.defenses.get(&team) {
644            Some(row) => PickFacts {
645                team: Some(row.team),
646                opponent: Some(row.opponent),
647                top_stats: String::new(),
648                score: nfl_scoring::score_defense(row),
649                present: true,
650            },
651            None => PickFacts::default(),
652        },
653        PickStats::Stored { snapshot, slate_id } => {
654            let value = PlayerOrDefenseId::Defense(team);
655            match stored_week(snapshot, slate_id, &value) {
656                Some((WeeklyStats::Defense(row), score)) => PickFacts {
657                    team: Some(row.team),
658                    opponent: Some(row.opponent),
659                    top_stats: String::new(),
660                    score: score.clone(),
661                    present: true,
662                },
663                _ => PickFacts::default(),
664            }
665        }
666    }
667}
668
669fn stored_week<'a>(
670    snapshot: &'a Snapshot,
671    slate_id: SlateId,
672    value: &PlayerOrDefenseId,
673) -> Option<(&'a WeeklyStats, &'a Score)> {
674    let scored = snapshot
675        .salaried_player(&slate_id, value)?
676        .scored_stats
677        .as_ref()?;
678    Some((&scored.stats, &scored.score))
679}
680
681#[allow(clippy::too_many_arguments)]
682pub fn build_picks<'a>(
683    lineup: &Lineup,
684    names: &HashMap<NflPlayerId, PlayerIdentity>,
685    stats: PickStats<'_>,
686    slate: &[Game],
687    salaried: impl Fn(&PlayerOrDefenseId) -> Option<&'a SalariedPlayer>,
688    ownership: &Ownership,
689    avatars: &Avatars,
690) -> Picks {
691    let mut rows: Vec<SlotRow> = lineup
692        .player_slots()
693        .into_iter()
694        .map(|(slot, id)| {
695            let known = names.get(id);
696            let facts = player_facts(stats, slot, id, known.and_then(|k| k.position.as_deref()));
697            let team = facts
698                .team
699                .map(|team| team.as_str().to_owned())
700                .or_else(|| known.and_then(|k| k.team.as_ref().map(|t| t.as_str().to_owned())));
701            let value = PlayerOrDefenseId::Player(id.clone());
702            let avatar = match avatars.get(&value) {
703                Some(media) => Avatar::Headshot(media.url()),
704                None => Avatar::Silhouette,
705            };
706            let points = Some(facts.score.total);
707            let row = salaried(&value);
708            SlotRow {
709                slot: slot.position_label(),
710                dom_id: slot.dom_id(),
711                name: known.map_or_else(|| id.as_ref().to_string(), |k| k.name.clone()),
712                avatar,
713                team: team.clone(),
714                kickoff: team.as_deref().and_then(|team| team_kickoff(slate, team)),
715                opponent: facts.opponent.map(|opponent| opponent.as_str().to_owned()),
716                game: team.as_deref().and_then(|t| game_line(slate, t)),
717                top_stats: facts.top_stats,
718                score: facts.score,
719                points,
720                score_direction: None,
721                score_delta: None,
722                coverage: Coverage::Complete,
723                phase: None,
724                period: None,
725                clock: None,
726                stale: false,
727                salary: row.map(|row| i64::from(row.salary)),
728                ownership: ownership.player(id),
729                injury: row.and_then(|row| row.injury),
730            }
731        })
732        .collect();
733
734    let facts = defense_facts(stats, lineup.def);
735    let def_team = lineup.def.as_str().to_owned();
736    let defense_id = PlayerOrDefenseId::Defense(lineup.def);
737    let top_stats = if facts.present {
738        or_dash(facts.score.stat_line())
739    } else {
740        String::new()
741    };
742    let points = Some(facts.score.total);
743    let row = salaried(&defense_id);
744    rows.push(SlotRow {
745        slot: RosterSlot::Def.position_label(),
746        dom_id: RosterSlot::Def.dom_id(),
747        name: format!("{def_team} DST"),
748        avatar: Avatar::TeamLogo(
749            avatars
750                .get(&defense_id)
751                .map_or_else(|| SILHOUETTE.to_string(), |media| media.url()),
752        ),
753        team: Some(def_team.clone()),
754        kickoff: team_kickoff(slate, &def_team),
755        opponent: facts.opponent.map(|opponent| opponent.as_str().to_owned()),
756        game: game_line(slate, &def_team),
757        top_stats,
758        score: facts.score,
759        points,
760        score_direction: None,
761        score_delta: None,
762        coverage: Coverage::Complete,
763        phase: None,
764        period: None,
765        clock: None,
766        stale: false,
767        salary: row.map(|row| i64::from(row.salary)),
768        ownership: ownership.defense(&lineup.def),
769        injury: row.and_then(|row| row.injury),
770    });
771
772    let total = Some(rows.iter().map(|r| r.points.unwrap_or_default()).sum());
773    Picks { rows, total }
774}
775
776pub(crate) fn apply_live_snapshot(
777    picks: &mut Picks,
778    lineup: &Lineup,
779    snapshot: &LiveContestSnapshot,
780    now: OffsetDateTime,
781) {
782    for ((slot, _), row) in lineup.player_slots().into_iter().zip(picks.rows.iter_mut()) {
783        apply_live_row(row, slot, lineup, snapshot, now);
784    }
785    if let Some(row) = picks.rows.last_mut() {
786        apply_live_row(row, RosterSlot::Def, lineup, snapshot, now);
787    }
788    picks.total = live::score_live_lineup(lineup, snapshot, now).points;
789}
790
791fn apply_live_row(
792    row: &mut SlotRow,
793    slot: RosterSlot,
794    lineup: &Lineup,
795    snapshot: &LiveContestSnapshot,
796    now: OffsetDateTime,
797) {
798    let status = live::score_live_slot(lineup, slot, snapshot, now);
799    row.points = if status.phase == Some(LiveGamePhase::Scheduled) {
800        None
801    } else {
802        status.total.points
803    };
804    row.coverage = status.total.coverage;
805    row.phase = status.phase;
806    row.period = status.period;
807    row.clock = status.clock;
808    row.stale = status.stale;
809    if status.total.points.is_none() {
810        row.score = Score::default();
811        row.top_stats = "Awaiting stats".into();
812    } else if status.phase == Some(LiveGamePhase::Scheduled) {
813        row.score = Score::default();
814        row.top_stats = String::new();
815    } else if slot == RosterSlot::Def
816        && row.coverage == Coverage::Partial
817        && let Some(stats) = snapshot.game_for_team(&lineup.def).and_then(|state| {
818            state
819                .defenses
820                .get(&crate::player_identity::canonical_team(&lineup.def))
821        })
822    {
823        row.opponent = Some(stats.opponent.as_str().to_owned());
824        row.score = nfl_scoring::score_live_defense(stats);
825        row.top_stats = or_dash(row.score.stat_line());
826    }
827}
828
829pub(crate) fn update_score_directions(
830    page: &mut EntryPage,
831    previous: &mut HashMap<&'static str, f64>,
832) {
833    let Some(picks) = page.picks.as_mut() else {
834        previous.clear();
835        return;
836    };
837
838    for row in &mut picks.rows {
839        let outcome = match row.points {
840            Some(current) => previous.insert(row.dom_id, current).and_then(|old| {
841                score_direction(old, current).map(|direction| (direction, current - old))
842            }),
843            None => {
844                previous.remove(row.dom_id);
845                None
846            }
847        };
848        (row.score_direction, row.score_delta) = outcome
849            .map_or((None, None), |(direction, delta)| {
850                (Some(direction), Some(delta))
851            });
852    }
853}
854
855fn score_direction(previous: f64, current: f64) -> Option<ScoreDirection> {
856    if scoring::ties(previous, current) {
857        None
858    } else if current > previous {
859        Some(ScoreDirection::Increase)
860    } else {
861        Some(ScoreDirection::Decrease)
862    }
863}
864
865fn clear_live_scores(picks: &mut Picks) {
866    for row in &mut picks.rows {
867        row.score = Score::default();
868        row.points = None;
869        row.score_direction = None;
870        row.score_delta = None;
871        row.coverage = Coverage::Unavailable;
872        row.phase = None;
873        row.period = None;
874        row.clock = None;
875        row.stale = false;
876        row.top_stats = "Awaiting stats".into();
877    }
878    picks.total = None;
879}
880
881/// The owner's pre-kickoff lineup review: the scored page's skeleton carrying
882/// what matters before play — salaries and the slate schedule.
883pub struct EntryPreview {
884    pub team_name: String,
885    pub owner_name: String,
886    pub logo_url: Option<String>,
887    pub contest_id: SlateId,
888    /// Names the page: "Week 12 Lineup".
889    pub contest_name: String,
890    pub rows: Vec<PreviewRow>,
891    spent: i64,
892}
893
894impl EntryPreview {
895    /// Up to two initials from the fantasy team name, for the logo fallback.
896    pub fn monogram(&self) -> String {
897        fantasy_teams_module::monogram(&self.team_name)
898    }
899
900    /// What the lineup left under the cap, `"$600"`.
901    pub fn remaining_str(&self) -> String {
902        format!("${}", scoring::format_thousands(SALARY_CAP - self.spent))
903    }
904}
905
906/// One preview row: the slot and who fills it, `None` when the slate has no
907/// priced row for the pick.
908pub struct PreviewRow {
909    pub slot: &'static str,
910    pub info: Option<PickInfo>,
911}
912
913/// Preview rows in roster order, plus the total salary spent. Game scores are
914/// stripped: nothing has been played from this entry's point of view.
915pub fn build_preview(
916    lineup: &Lineup,
917    player: impl Fn(&NflPlayerId) -> Option<SalariedPlayer>,
918    defense: impl Fn(&TeamAbbr) -> Option<SalariedPlayer>,
919    avatars: &Avatars,
920) -> (Vec<PreviewRow>, i64) {
921    let mut rows: Vec<PreviewRow> = lineup
922        .player_slots()
923        .into_iter()
924        .map(|(slot, id)| PreviewRow {
925            slot: slot.position_label(),
926            info: player(id).map(|salaried| {
927                PickInfo::new(
928                    salaried,
929                    avatars.get(&PlayerOrDefenseId::Player(id.clone())),
930                )
931            }),
932        })
933        .collect();
934
935    rows.push(PreviewRow {
936        slot: RosterSlot::Def.position_label(),
937        info: defense(&lineup.def).map(|salaried| {
938            PickInfo::new(
939                salaried,
940                avatars.get(&PlayerOrDefenseId::Defense(lineup.def)),
941            )
942        }),
943    });
944
945    let spent = rows
946        .iter()
947        .filter_map(|row| row.info.as_ref())
948        .map(PickInfo::salary)
949        .sum();
950    (rows, spent)
951}
952
953/// A content heuristic for long names; CSS handles narrow containers.
954pub(crate) const LONG_NAME_CHARS: usize = 15;
955
956/// A player name with its first word abbreviated when it has a surname.
957/// Already-initialized first tokens pass through unchanged. Two-character first
958/// names are also kept intact. Everything after the first word is kept, so
959/// compound last names survive; a single-word name passes through.
960pub(crate) fn abbreviated_name(name: &str) -> String {
961    match name.split_once(' ') {
962        Some((first, _)) if first.contains('.') || first.chars().count() == 2 => name.to_string(),
963        Some((first, rest)) if !rest.is_empty() => match first.chars().next() {
964            Some(initial) => format!("{initial}. {rest}"),
965            None => name.to_string(),
966        },
967        _ => name.to_string(),
968    }
969}
970
971/// Whether a name exceeds the content-length heuristic for a row.
972pub(crate) fn is_long_name(name: &str) -> bool {
973    name.chars().count() > LONG_NAME_CHARS
974}
975
976/// `game_line` with any scores stripped, for pre-kickoff pages: replayed dev
977/// data may already carry them, but nothing has been played yet.
978/// The team's slate kickoff as `"Sun 11/23 1:00pm"` Eastern, `None` while
979/// unscheduled.
980pub(crate) fn team_kickoff(slate: &[Game], team: &str) -> Option<String> {
981    slate
982        .iter()
983        .find(|g| g.home_team.as_str() == team || g.away_team.as_str() == team)
984        .and_then(|g| g.kickoff_eastern())
985        .map(short_kickoff)
986}
987
988/// `"Sun 11/23 1:00pm"`, in the offset `et` carries (callers pass Eastern).
989fn short_kickoff(et: OffsetDateTime) -> String {
990    use time::macros::format_description;
991    et.format(format_description!(
992        "[weekday repr:short] [month padding:none]/[day padding:none] [hour repr:12 padding:none]:[minute][period case:lower]"
993    ))
994    .unwrap_or_default()
995}
996
997/// Roster ownership across a contest's lineups: the fraction of lineups that
998/// include each player and each team defense.
999#[derive(Default)]
1000pub struct Ownership {
1001    shares: HashMap<PlayerOrDefenseId, f64>,
1002}
1003
1004impl Ownership {
1005    pub fn player(&self, id: &NflPlayerId) -> Option<f64> {
1006        self.shares
1007            .get(&PlayerOrDefenseId::Player(id.clone()))
1008            .copied()
1009    }
1010    pub fn defense(&self, team: &TeamAbbr) -> Option<f64> {
1011        self.shares.get(&PlayerOrDefenseId::Defense(*team)).copied()
1012    }
1013}
1014
1015/// Count each pick across all lineups and divide by the lineup count.
1016pub fn compute_ownership<'a>(lineups: impl IntoIterator<Item = &'a Lineup>) -> Ownership {
1017    let mut total = 0.0;
1018    let mut counts: HashMap<PlayerOrDefenseId, u32> = HashMap::new();
1019    for lineup in lineups {
1020        total += 1.0;
1021        for id in lineup.player_ids() {
1022            *counts
1023                .entry(PlayerOrDefenseId::Player(id.clone()))
1024                .or_insert(0) += 1;
1025        }
1026        *counts
1027            .entry(PlayerOrDefenseId::Defense(lineup.def))
1028            .or_insert(0) += 1;
1029    }
1030    let frac = |c: u32| c as f64 / total;
1031    Ownership {
1032        shares: counts
1033            .into_iter()
1034            .map(|(value, count)| (value, frac(count)))
1035            .collect(),
1036    }
1037}
1038pub async fn page(state: &AppState, viewer: &User, id: EntryId) -> Result<EntryView, AppError> {
1039    let reader = state.db.reader();
1040    let entry = store::by_id(reader, id).await?.ok_or(AppError::NotFound)?;
1041    fantasy_teams::team_for_user(reader, entry.league_id, viewer.id)
1042        .await?
1043        .ok_or(AppError::NotFound)?;
1044
1045    let snapshot_ref = state.nfl.snapshot();
1046    let slate = snapshot_ref
1047        .slate(&entry.slate_id)
1048        .ok_or(AppError::NotFound)?;
1049    let games = snapshot_ref.games_for_slate(&entry.slate_id);
1050    let contest_name = slate.name.clone();
1051    let now = state.now();
1052
1053    let is_owner = entry.team.user_id == viewer.id;
1054    let kicked_off = slate.locked(now);
1055
1056    if is_owner && !kicked_off {
1057        let values: Vec<PlayerOrDefenseId> = entry
1058            .lineup
1059            .to_slots()
1060            .into_iter()
1061            .map(|slot| slot.value)
1062            .collect();
1063        let avatars = avatars::by_id(&state.db, &values).await?;
1064        let (rows, spent) = build_preview(
1065            &entry.lineup,
1066            |id| snapshot_ref.player(&entry.slate_id, id).cloned(),
1067            |team| snapshot_ref.defense(&entry.slate_id, team).cloned(),
1068            &avatars,
1069        );
1070        return Ok(EntryView::Preview(EntryPreview {
1071            team_name: entry.team.name,
1072            owner_name: entry.team.owner_name,
1073            logo_url: entry.team.logo.map(|m| m.url()),
1074            contest_id: entry.slate_id,
1075            contest_name,
1076            rows,
1077            spent,
1078        }));
1079    }
1080
1081    let (picks, rank, score) = if kicked_off {
1082        let ids = entry.lineup.player_ids().map(Clone::clone);
1083        let source = live::load_contest_scores(state, entry.slate_id).await?;
1084        let stream_eligible = live::stream_eligible(state, entry.slate_id, &source).await?;
1085        let unsynced = WeekStats::default();
1086        // Keep official scores, games, and salaries on the same publication.
1087        let (stats, display_slate, roster) = match &source {
1088            ContestScores::Official(official) => (
1089                PickStats::Stored {
1090                    snapshot: official,
1091                    slate_id: entry.slate_id,
1092                },
1093                official.games_for_slate(&entry.slate_id).to_vec(),
1094                official.as_ref(),
1095            ),
1096            ContestScores::Provisional(snapshot) => (
1097                PickStats::Raw(&snapshot.stats),
1098                snapshot.scored_games(),
1099                snapshot_ref.as_ref(),
1100            ),
1101            ContestScores::Upcoming | ContestScores::Unavailable => (
1102                PickStats::Raw(&unsynced),
1103                games.to_vec(),
1104                snapshot_ref.as_ref(),
1105            ),
1106        };
1107        let names = state.nfl.identify(&ids).await?;
1108        let values: Vec<PlayerOrDefenseId> = entry
1109            .lineup
1110            .to_slots()
1111            .into_iter()
1112            .map(|slot| slot.value)
1113            .collect();
1114        let avatars = avatars::by_id(&state.db, &values).await?;
1115        let contest_entries = store::by_contest(reader, entry.slate_id, entry.league_id).await?;
1116
1117        let ownership = compute_ownership(contest_entries.iter().map(|e| &e.lineup));
1118
1119        let rank = match &source {
1120            ContestScores::Official(official) => {
1121                contests::rank_contest_entries(contests::entrants(&contest_entries, |lineup| {
1122                    Some(scoring_service::lineup_total(
1123                        lineup,
1124                        official,
1125                        entry.slate_id,
1126                    ))
1127                }))
1128                .into_iter()
1129                .find(|row| row.id == id)
1130                .and_then(|row| row.rank)
1131            }
1132            ContestScores::Provisional(snapshot) => {
1133                contests::rank_live_entries(&contest_entries, snapshot, now)
1134                    .into_iter()
1135                    .find(|row| row.id == id)
1136                    .and_then(|row| row.rank)
1137            }
1138            ContestScores::Upcoming | ContestScores::Unavailable => None,
1139        };
1140
1141        let mut picks = build_picks(
1142            &entry.lineup,
1143            &names,
1144            stats,
1145            &display_slate,
1146            |value| roster.salaried_player(&entry.slate_id, value),
1147            &ownership,
1148            &avatars,
1149        );
1150        match &source {
1151            ContestScores::Provisional(snapshot) => {
1152                apply_live_snapshot(&mut picks, &entry.lineup, snapshot, now);
1153            }
1154            ContestScores::Unavailable => clear_live_scores(&mut picks),
1155            ContestScores::Official(_) | ContestScores::Upcoming => {}
1156        }
1157        let score = score_meta(&source, &entry.lineup, id, now, stream_eligible);
1158        (Some(picks), rank, score)
1159    } else {
1160        (
1161            None,
1162            None,
1163            ScoreMeta {
1164                coverage: Coverage::Unavailable,
1165                events_url: None,
1166                active: false,
1167                delayed: false,
1168                official: false,
1169            },
1170        )
1171    };
1172
1173    Ok(EntryView::Scored(EntryPage {
1174        team_name: entry.team.name,
1175        owner_name: entry.team.owner_name,
1176        logo_url: entry.team.logo.map(|m| m.url()),
1177        contest_id: entry.slate_id,
1178        contest_name,
1179        rank,
1180        score,
1181        picks,
1182    }))
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    use super::*;
1188    use crate::tests::factories;
1189    use nfl_data::{
1190        Game, PlayerWeekStats as NflPlayerWeekStats, TeamAbbr, TeamWeekStats as NflTeamWeekStats,
1191    };
1192
1193    fn lineup() -> Lineup {
1194        Lineup {
1195            qb: NflPlayerId("00-QB".into()),
1196            rb1: NflPlayerId("00-RB1".into()),
1197            rb2: NflPlayerId("00-RB2".into()),
1198            wr1: NflPlayerId("00-WR1".into()),
1199            wr2: NflPlayerId("00-WR2".into()),
1200            wr3: NflPlayerId("00-WR3".into()),
1201            te: NflPlayerId("00-TE".into()),
1202            flex: NflPlayerId("00-FLEX".into()),
1203            def: TeamAbbr::KC,
1204        }
1205    }
1206
1207    /// Every pick named, each on KC.
1208    fn names() -> HashMap<NflPlayerId, PlayerIdentity> {
1209        [
1210            ("00-QB", "Quinn Back"),
1211            ("00-RB1", "Alpha Runner"),
1212            ("00-RB2", "Beta Runner"),
1213            ("00-WR1", "Wide One"),
1214            ("00-WR2", "Wide Two"),
1215            ("00-WR3", "Wide Three"),
1216            ("00-TE", "Tight End"),
1217            ("00-FLEX", "Flex Player"),
1218        ]
1219        .into_iter()
1220        .map(|(gsis, name)| {
1221            (
1222                NflPlayerId(gsis.to_string()),
1223                factories::identity(name, Some("KC")),
1224            )
1225        })
1226        .collect()
1227    }
1228
1229    /// RB1 with 100 rushing yards (13.00) and the KC defense allowing 3
1230    /// (7.00); every other slot has no stat row.
1231    fn week_stats() -> WeekStats {
1232        let rb = NflPlayerWeekStats {
1233            opponent: Some(TeamAbbr::BUF),
1234            ..factories::rb_stats("00-RB1", 1, 100)
1235        };
1236        let def = NflTeamWeekStats {
1237            points_allowed: 3,
1238            ..factories::defense_stats("KC", "LA", 1)
1239        };
1240        WeekStats {
1241            players: [(NflPlayerId("00-RB1".into()), rb)].into(),
1242            defenses: [(TeamAbbr::KC, def)].into(),
1243        }
1244    }
1245
1246    /// RB1's game (KC home vs BUF) with a final score.
1247    fn slate() -> Vec<Game> {
1248        vec![Game {
1249            home_score: Some(20),
1250            away_score: Some(13),
1251            ..factories::game("2025_01_BUF_KC", 1)
1252        }]
1253    }
1254
1255    /// The default page inputs, with each part overridable by a test.
1256    struct Fixture {
1257        names: HashMap<NflPlayerId, PlayerIdentity>,
1258        stats: WeekStats,
1259        ownership: Ownership,
1260    }
1261
1262    impl Default for Fixture {
1263        fn default() -> Fixture {
1264            Fixture {
1265                names: names(),
1266                stats: week_stats(),
1267                ownership: compute_ownership(&[lineup()]),
1268            }
1269        }
1270    }
1271
1272    impl Fixture {
1273        fn picks(&self) -> Picks {
1274            self.picks_with(&Avatars::default())
1275        }
1276
1277        fn picks_with(&self, avatars: &Avatars) -> Picks {
1278            build_picks(
1279                &lineup(),
1280                &self.names,
1281                PickStats::Raw(&self.stats),
1282                &slate(),
1283                |_| None,
1284                &self.ownership,
1285                avatars,
1286            )
1287        }
1288    }
1289
1290    /// The fixture's rows, for the tests that override nothing.
1291    fn picks() -> Picks {
1292        Fixture::default().picks()
1293    }
1294
1295    fn page_with_picks(picks: Option<Picks>) -> EntryPage {
1296        EntryPage {
1297            team_name: "Test Team".into(),
1298            owner_name: "Test Owner".into(),
1299            logo_url: None,
1300            contest_id: SlateId(20260011),
1301            contest_name: "Test Contest".into(),
1302            rank: None,
1303            score: ScoreMeta {
1304                coverage: Coverage::Complete,
1305                events_url: None,
1306                active: false,
1307                delayed: false,
1308                official: false,
1309            },
1310            picks,
1311        }
1312    }
1313
1314    #[test]
1315    fn scheduled_row_shows_kickoff_and_blank_score() {
1316        let mut picks = picks();
1317        let row = &mut picks.rows[0];
1318        row.kickoff = Some("Sun 9/7 1:00pm".into());
1319        row.coverage = Coverage::Complete;
1320        row.phase = Some(LiveGamePhase::Scheduled);
1321        row.points = None;
1322
1323        assert_eq!(row.status(), "Sun 9/7 1:00pm");
1324        assert!(row.has_status());
1325        assert_eq!(row.points_whole(), "");
1326        assert_eq!(row.points_dec(), "");
1327        assert!(!row.has_points());
1328
1329        row.kickoff = None;
1330        assert_eq!(row.status(), "Upcoming");
1331
1332        row.points = Some(0.0);
1333        row.phase = Some(LiveGamePhase::Final);
1334        assert!(row.has_points());
1335        assert_eq!(row.points_whole(), "0");
1336        assert_eq!(row.points_dec(), ".00");
1337    }
1338
1339    #[test]
1340    fn score_direction_uses_display_precision() {
1341        assert!(matches!(
1342            score_direction(10.00, 11.00),
1343            Some(ScoreDirection::Increase)
1344        ));
1345        assert!(matches!(
1346            score_direction(11.00, 10.00),
1347            Some(ScoreDirection::Decrease)
1348        ));
1349        assert!(score_direction(10.00, 10.00).is_none());
1350        assert!(score_direction(10.00, 10.004).is_none());
1351        assert!(score_direction(10.004, 10.00).is_none());
1352    }
1353
1354    #[test]
1355    fn score_delta_formats_signs_rounding_and_dash() {
1356        let mut picks = picks();
1357        let row = &mut picks.rows[0];
1358        assert_eq!(row.score_delta(), "");
1359        row.score_delta = Some(2.0);
1360        assert_eq!(row.score_delta(), "+2.00");
1361        row.score_delta = Some(-1.75);
1362        assert_eq!(row.score_delta(), "-1.75");
1363        row.score_delta = Some(1.236);
1364        assert_eq!(row.score_delta(), "+1.24");
1365    }
1366
1367    #[test]
1368    fn update_score_directions_tracks_numeric_rows_and_resets_missing_rows() {
1369        let mut page = page_with_picks(Some(picks()));
1370        let mut previous = HashMap::new();
1371
1372        update_score_directions(&mut page, &mut previous);
1373        assert!(
1374            page.picks
1375                .as_ref()
1376                .unwrap()
1377                .rows
1378                .iter()
1379                .all(|row| !row.score_increased() && !row.score_decreased())
1380        );
1381
1382        let picks = page.picks.as_mut().unwrap();
1383        picks.rows[1].points = Some(14.0);
1384        picks.rows[2].points = Some(0.004);
1385        update_score_directions(&mut page, &mut previous);
1386        let picks = page.picks.as_ref().unwrap();
1387        assert!(picks.rows[1].score_increased());
1388        assert_eq!(picks.rows[1].score_delta(), "+1.00");
1389        assert!(!picks.rows[2].score_increased());
1390        assert!(!picks.rows[2].score_decreased());
1391        assert_eq!(picks.rows[2].score_delta(), "");
1392
1393        page.picks.as_mut().unwrap().rows[1].points = Some(14.004);
1394        update_score_directions(&mut page, &mut previous);
1395        assert!(!page.picks.as_ref().unwrap().rows[1].score_increased());
1396        assert_eq!(page.picks.as_ref().unwrap().rows[1].score_delta(), "");
1397
1398        page.picks.as_mut().unwrap().rows[1].points = None;
1399        update_score_directions(&mut page, &mut previous);
1400        assert!(!previous.contains_key("rb1"));
1401        assert!(!page.picks.as_ref().unwrap().rows[1].score_increased());
1402        assert_eq!(page.picks.as_ref().unwrap().rows[1].score_delta(), "");
1403
1404        page.picks.as_mut().unwrap().rows[1].points = Some(15.0);
1405        update_score_directions(&mut page, &mut previous);
1406        assert!(!page.picks.as_ref().unwrap().rows[1].score_increased());
1407        assert_eq!(page.picks.as_ref().unwrap().rows[1].score_delta(), "");
1408
1409        page.picks = None;
1410        update_score_directions(&mut page, &mut previous);
1411        assert!(previous.is_empty());
1412    }
1413
1414    #[test]
1415    fn rows_preserve_roster_identity() {
1416        let picks = picks();
1417        let rows: Vec<(String, &str, &str)> = picks
1418            .rows
1419            .iter()
1420            .map(|r| (r.dom_id(), r.slot, r.name.as_str()))
1421            .collect();
1422        assert_eq!(
1423            rows,
1424            vec![
1425                ("qb".to_string(), "QB", "Quinn Back"),
1426                ("rb1".to_string(), "RB", "Alpha Runner"),
1427                ("rb2".to_string(), "RB", "Beta Runner"),
1428                ("wr1".to_string(), "WR", "Wide One"),
1429                ("wr2".to_string(), "WR", "Wide Two"),
1430                ("wr3".to_string(), "WR", "Wide Three"),
1431                ("te".to_string(), "TE", "Tight End"),
1432                ("flex".to_string(), "FLEX", "Flex Player"),
1433                ("def".to_string(), "DEF", "KC DST"),
1434            ]
1435        );
1436    }
1437
1438    #[test]
1439    fn missing_salary_and_ownership_render_a_dash() {
1440        let picks = Fixture {
1441            ownership: Ownership::default(),
1442            ..Fixture::default()
1443        }
1444        .picks();
1445        assert_eq!(picks.rows[0].salary_str(), "—");
1446        assert_eq!(picks.rows[0].ownership_str(), "—");
1447        assert_eq!(picks.rows[8].salary_str(), "—", "DST salary also dashes");
1448        assert_eq!(picks.rows[8].ownership_str(), "—");
1449    }
1450
1451    #[test]
1452    fn top_stats_line_is_position_specific() {
1453        use RosterSlot::*;
1454        let qb = NflPlayerWeekStats {
1455            completions: 26,
1456            attempts: 38,
1457            passing_yards: 182,
1458            passing_tds: 1,
1459            passing_interceptions: 1,
1460            ..factories::player_stats("00-QB", 1)
1461        };
1462        assert_eq!(
1463            top_stats_line(Qb, Some("QB"), &qb),
1464            "26/38, 182 YDS, 1 TD, 1 INT"
1465        );
1466
1467        let rb = NflPlayerWeekStats {
1468            rushing_attempts: 11,
1469            rushing_yards: 105,
1470            rushing_tds: 2,
1471            ..factories::player_stats("00-RB", 1)
1472        };
1473        assert_eq!(
1474            top_stats_line(Rb1, Some("RB"), &rb),
1475            "11 CAR, 105 YDS, 2 TD"
1476        );
1477
1478        // A pass-catching back shows both lines with one combined TD count.
1479        let dual = NflPlayerWeekStats {
1480            rushing_attempts: 11,
1481            rushing_yards: 105,
1482            rushing_tds: 1,
1483            receptions: 3,
1484            receiving_yards: 25,
1485            receiving_tds: 1,
1486            ..factories::player_stats("00-RB", 1)
1487        };
1488        assert_eq!(
1489            top_stats_line(Rb1, Some("RB"), &dual),
1490            "11 CAR, 105 YDS, 3 REC, 25 YDS, 2 TD"
1491        );
1492
1493        // A zero TD count is dropped.
1494        let rb_no_td = NflPlayerWeekStats {
1495            rushing_attempts: 14,
1496            rushing_yards: 43,
1497            ..factories::player_stats("00-RB", 1)
1498        };
1499        assert_eq!(top_stats_line(Rb2, Some("RB"), &rb_no_td), "14 CAR, 43 YDS");
1500
1501        let wr = NflPlayerWeekStats {
1502            receptions: 2,
1503            receiving_yards: 37,
1504            ..factories::player_stats("00-WR", 1)
1505        };
1506        assert_eq!(top_stats_line(Wr1, Some("WR"), &wr), "2 REC, 37 YDS");
1507
1508        let te = NflPlayerWeekStats {
1509            receptions: 5,
1510            receiving_yards: 41,
1511            receiving_tds: 1,
1512            ..factories::player_stats("00-TE", 1)
1513        };
1514        assert_eq!(top_stats_line(Te, Some("TE"), &te), "5 REC, 41 YDS, 1 TD");
1515
1516        // Played but no production — the receiving line still shows.
1517        let blank = NflPlayerWeekStats {
1518            ..factories::player_stats("00-WR", 1)
1519        };
1520        assert_eq!(top_stats_line(Wr1, Some("WR"), &blank), "0 REC, 0 YDS");
1521
1522        // FLEX resolves to the player's true position (a receiver here).
1523        assert_eq!(top_stats_line(Flex, Some("WR"), &wr), "2 REC, 37 YDS");
1524        // Unknown position at FLEX is never a QB — the skill line.
1525        assert_eq!(top_stats_line(Flex, None, &wr), "2 REC, 37 YDS");
1526        // Unknown position at the QB slot falls back to the passing line.
1527        assert_eq!(top_stats_line(Qb, None, &qb), "26/38, 182 YDS, 1 TD, 1 INT");
1528
1529        // A week ingested before completions and attempts existed: no "0/0".
1530        let old_week = NflPlayerWeekStats {
1531            passing_yards: 284,
1532            passing_tds: 1,
1533            ..factories::player_stats("00-QB", 1)
1534        };
1535        assert_eq!(top_stats_line(Qb, Some("QB"), &old_week), "284 YDS, 1 TD");
1536    }
1537
1538    #[test]
1539    fn row_top_stats_is_the_box_score_not_the_scoring_line() {
1540        let picks = picks();
1541        // RB1's collapsed line is the natural box score (the fixture sets no
1542        // carries), distinct from its fantasy-scoring line.
1543        assert_eq!(picks.rows[1].top_stats(), "0 CAR, 100 YDS");
1544        assert_eq!(picks.rows[1].stat_line_str(), "100 RuY, 100+ RuY Gm");
1545        assert_eq!(picks.rows[0].top_stats(), "");
1546    }
1547
1548    #[test]
1549    fn statless_row_blanks_the_stats_cell() {
1550        let picks = picks();
1551        let qb = &picks.rows[0];
1552        assert_eq!(qb.top_stats(), "");
1553        assert_eq!(qb.stat_line_str(), "—");
1554        assert_eq!(qb.points_whole(), "0");
1555        assert_eq!(qb.points_dec(), ".00");
1556        assert_eq!(qb.matchup_str(), "KC");
1557    }
1558
1559    #[test]
1560    fn defense_row_scores_points_allowed_tier() {
1561        let picks = picks();
1562        let def = &picks.rows[8];
1563        assert_eq!(def.stat_line_str(), "3 DE/PA");
1564        assert_eq!(def.matchup_str(), "KC vs LA");
1565        assert_eq!(def.points_whole(), "7");
1566        assert_eq!(def.points_dec(), ".00");
1567    }
1568
1569    #[test]
1570    fn statless_defense_row_when_defense_has_no_stats() {
1571        let mut f = Fixture::default();
1572        f.stats.defenses.clear();
1573        let picks = f.picks();
1574        let def = &picks.rows[8];
1575        assert_eq!(def.top_stats(), "");
1576        assert_eq!(def.stat_line_str(), "—");
1577        assert_eq!(def.points_whole(), "0");
1578        assert_eq!(def.points_dec(), ".00");
1579        assert_eq!(def.matchup_str(), "KC");
1580    }
1581
1582    #[test]
1583    fn scoreless_stat_row_still_renders_a_dash() {
1584        // A defense that allows 21-27 points and does nothing else plays, so
1585        // it has a stat row and a matchup, but nothing that scores. The stat
1586        // cell must not go blank.
1587        let scoreless = NflTeamWeekStats {
1588            points_allowed: 24,
1589            ..factories::defense_stats("KC", "LA", 1)
1590        };
1591        let mut f = Fixture::default();
1592        f.stats.defenses = [(TeamAbbr::KC, scoreless)].into();
1593        let picks = f.picks();
1594        let def = &picks.rows[8];
1595        assert_eq!(def.matchup_str(), "KC vs LA");
1596        assert_eq!(def.top_stats(), "—");
1597        assert_eq!(def.stat_line_str(), "—");
1598    }
1599
1600    #[test]
1601    fn matchup_renders_dash_with_no_team_and_no_stat_row() {
1602        let mut f = Fixture::default();
1603        f.names.insert(
1604            NflPlayerId("00-QB".into()),
1605            factories::identity("Quinn Back", None),
1606        );
1607        let picks = f.picks();
1608        assert_eq!(picks.rows[0].matchup_str(), "—");
1609    }
1610
1611    #[test]
1612    fn abbreviated_name_preserves_surnames_and_short_tokens() {
1613        for (full, abbreviated) in [
1614            ("Drake Maye", "D. Maye"),
1615            ("Wan'Dale Robinson", "W. Robinson"),
1616            ("Jaxon Smith-Njigba", "J. Smith-Njigba"),
1617            ("Amon-Ra St. Brown Jr.", "A. St. Brown Jr."),
1618            ("Mononymous-Longer-Than-Fits", "Mononymous-Longer-Than-Fits"),
1619            ("T.J. Hockenson", "T.J. Hockenson"),
1620            ("RJ Harvey", "RJ Harvey"),
1621        ] {
1622            assert_eq!(abbreviated_name(full), abbreviated, "{full}");
1623        }
1624    }
1625
1626    /// A priced slate row on the KC game, kicking off at 1:00pm Eastern.
1627    fn salaried(
1628        id: Option<&str>,
1629        name: &str,
1630        position: DfsPosition,
1631        salary: u32,
1632        fppg: f64,
1633        games_played: u8,
1634    ) -> SalariedPlayer {
1635        SalariedPlayer {
1636            id: id.map(|id| NflPlayerId(id.into())),
1637            game: Arc::new(factories::game_at(
1638                "2025_01_BUF_KC",
1639                1,
1640                datetime!(2025-09-07 13:00 -4),
1641            )),
1642            name: name.into(),
1643            position,
1644            team: TeamAbbr::KC,
1645            salary,
1646            games_played,
1647            fppg,
1648            injury: None,
1649            scored_stats: None,
1650        }
1651    }
1652
1653    #[test]
1654    fn abbreviated_name_preserves_defense_rows() {
1655        let info = PickInfo::new(
1656            salaried(None, "KC DST", DfsPosition::Dst, 3_000, 0.0, 0),
1657            None,
1658        );
1659        assert!(info.is_dst());
1660        assert_eq!(info.abbreviated_name(), "KC DST");
1661
1662        let picks = picks();
1663        let defense = &picks.rows[8];
1664        assert_eq!(defense.abbreviated_name(), "KC DST");
1665    }
1666
1667    #[test]
1668    fn is_long_name_starts_after_fifteen_characters() {
1669        assert!(!is_long_name("Patrick Mahomes"), "15 chars stays short");
1670        assert!(is_long_name("Jameson Williams"), "16 chars is long");
1671    }
1672
1673    #[test]
1674    fn preview_rows_carry_salary_and_schedule_never_scores() {
1675        let players: HashMap<NflPlayerId, SalariedPlayer> = lineup()
1676            .player_slots()
1677            .into_iter()
1678            .map(|(_, id)| {
1679                let (fppg, games) = if id.as_ref() == "00-RB1" {
1680                    (11.0, 2)
1681                } else {
1682                    (0.0, 0)
1683                };
1684                (
1685                    id.clone(),
1686                    salaried(
1687                        Some(id.as_ref()),
1688                        id.as_ref(),
1689                        DfsPosition::Rb,
1690                        5_000,
1691                        fppg,
1692                        games,
1693                    ),
1694                )
1695            })
1696            .collect();
1697        let defense = salaried(None, "KC DST", DfsPosition::Dst, 3_000, 6.5, 2);
1698        let (rows, spent) = build_preview(
1699            &lineup(),
1700            |id| players.get(id).cloned(),
1701            |team| (*team == TeamAbbr::KC).then(|| defense.clone()),
1702            &Avatars::default(),
1703        );
1704        assert_eq!(rows.len(), 9, "all nine slots");
1705        assert_eq!(
1706            spent,
1707            rows.iter()
1708                .filter_map(|r| r.info.as_ref())
1709                .map(PickInfo::salary)
1710                .sum::<i64>(),
1711            "spent is the sum of known salaries"
1712        );
1713        for row in &rows {
1714            let g = row.info.as_ref().expect("priced row").game();
1715            assert_eq!(g.away_score, None, "no game scores before kickoff");
1716            assert_eq!(g.home_score, None);
1717        }
1718        // Season pace flows to both position groups.
1719        let rb1 = rows
1720            .iter()
1721            .find(|r| r.slot == RosterSlot::Rb1.position_label())
1722            .expect("RB1 row")
1723            .info
1724            .as_ref()
1725            .expect("priced row");
1726        assert_eq!(rb1.fppg_str(), "11.0");
1727        assert_eq!(rb1.played_str(), "2");
1728        let def = &rows[8];
1729        assert_eq!(def.slot, RosterSlot::Def.position_label());
1730        let def = def.info.as_ref().expect("priced row");
1731        assert_eq!(def.fppg_str(), "6.5");
1732        assert_eq!(def.played_str(), "2");
1733    }
1734
1735    #[test]
1736    fn entry_page_total_agrees_with_the_standings_total() {
1737        let picks = picks();
1738        assert_eq!(picks.total, Some(20.0));
1739    }
1740
1741    #[test]
1742    fn unknown_player_renders_raw_id_and_dash_matchup() {
1743        let mut f = Fixture::default();
1744        f.names.remove(&NflPlayerId("00-QB".into()));
1745        let picks = f.picks();
1746        let qb = &picks.rows[0];
1747        assert_eq!(qb.name, "00-QB");
1748        assert_eq!(qb.matchup_str(), "—");
1749    }
1750
1751    #[test]
1752    fn game_line_bolds_the_home_team_when_the_pick_is_home() {
1753        let g = Game {
1754            home_score: Some(20),
1755            away_score: Some(13),
1756            ..factories::game("2025_01_BUF_KC", 1)
1757        };
1758        let line = game_line(&[g], "KC").expect("game found");
1759        assert_eq!(line.home, "KC");
1760        assert_eq!(line.away, "BUF");
1761        assert_eq!(line.home_score, Some(20));
1762        assert_eq!(line.away_score, Some(13));
1763        assert!(line.home_is_pick, "KC is the home side");
1764    }
1765
1766    #[test]
1767    fn game_line_marks_away_pick_and_keeps_missing_scores() {
1768        let line = game_line(&[factories::game("2025_01_BUF_KC", 1)], "BUF").expect("game found");
1769        assert!(!line.home_is_pick, "BUF is the away side");
1770        assert_eq!(line.home_score, None);
1771        assert_eq!(line.away_score, None);
1772    }
1773
1774    #[test]
1775    fn game_line_none_when_team_not_on_slate() {
1776        assert!(game_line(&[factories::game("2025_01_BUF_KC", 1)], "SF").is_none());
1777    }
1778
1779    #[test]
1780    fn ownership_is_the_share_of_lineups_rostering_a_pick() {
1781        let a = lineup(); // rb1 = 00-RB1, def = KC
1782        let mut b = lineup();
1783        b.rb1 = NflPlayerId("00-OTHER".into());
1784        b.def = TeamAbbr::SF;
1785        let own = compute_ownership(&[a.clone(), b]);
1786        // 00-QB is in both lineups -> 1.0; 00-RB1 in one of two -> 0.5.
1787        assert_eq!(own.player(&NflPlayerId("00-QB".into())), Some(1.0));
1788        assert_eq!(own.player(&NflPlayerId("00-RB1".into())), Some(0.5));
1789        // KC defense in one of two -> 0.5; a team nobody has -> None.
1790        assert_eq!(own.defense(&TeamAbbr::KC), Some(0.5));
1791        assert_eq!(own.defense(&TeamAbbr::DEN), None);
1792    }
1793}