Skip to main content

sunday_slate/draft_entry/
service.rs

1//! The draft-entry editor's service layer: cap math, candidate pools, and the
2//! page / slot / save operations the handler and templates consume.
3
4use std::collections::HashSet;
5use std::sync::Arc;
6
7use nfl_data::DfsPosition;
8use nfl_data::salaried_players::SalariedPlayer;
9use nfl_data::slates::{Slate, SlateId};
10use nfl_data::snapshot::Snapshot;
11use nfl_model::DfsPositionSlotType;
12use strum::IntoEnumIterator;
13use time::OffsetDateTime;
14
15use crate::draft_entry::model::DraftEntry;
16use crate::draft_entry::store as draft_store;
17use crate::entries::service::{self as entries_service, PickInfo, SALARY_CAP};
18use crate::entries::store as entries_store;
19use crate::entries::{EntryId, EntrySlot, Lineup, PlayerOrDefenseId, RosterSlot};
20use crate::fantasy_teams::FantasyTeamId;
21use crate::injuries::InjuryChip;
22use crate::media::Media;
23use crate::scoring::format_thousands;
24use crate::{AppError, AppState};
25
26/// Remaining budget and the per-open-slot average. Negative remaining = over
27/// the cap.
28pub fn remaining_and_per_open(spent: i64, filled: u8) -> (i64, i64) {
29    let remaining = SALARY_CAP - spent;
30    let open = 9 - filled;
31    let per_open = if open == 0 {
32        0
33    } else {
34        remaining / open as i64
35    };
36    (remaining, per_open)
37}
38
39/// The editor page: cap state, the nine rows, and whether the slate is read-only.
40pub struct EditorPage {
41    pub contest_name: String,
42    pub team_name: String,
43    pub cap: CapState,
44    pub slots: Vec<EditorSlotRow>,
45    pub locked: bool,
46    /// The committed entry, when one exists: the first save creates it, later
47    /// saves update it.
48    pub entry_id: Option<EntryId>,
49}
50
51impl EditorPage {
52    fn has_entry(&self) -> bool {
53        self.entry_id.is_some()
54    }
55
56    /// The save gate: every slot filled and the lineup under the cap.
57    pub fn can_save(&self) -> bool {
58        self.cap.can_save()
59    }
60
61    /// The commit action: `"Save Entry"` first, `"Update Entry"` after.
62    pub fn save_label(&self) -> &'static str {
63        if self.has_entry() {
64            "Update Entry"
65        } else {
66            "Save Entry"
67        }
68    }
69
70    /// Abandoning the draft only loses unsaved work; the committed entry, if
71    /// any, stays.
72    pub fn discard_label(&self) -> &'static str {
73        if self.has_entry() {
74            "Discard Changes"
75        } else {
76            "Discard Draft"
77        }
78    }
79
80    pub fn over_cap(&self) -> bool {
81        self.cap.over_cap()
82    }
83
84    /// The band's headline amount: what's left under the cap, or the
85    /// overage (unsigned — the "over the salary cap" label carries the
86    /// sign).
87    pub fn remaining_str(&self) -> String {
88        format!("${}", format_thousands(self.cap.remaining.abs()))
89    }
90
91    /// The band's right-hand note: the per-open budget while slots stay
92    /// open. `None` over the cap — the red headline already says it all.
93    pub fn cap_note(&self) -> Option<String> {
94        if self.over_cap() {
95            None
96        } else if self.cap.filled == 9 {
97            Some("All positions filled".to_string())
98        } else {
99            Some(format!("${} per open", format_thousands(self.cap.per_open)))
100        }
101    }
102
103    /// The open-slot count under the cap note, `None` once all are filled
104    /// (or the lineup is locked and no longer editable).
105    pub fn save_hint(&self) -> Option<String> {
106        if self.locked {
107            return None;
108        }
109        match 9 - self.cap.filled {
110            0 => None,
111            1 => Some("1 position left to fill".to_string()),
112            open => Some(format!("{open} positions left to fill")),
113        }
114    }
115}
116
117/// One of the editor's nine slot rows: what fills the slot and how it prices.
118pub struct EditorSlotRow {
119    pub slot: RosterSlot,
120    pub info: Option<PickInfo>,
121}
122
123impl EditorSlotRow {
124    pub fn injury(&self) -> Option<InjuryChip> {
125        self.info.as_ref().and_then(PickInfo::injury)
126    }
127
128    /// The row's avatar: the pick's, or the silhouette for an open slot.
129    pub fn avatar_url(&self) -> String {
130        self.info
131            .as_ref()
132            .map_or_else(entries_service::silhouette_url, PickInfo::avatar_url)
133    }
134}
135
136/// One candidate for a slot's pick list, with its price and pace.
137pub struct SlotChoice {
138    pub info: PickInfo,
139    pub is_picked: bool,
140    pub over_cap: bool,
141}
142
143/// Open (or resume) the draft and assemble the editor page. `NotFound` when
144/// the slate is not published with salaried players.
145pub async fn editor_page(
146    state: &AppState,
147    team_id: FantasyTeamId,
148    team_name: String,
149    slate_id: SlateId,
150) -> Result<EditorPage, AppError> {
151    let reader = state.db.reader();
152
153    let ctx = slate_ctx(state, slate_id).await?;
154
155    // Resume an in-progress draft; seed a first open from the committed entry.
156    let committed = entries_store::lineup_for_team(reader, slate_id, team_id).await?;
157    let entry_id = committed.as_ref().map(|(id, _)| *id);
158    let current_lineup = committed.and_then(|(_, lineup)| lineup);
159    let draft_entry =
160        get_or_create_draft(state, slate_id, team_id, current_lineup.as_ref()).await?;
161
162    let player_dst_ids: Vec<PlayerOrDefenseId> = RosterSlot::iter()
163        .filter_map(|slot| draft_entry.get(slot))
164        .collect();
165    let avatars = crate::avatars::by_id(&state.db, &player_dst_ids).await?;
166
167    let roster_slots: Vec<EditorSlotRow> = RosterSlot::iter()
168        .map(|roster_slot| {
169            let player_dst_id = draft_entry.get(roster_slot);
170            let player = player_dst_id
171                .as_ref()
172                .and_then(|pd_id| ctx.salaried_player(pd_id));
173            let avatar = player_dst_id.as_ref().and_then(|pd_id| avatars.get(pd_id));
174            build_slot_row(roster_slot, player, avatar)
175        })
176        .collect();
177
178    let cap = CapState::new(&draft_entry, &ctx);
179
180    Ok(EditorPage {
181        contest_name: ctx.slate.name.clone(),
182        team_name,
183        cap,
184        slots: roster_slots,
185        locked: ctx.locked(),
186        entry_id,
187    })
188}
189
190/// The candidate list for one slot, salary-descending from the snapshot.
191/// Omits players already picked into another slot; the current occupant of
192/// `slot` appears marked `is_picked`. Defense choices carry the team abbr as
193/// the value key.
194pub async fn choices(
195    state: &AppState,
196    team_id: FantasyTeamId,
197    slate_id: SlateId,
198    slot: RosterSlot,
199) -> Result<Vec<SlotChoice>, AppError> {
200    // Resolve the slate first: a contest with no playable slate is `NotFound`,
201    // and must not leave a draft row behind.
202    let ctx = slate_ctx(state, slate_id).await?;
203    let draft = get_or_create_draft(state, slate_id, team_id, None).await?;
204
205    // The budget this slot may spend: the cap minus what the *other* slots
206    // hold. Swapping replaces the current occupant, so it doesn't count.
207    let spent_elsewhere: i64 = RosterSlot::iter()
208        .filter(|s| *s != slot)
209        .filter_map(|s| slot_salary(&draft, s, &ctx))
210        .sum();
211    let budget = SALARY_CAP - spent_elsewhere;
212
213    let picked_elsewhere: HashSet<String> = RosterSlot::iter()
214        .filter(|s| *s != slot)
215        .filter_map(|s| match draft.get(s) {
216            Some(PlayerOrDefenseId::Player(id)) => Some(id.0),
217            _ => None,
218        })
219        .collect();
220
221    let visible: Vec<&SalariedPlayer> = ctx
222        .snapshot
223        .salaried_players_for_position(&ctx.slate.id, &slot_type(slot))
224        .iter()
225        .filter(|player| {
226            player
227                .id
228                .as_ref()
229                .is_none_or(|id| !picked_elsewhere.contains(id.as_ref()))
230        })
231        .collect();
232
233    let values: Vec<PlayerOrDefenseId> = visible.iter().map(|player| value_of(player)).collect();
234    let avatars = crate::avatars::by_id(&state.db, &values).await?;
235
236    let same_player = match draft.get(slot) {
237        Some(PlayerOrDefenseId::Player(id)) => Some(id),
238        _ => None,
239    };
240    let same_defense = draft.def;
241
242    Ok(visible
243        .into_iter()
244        .map(|player| {
245            let value = value_of(player);
246            let media = avatars.get(&value);
247            let is_picked = match player.id.as_ref() {
248                Some(id) => same_player.as_ref() == Some(id),
249                None => same_defense == Some(player.team),
250            };
251            SlotChoice {
252                info: PickInfo::new(player.clone(), media),
253                is_picked,
254                over_cap: i64::from(player.salary) > budget,
255            }
256        })
257        .collect())
258}
259
260/// Place (or replace) a pick in a slot. Rejects an invalid pick (see
261/// [`validate_pick`]) and refuses on a locked slate.
262pub async fn set_slot(
263    state: &AppState,
264    team_id: FantasyTeamId,
265    slate_id: SlateId,
266    slot: RosterSlot,
267    value: PlayerOrDefenseId,
268) -> Result<(), AppError> {
269    let ctx = require_open(state, slate_id).await?;
270    mutate_draft(state, slate_id, team_id, move |draft| {
271        validate_pick(draft, slot, &value, &ctx)?;
272        draft.set(slot, value);
273        Ok(())
274    })
275    .await
276}
277
278/// Empty a slot. An absent draft is created then cleared (net no-op).
279/// Refuses on a locked slate.
280pub async fn clear_slot(
281    state: &AppState,
282    team_id: FantasyTeamId,
283    slate_id: SlateId,
284    slot: RosterSlot,
285) -> Result<(), AppError> {
286    require_open(state, slate_id).await?;
287    mutate_draft(state, slate_id, team_id, move |draft| {
288        draft.clear(slot);
289        Ok(())
290    })
291    .await
292}
293
294/// Load-or-create the draft, apply `mutate`, and persist — one transaction on
295/// the write pool (the reader is read-only), so a rejected mutation also rolls
296/// back an incidental draft creation.
297async fn mutate_draft(
298    state: &AppState,
299    slate_id: SlateId,
300    team_id: FantasyTeamId,
301    mutate: impl FnOnce(&mut DraftEntry) -> Result<(), AppError> + Send,
302) -> Result<(), AppError> {
303    state
304        .db
305        .write_tx::<_, (), AppError>(async move |conn| {
306            let mut draft = draft_store::get_or_create_tx(conn, slate_id, team_id, None).await?;
307            mutate(&mut draft)?;
308            draft_store::save(conn, &draft).await?;
309            Ok(())
310        })
311        .await
312}
313
314/// Delete the draft row, abandoning the in-progress lineup. Never refused:
315/// there is no committed data to protect.
316pub async fn discard(
317    state: &AppState,
318    team_id: FantasyTeamId,
319    slate_id: SlateId,
320) -> Result<(), AppError> {
321    state
322        .db
323        .write_tx::<_, (), AppError>(async move |conn| {
324            draft_store::delete_by_keys(conn, slate_id, team_id).await?;
325            Ok(())
326        })
327        .await
328}
329
330/// Commit the draft as a real entry: upsert the `entries` row, replace its
331/// nine `entry_slots`, and delete the draft row. Refuses when the lineup is
332/// incomplete or over the salary cap.
333pub async fn save(
334    state: &AppState,
335    team_id: FantasyTeamId,
336    slate_id: SlateId,
337) -> Result<EntryId, AppError> {
338    let ctx = require_open(state, slate_id).await?;
339    state
340        .db
341        .write_tx::<_, EntryId, AppError>(async move |conn| {
342            let Some(draft) = draft_store::by_keys(&mut *conn, slate_id, team_id).await? else {
343                return Err(AppError::BadRequest(
344                    "Complete all nine slots before saving.".into(),
345                ));
346            };
347            let cap = CapState::new(&draft, &ctx);
348            if !cap.can_save() {
349                return Err(AppError::BadRequest(if cap.filled < 9 {
350                    "Complete all nine slots before saving.".into()
351                } else {
352                    "Lineup is over the salary cap.".into()
353                }));
354            }
355            let lineup = Lineup::from_slots(RosterSlot::iter().map(|s| EntrySlot {
356                slot: s,
357                value: draft.get(s).expect("can_save guarantees nine filled slots"),
358            }))
359            .map_err(|e| AppError::BadRequest(e.to_string()))?;
360            let id = entries_store::upsert_with_lineup(conn, slate_id, team_id, &lineup).await?;
361            draft_store::delete(&mut *conn, draft.id).await?;
362            Ok(id)
363        })
364        .await
365}
366
367/// What a salaried row is, as a slot value.
368fn value_of(player: &SalariedPlayer) -> PlayerOrDefenseId {
369    match player.id.as_ref() {
370        Some(id) => PlayerOrDefenseId::Player(id.clone()),
371        None => PlayerOrDefenseId::Defense(player.team),
372    }
373}
374
375/// The snapshot bucket a roster slot draws from.
376fn slot_type(slot: RosterSlot) -> DfsPositionSlotType {
377    match slot {
378        RosterSlot::Qb => DfsPositionSlotType::Position(DfsPosition::Qb),
379        RosterSlot::Rb1 | RosterSlot::Rb2 => DfsPositionSlotType::Position(DfsPosition::Rb),
380        RosterSlot::Wr1 | RosterSlot::Wr2 | RosterSlot::Wr3 => {
381            DfsPositionSlotType::Position(DfsPosition::Wr)
382        }
383        RosterSlot::Te => DfsPositionSlotType::Position(DfsPosition::Te),
384        RosterSlot::Flex => DfsPositionSlotType::Flex,
385        RosterSlot::Def => DfsPositionSlotType::Position(DfsPosition::Dst),
386    }
387}
388
389/// The picker only offers valid choices, so these rejections are the
390/// defense-in-depth path: a stale or tampered form fails with a message
391/// instead of a constraint error.
392fn validate_pick(
393    draft: &DraftEntry,
394    slot: RosterSlot,
395    value: &PlayerOrDefenseId,
396    ctx: &SlateCtx,
397) -> Result<(), AppError> {
398    match value {
399        PlayerOrDefenseId::Defense(team) => {
400            if slot != RosterSlot::Def {
401                return Err(AppError::BadRequest(format!(
402                    "{} is a defense; the {} slot takes a player.",
403                    team.as_str(),
404                    slot.position_label()
405                )));
406            }
407            if ctx.salaried_player(value).is_none() {
408                return Err(AppError::BadRequest(format!(
409                    "{} is not on this slate.",
410                    team.as_str()
411                )));
412            }
413            Ok(())
414        }
415        PlayerOrDefenseId::Player(id) => {
416            if slot == RosterSlot::Def {
417                return Err(AppError::BadRequest(
418                    "DEF takes a team defense, not a player.".into(),
419                ));
420            }
421            let position = ctx
422                .salaried_player(value)
423                .map(|player| player.position)
424                .ok_or_else(|| {
425                    AppError::BadRequest(format!("{} is not on this slate.", id.as_ref()))
426                })?;
427            if !slot_type(slot).allows(position) {
428                return Err(AppError::BadRequest(format!(
429                    "{} does not fit the {} slot.",
430                    id.as_ref(),
431                    slot.position_label()
432                )));
433            }
434            let elsewhere = RosterSlot::iter()
435                .filter(|s| *s != slot)
436                .filter_map(|s| match draft.get(s) {
437                    Some(PlayerOrDefenseId::Player(p)) => Some(p),
438                    _ => None,
439                })
440                .any(|p| p.as_ref() == id.as_ref());
441            if elsewhere {
442                return Err(AppError::BadRequest(format!(
443                    "{} is already in this lineup.",
444                    id.as_ref()
445                )));
446            }
447            Ok(())
448        }
449    }
450}
451
452/// The contest's slate and NflData snapshot
453struct SlateCtx {
454    slate: Slate,
455    snapshot: Arc<Snapshot>,
456    now: OffsetDateTime,
457}
458
459impl SlateCtx {
460    fn salaried_player(&self, value: &PlayerOrDefenseId) -> Option<&SalariedPlayer> {
461        self.snapshot.salaried_player(&self.slate.id, value)
462    }
463
464    /// Whether the slate has kicked off.
465    fn locked(&self) -> bool {
466        self.slate.locked(self.now)
467    }
468}
469
470async fn slate_ctx(state: &AppState, slate_id: SlateId) -> Result<SlateCtx, AppError> {
471    let snapshot = state.nfl.snapshot();
472    let slate = snapshot.slate(&slate_id).ok_or(AppError::NotFound)?.clone();
473    Ok(SlateCtx {
474        slate,
475        snapshot,
476        now: state.now(),
477    })
478}
479
480/// The write-path gate: `Forbidden` once the slate kicks off.
481async fn require_open(state: &AppState, slate_id: SlateId) -> Result<SlateCtx, AppError> {
482    let ctx = slate_ctx(state, slate_id).await?;
483    if ctx.locked() {
484        return Err(AppError::Forbidden);
485    }
486    Ok(ctx)
487}
488
489/// A draft's cap position: how many slots are filled, what is left under the
490/// cap, and the average left per open slot.
491pub struct CapState {
492    pub filled: u8,
493    pub remaining: i64,
494    pub per_open: i64,
495}
496
497impl CapState {
498    fn new(draft: &DraftEntry, ctx: &SlateCtx) -> Self {
499        let spent: i64 = RosterSlot::iter()
500            .filter_map(|s| slot_salary(draft, s, ctx))
501            .sum();
502        let filled = RosterSlot::iter()
503            .filter(|s| draft.get(*s).is_some())
504            .count() as u8;
505        let (remaining, per_open) = remaining_and_per_open(spent, filled);
506        Self {
507            filled,
508            remaining,
509            per_open,
510        }
511    }
512
513    /// The save gate: every slot filled and the lineup under the cap.
514    fn can_save(&self) -> bool {
515        self.filled == 9 && self.remaining >= 0
516    }
517
518    /// Whether the lineup has spent past the cap.
519    fn over_cap(&self) -> bool {
520        self.remaining < 0
521    }
522}
523
524/// The salary a filled slot contributes to the cap, `None` for an empty slot
525fn slot_salary(draft: &DraftEntry, slot: RosterSlot, ctx: &SlateCtx) -> Option<i64> {
526    draft
527        .get(slot)
528        .and_then(|value| ctx.salaried_player(&value))
529        .map(|player| i64::from(player.salary))
530}
531
532fn build_slot_row(
533    slot: RosterSlot,
534    player: Option<&SalariedPlayer>,
535    avatar: Option<&Media>,
536) -> EditorSlotRow {
537    EditorSlotRow {
538        slot,
539        info: player.map(|player| PickInfo::new(player.clone(), avatar)),
540    }
541}
542
543/// Get-or-resume the draft row: read it off the reader, and only take the
544/// serialized write connection to create it.
545async fn get_or_create_draft(
546    state: &AppState,
547    slate_id: SlateId,
548    team_id: FantasyTeamId,
549    seed: Option<&Lineup>,
550) -> Result<DraftEntry, AppError> {
551    if let Some(draft) = draft_store::by_keys(state.db.reader(), slate_id, team_id).await? {
552        return Ok(draft);
553    }
554    state
555        .db
556        .write_tx::<_, DraftEntry, AppError>(async move |conn| {
557            Ok(draft_store::get_or_create_tx(conn, slate_id, team_id, seed).await?)
558        })
559        .await
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565
566    #[test]
567    fn remaining_flips_negative_over_cap() {
568        let (rem, _) = remaining_and_per_open(59_000, 1);
569        assert_eq!(rem, 1_000);
570    }
571
572    #[test]
573    fn per_open_is_floored_division() {
574        let (rem, per) = remaining_and_per_open(30_000, 1);
575        assert_eq!(rem, 30_000);
576        assert_eq!(per, 3_750); // 30_000 / 8
577    }
578
579    #[test]
580    fn per_open_is_zero_when_full() {
581        let (rem, per) = remaining_and_per_open(0, 9);
582        assert_eq!(rem, SALARY_CAP);
583        assert_eq!(per, 0);
584    }
585
586    #[test]
587    fn can_save_requires_nine_slots_and_nonnegative_remaining() {
588        let cap = |filled, remaining| CapState {
589            filled,
590            remaining,
591            per_open: 0,
592        };
593        assert!(cap(9, 0).can_save());
594        assert!(cap(9, 1).can_save());
595        assert!(!cap(9, -1).can_save(), "over cap disables save");
596        assert!(!cap(8, 0).can_save(), "incomplete disables save");
597        assert!(!cap(0, SALARY_CAP).can_save());
598    }
599
600    fn band_page(filled: u8, remaining: i64, locked: bool) -> EditorPage {
601        EditorPage {
602            contest_name: "Week 1".into(),
603            team_name: "Team".into(),
604            cap: CapState {
605                filled,
606                remaining,
607                per_open: if filled == 9 {
608                    0
609                } else {
610                    remaining / (9 - filled) as i64
611                },
612            },
613            slots: Vec::new(),
614            locked,
615            entry_id: None,
616        }
617    }
618
619    #[test]
620    fn action_labels_follow_entry_state() {
621        let mut page = band_page(9, 0, false);
622        assert_eq!(page.save_label(), "Save Entry");
623        assert_eq!(page.discard_label(), "Discard Draft");
624        page.entry_id = Some(EntryId(42));
625        assert_eq!(page.save_label(), "Update Entry");
626        assert_eq!(page.discard_label(), "Discard Changes");
627    }
628
629    #[test]
630    fn cap_note_tracks_the_band_state() {
631        assert_eq!(
632            band_page(4, 25_600, false).cap_note().as_deref(),
633            Some("$5,120 per open")
634        );
635        assert_eq!(
636            band_page(9, 2_200, false).cap_note().as_deref(),
637            Some("All positions filled")
638        );
639        assert_eq!(
640            band_page(9, -9_500, false).cap_note(),
641            None,
642            "over cap the red headline stands alone"
643        );
644    }
645
646    #[test]
647    fn save_hint_counts_the_open_slots() {
648        assert_eq!(
649            band_page(8, 100, false).save_hint().as_deref(),
650            Some("1 position left to fill")
651        );
652        assert_eq!(
653            band_page(4, 25_600, false).save_hint().as_deref(),
654            Some("5 positions left to fill")
655        );
656        assert_eq!(
657            band_page(9, -9_500, false).save_hint(),
658            None,
659            "over cap is the headline's story, not the hint's"
660        );
661        assert_eq!(band_page(9, 2_200, false).save_hint(), None, "saveable");
662        assert_eq!(
663            band_page(4, 0, true).save_hint(),
664            None,
665            "locked hides the hint"
666        );
667    }
668}