Skip to main content

sunday_slate/entries/
store.rs

1use std::collections::HashMap;
2
3use itertools::Itertools;
4
5use crate::entries::model::{
6    ContestEntry, EntryDetails, EntryId, EntrySlot, EntryTeam, FantasyTeamEntries,
7    FantasyTeamEntry, Lineup, LineupError, NflPlayerId, PlayerOrDefenseId, RosterSlot,
8};
9use crate::fantasy_teams::FantasyTeamId;
10use crate::media::MediaId;
11use crate::media::store::{LogoColumns, build_logo};
12use nfl_data::TeamAbbr;
13use nfl_data::slates::SlateId;
14use sqlx::{Sqlite, SqliteConnection};
15use time::PrimitiveDateTime;
16
17#[derive(Debug, thiserror::Error)]
18pub enum EntriesError {
19    #[error(transparent)]
20    Sqlx(#[from] sqlx::Error),
21
22    /// An entry whose slot rows don't form a complete lineup — the entries
23    /// table holds complete lineups; anything less is corruption.
24    #[error("entry in slate {slate_id:?}: {source}")]
25    Lineup {
26        slate_id: SlateId,
27        source: LineupError,
28    },
29}
30
31/// Every fantasy team in a league with its contest entries, lineups parsed
32/// and total. Entry-less fantasy teams appear with empty `entries`.
33pub async fn by_fantasy_team<'e, E>(
34    ex: E,
35    league_id: i64,
36) -> Result<Vec<FantasyTeamEntries>, EntriesError>
37where
38    E: sqlx::Executor<'e, Database = Sqlite> + Copy,
39{
40    let teams = sqlx::query!(
41        r#"SELECT ft.id          AS "id!: FantasyTeamId",
42                  ft.name        AS "name!: String",
43                  ft.owner_name  AS "owner_name!: String",
44                  m.id           AS "media_id?: MediaId",
45                  m.path         AS "media_path?: String",
46                  m.content_type AS "media_content_type?: String",
47                  m.byte_size    AS "media_byte_size?: i64",
48                  m.width        AS "media_width?: i64",
49                  m.height       AS "media_height?: i64",
50                  m.created_at   AS "media_created_at?: PrimitiveDateTime",
51                  m.updated_at   AS "media_updated_at?: PrimitiveDateTime"
52           FROM fantasy_teams ft
53           LEFT JOIN media m ON m.id = ft.logo_media_id
54           WHERE ft.league_id = ?1
55           ORDER BY ft.id"#,
56        league_id,
57    )
58    .fetch_all(ex)
59    .await?;
60
61    let slot_rows = sqlx::query!(
62        r#"SELECT e.fantasy_team_id AS "fantasy_team_id!: FantasyTeamId",
63                  e.slate_id        AS "slate_id!: SlateId",
64                  s.roster_slot     AS "roster_slot!: RosterSlot",
65                  s.gsis_player_id  AS "gsis_player_id?: NflPlayerId",
66                  s.team_abbr       AS "team_abbr?: TeamAbbr"
67           FROM entry_slots s
68           JOIN entries e ON e.id = s.entry_id
69           JOIN fantasy_teams ft ON ft.id = e.fantasy_team_id
70           WHERE ft.league_id = ?1
71           ORDER BY e.fantasy_team_id, e.slate_id"#,
72        league_id,
73    )
74    .fetch_all(ex)
75    .await?;
76
77    // ORDER BY makes each entry's slot rows adjacent (and entries land in
78    // slate order per team), so chunk_by yields one chunk per entry.
79    let by_entry = slot_rows
80        .into_iter()
81        .chunk_by(|r| (r.fantasy_team_id, r.slate_id));
82    let mut entries_by_team: HashMap<FantasyTeamId, Vec<FantasyTeamEntry>> = by_entry
83        .into_iter()
84        .map(|((team_id, slate_id), rows)| {
85            let slots = rows.map(|r| entry_slot(r.roster_slot, r.gsis_player_id, r.team_abbr));
86            Lineup::from_slots(slots)
87                .map(|lineup| (team_id, FantasyTeamEntry { slate_id, lineup }))
88                .map_err(|source| EntriesError::Lineup { slate_id, source })
89        })
90        .collect::<Result<Vec<_>, _>>()?
91        .into_iter()
92        .into_group_map();
93
94    Ok(teams
95        .into_iter()
96        .map(|t| FantasyTeamEntries {
97            id: t.id,
98            name: t.name,
99            owner_name: t.owner_name,
100            logo: build_logo(LogoColumns {
101                id: t.media_id,
102                path: t.media_path,
103                content_type: t.media_content_type,
104                byte_size: t.media_byte_size,
105                width: t.media_width,
106                height: t.media_height,
107                created_at: t.media_created_at,
108                updated_at: t.media_updated_at,
109            }),
110            entries: entries_by_team.remove(&t.id).unwrap_or_default(),
111        })
112        .collect())
113}
114
115/// One fantasy team in a league with its contest entries, lineups parsed and
116/// typed. `None` when the id is not in this league.
117pub async fn for_fantasy_team<'e, E>(
118    ex: E,
119    league_id: i64,
120    team_id: FantasyTeamId,
121) -> Result<Option<FantasyTeamEntries>, EntriesError>
122where
123    E: sqlx::Executor<'e, Database = Sqlite> + Copy,
124{
125    let Some(t) = sqlx::query!(
126        r#"SELECT ft.id          AS "id!: FantasyTeamId",
127                  ft.name        AS "name!: String",
128                  ft.owner_name  AS "owner_name!: String",
129                  m.id           AS "media_id?: MediaId",
130                  m.path         AS "media_path?: String",
131                  m.content_type AS "media_content_type?: String",
132                  m.byte_size    AS "media_byte_size?: i64",
133                  m.width        AS "media_width?: i64",
134                  m.height       AS "media_height?: i64",
135                  m.created_at   AS "media_created_at?: PrimitiveDateTime",
136                  m.updated_at   AS "media_updated_at?: PrimitiveDateTime"
137           FROM fantasy_teams ft
138           LEFT JOIN media m ON m.id = ft.logo_media_id
139           WHERE ft.id = ?1 AND ft.league_id = ?2"#,
140        team_id,
141        league_id,
142    )
143    .fetch_optional(ex)
144    .await?
145    else {
146        return Ok(None);
147    };
148
149    let slot_rows = sqlx::query!(
150        r#"SELECT e.slate_id       AS "slate_id!: SlateId",
151                  s.roster_slot    AS "roster_slot!: RosterSlot",
152                  s.gsis_player_id AS "gsis_player_id?: NflPlayerId",
153                  s.team_abbr      AS "team_abbr?: TeamAbbr"
154           FROM entry_slots s
155           JOIN entries e ON e.id = s.entry_id
156           WHERE e.fantasy_team_id = ?1
157           ORDER BY e.slate_id"#,
158        team_id,
159    )
160    .fetch_all(ex)
161    .await?;
162
163    // ORDER BY makes each entry's rows adjacent, so chunk_by yields one chunk
164    // per entry.
165    let by_entry = slot_rows.into_iter().chunk_by(|r| r.slate_id);
166    let entries = by_entry
167        .into_iter()
168        .map(|(slate_id, rows)| {
169            let slots = rows.map(|r| entry_slot(r.roster_slot, r.gsis_player_id, r.team_abbr));
170            Lineup::from_slots(slots)
171                .map(|lineup| FantasyTeamEntry { slate_id, lineup })
172                .map_err(|source| EntriesError::Lineup { slate_id, source })
173        })
174        .collect::<Result<Vec<_>, _>>()?;
175
176    Ok(Some(FantasyTeamEntries {
177        id: t.id,
178        name: t.name,
179        owner_name: t.owner_name,
180        logo: build_logo(LogoColumns {
181            id: t.media_id,
182            path: t.media_path,
183            content_type: t.media_content_type,
184            byte_size: t.media_byte_size,
185            width: t.media_width,
186            height: t.media_height,
187            created_at: t.media_created_at,
188            updated_at: t.media_updated_at,
189        }),
190        entries,
191    }))
192}
193
194/// Each of a fantasy team's entries: slate id → entry id, for linking
195/// straight to a lineup.
196pub async fn entry_ids_for_team<'e, E>(
197    ex: E,
198    team_id: FantasyTeamId,
199) -> Result<HashMap<SlateId, EntryId>, sqlx::Error>
200where
201    E: sqlx::Executor<'e, Database = Sqlite>,
202{
203    let rows = sqlx::query!(
204        r#"SELECT id AS "id!: EntryId", slate_id AS "slate_id!: SlateId"
205           FROM entries
206           WHERE fantasy_team_id = ?1"#,
207        team_id,
208    )
209    .fetch_all(ex)
210    .await?;
211    Ok(rows.into_iter().map(|r| (r.slate_id, r.id)).collect())
212}
213
214/// One contest's entries within one league: each entering fantasy team with
215/// its total lineup. Fantasy teams without an entry in this contest do not
216/// appear. Row order is by fantasy team id; callers sort for display.
217pub async fn by_contest<'e, E>(
218    ex: E,
219    slate_id: SlateId,
220    league_id: i64,
221) -> Result<Vec<ContestEntry>, EntriesError>
222where
223    E: sqlx::Executor<'e, Database = Sqlite> + Copy,
224{
225    let teams = sqlx::query!(
226        r#"SELECT e.id           AS "entry_id!: EntryId",
227                  ft.id          AS "id!: FantasyTeamId",
228                  ft.name        AS "name!: String",
229                  ft.owner_name  AS "owner_name!: String",
230                  m.id           AS "media_id?: MediaId",
231                  m.path         AS "media_path?: String",
232                  m.content_type AS "media_content_type?: String",
233                  m.byte_size    AS "media_byte_size?: i64",
234                  m.width        AS "media_width?: i64",
235                  m.height       AS "media_height?: i64",
236                  m.created_at   AS "media_created_at?: PrimitiveDateTime",
237                  m.updated_at   AS "media_updated_at?: PrimitiveDateTime"
238           FROM entries e
239           JOIN fantasy_teams ft ON ft.id = e.fantasy_team_id
240           LEFT JOIN media m ON m.id = ft.logo_media_id
241           WHERE e.slate_id = ?1 AND ft.league_id = ?2
242           ORDER BY e.created_at, e.id"#,
243        slate_id,
244        league_id,
245    )
246    .fetch_all(ex)
247    .await?;
248
249    let slot_rows = sqlx::query!(
250        r#"SELECT e.fantasy_team_id AS "fantasy_team_id!: FantasyTeamId",
251                  s.roster_slot     AS "roster_slot!: RosterSlot",
252                  s.gsis_player_id  AS "gsis_player_id?: NflPlayerId",
253                  s.team_abbr       AS "team_abbr?: TeamAbbr"
254           FROM entry_slots s
255           JOIN entries e ON e.id = s.entry_id
256           JOIN fantasy_teams ft ON ft.id = e.fantasy_team_id
257           WHERE e.slate_id = ?1 AND ft.league_id = ?2
258           ORDER BY e.fantasy_team_id"#,
259        slate_id,
260        league_id,
261    )
262    .fetch_all(ex)
263    .await?;
264
265    let mut slots_by_team: HashMap<FantasyTeamId, Vec<EntrySlot>> = slot_rows
266        .into_iter()
267        .map(|r| {
268            (
269                r.fantasy_team_id,
270                entry_slot(r.roster_slot, r.gsis_player_id, r.team_abbr),
271            )
272        })
273        .into_group_map();
274
275    teams
276        .into_iter()
277        .map(|t| {
278            // No slot rows means a slotless entry; `from_slots` names the
279            // first missing slot.
280            let slots = slots_by_team.remove(&t.id).unwrap_or_default();
281            let lineup = Lineup::from_slots(slots)
282                .map_err(|source| EntriesError::Lineup { slate_id, source })?;
283            Ok(ContestEntry {
284                id: t.entry_id,
285                fantasy_team: t.id,
286                team_name: t.name,
287                owner_name: t.owner_name,
288                logo: build_logo(LogoColumns {
289                    id: t.media_id,
290                    path: t.media_path,
291                    content_type: t.media_content_type,
292                    byte_size: t.media_byte_size,
293                    width: t.media_width,
294                    height: t.media_height,
295                    created_at: t.media_created_at,
296                    updated_at: t.media_updated_at,
297                }),
298                lineup,
299            })
300        })
301        .collect()
302}
303
304/// Type one slot row's payload. The expects encode `entry_slots`' CHECK
305/// constraint (DEF carries exactly a team abbr, player slots exactly a
306/// gsis id), which the schema enforces on write.
307fn entry_slot(slot: RosterSlot, gsis: Option<NflPlayerId>, team: Option<TeamAbbr>) -> EntrySlot {
308    let value = match slot {
309        RosterSlot::Def => {
310            PlayerOrDefenseId::Defense(team.expect("entry_slots CHECK: DEF carries a team_abbr"))
311        }
312        _ => PlayerOrDefenseId::Player(
313            gsis.expect("entry_slots CHECK: a player slot carries a gsis_player_id"),
314        ),
315    };
316    EntrySlot { slot, value }
317}
318
319/// One entry with the context its page needs: lineup, contest, league, and
320/// owning fantasy team. `None` for an unknown id.
321pub async fn by_id<'e, E>(ex: E, id: EntryId) -> Result<Option<EntryDetails>, EntriesError>
322where
323    E: sqlx::Executor<'e, Database = Sqlite> + Copy,
324{
325    let Some(h) = sqlx::query!(
326        r#"SELECT e.id            AS "id!: EntryId",
327                  ft.league_id    AS "league_id!: i64",
328                  e.slate_id      AS "slate_id!: SlateId",
329                  ft.id           AS "team_id!: FantasyTeamId",
330                  ft.user_id      AS "user_id!: i64",
331                  ft.name         AS "team_name!: String",
332                  ft.owner_name   AS "owner_name!: String",
333                  m.id            AS "media_id?: MediaId",
334                  m.path          AS "media_path?: String",
335                  m.content_type  AS "media_content_type?: String",
336                  m.byte_size     AS "media_byte_size?: i64",
337                  m.width         AS "media_width?: i64",
338                  m.height        AS "media_height?: i64",
339                  m.created_at    AS "media_created_at?: PrimitiveDateTime",
340                  m.updated_at    AS "media_updated_at?: PrimitiveDateTime"
341           FROM entries e
342           JOIN fantasy_teams ft ON ft.id = e.fantasy_team_id
343           LEFT JOIN media m ON m.id = ft.logo_media_id
344           WHERE e.id = ?1"#,
345        id,
346    )
347    .fetch_optional(ex)
348    .await?
349    else {
350        return Ok(None);
351    };
352
353    let slots = sqlx::query!(
354        r#"SELECT roster_slot    AS "roster_slot!: RosterSlot",
355                  gsis_player_id AS "gsis_player_id?: NflPlayerId",
356                  team_abbr      AS "team_abbr?: TeamAbbr"
357           FROM entry_slots WHERE entry_id = ?1"#,
358        id,
359    )
360    .fetch_all(ex)
361    .await?;
362
363    let lineup = Lineup::from_slots(
364        slots
365            .into_iter()
366            .map(|r| entry_slot(r.roster_slot, r.gsis_player_id, r.team_abbr)),
367    )
368    .map_err(|source| EntriesError::Lineup {
369        slate_id: h.slate_id,
370        source,
371    })?;
372
373    Ok(Some(EntryDetails {
374        id: h.id,
375        league_id: h.league_id,
376        slate_id: h.slate_id,
377        team: EntryTeam {
378            id: h.team_id,
379            user_id: h.user_id,
380            name: h.team_name,
381            owner_name: h.owner_name,
382            logo: build_logo(LogoColumns {
383                id: h.media_id,
384                path: h.media_path,
385                content_type: h.media_content_type,
386                byte_size: h.media_byte_size,
387                width: h.media_width,
388                height: h.media_height,
389                created_at: h.media_created_at,
390                updated_at: h.media_updated_at,
391            }),
392        },
393        lineup,
394    }))
395}
396
397/// The league an entry belongs to, via its fantasy team. `None` for an
398/// unknown entry id.
399pub async fn league_id_of<'e, E>(ex: E, entry_id: i64) -> Result<Option<i64>, sqlx::Error>
400where
401    E: sqlx::Executor<'e, Database = Sqlite>,
402{
403    sqlx::query_scalar!(
404        r#"SELECT ft.league_id AS "league_id!: i64"
405           FROM entries e
406           JOIN fantasy_teams ft ON ft.id = e.fantasy_team_id
407           WHERE e.id = ?1"#,
408        entry_id,
409    )
410    .fetch_optional(ex)
411    .await
412}
413
414/// Upsert the (slate, fantasy team) entry and replace its slots with the
415/// lineup's nine. Runs on the caller's write connection, inside its
416/// transaction.
417pub async fn upsert_with_lineup(
418    conn: &mut SqliteConnection,
419    slate_id: SlateId,
420    team_id: FantasyTeamId,
421    lineup: &Lineup,
422) -> Result<EntryId, sqlx::Error> {
423    let id: i64 = sqlx::query_scalar(
424        r#"INSERT INTO entries (slate_id, fantasy_team_id)
425           VALUES (?1, ?2)
426           ON CONFLICT(slate_id, fantasy_team_id)
427           DO UPDATE SET updated_at = datetime('now', 'subsec')
428           RETURNING id"#,
429    )
430    .bind(slate_id)
431    .bind(team_id)
432    .fetch_one(&mut *conn)
433    .await?;
434
435    sqlx::query("DELETE FROM entry_slots WHERE entry_id = ?1")
436        .bind(id)
437        .execute(&mut *conn)
438        .await?;
439
440    for EntrySlot { slot, value } in lineup.to_slots() {
441        let slot_name = slot.to_string();
442        match value {
443            PlayerOrDefenseId::Player(player_id) => {
444                sqlx::query!(
445                    r#"INSERT INTO entry_slots (entry_id, roster_slot, gsis_player_id)
446                       VALUES (?1, ?2, ?3)"#,
447                    id,
448                    slot_name,
449                    player_id,
450                )
451                .execute(&mut *conn)
452                .await?;
453            }
454            PlayerOrDefenseId::Defense(team) => {
455                sqlx::query!(
456                    r#"INSERT INTO entry_slots (entry_id, roster_slot, team_abbr)
457                       VALUES (?1, ?2, ?3)"#,
458                    id,
459                    slot_name,
460                    team,
461                )
462                .execute(&mut *conn)
463                .await?;
464            }
465        }
466    }
467    Ok(EntryId(id))
468}
469
470/// The team's committed entry in a slate: its id and its lineup. The lineup
471/// is `None` when the stored slots don't parse (corrupt or incomplete), which
472/// still marks the entry as existing.
473pub async fn lineup_for_team<'e, E>(
474    ex: E,
475    slate_id: SlateId,
476    team_id: FantasyTeamId,
477) -> Result<Option<(EntryId, Option<Lineup>)>, sqlx::Error>
478where
479    E: sqlx::Executor<'e, Database = Sqlite> + Copy,
480{
481    let rows = sqlx::query!(
482        r#"SELECT e.id             AS "entry_id!: EntryId",
483                  s.roster_slot    AS "roster_slot!: RosterSlot",
484                  s.gsis_player_id AS "gsis_player_id?: NflPlayerId",
485                  s.team_abbr      AS "team_abbr?: TeamAbbr"
486           FROM entry_slots s
487           JOIN entries e ON e.id = s.entry_id
488           WHERE e.slate_id = ?1 AND e.fantasy_team_id = ?2"#,
489        slate_id,
490        team_id,
491    )
492    .fetch_all(ex)
493    .await?;
494    let Some(entry_id) = rows.first().map(|r| r.entry_id) else {
495        return Ok(None);
496    };
497    let slots = rows
498        .into_iter()
499        .map(|r| entry_slot(r.roster_slot, r.gsis_player_id, r.team_abbr));
500    Ok(Some((entry_id, Lineup::from_slots(slots).ok())))
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506    use crate::tests::factories::{self, TeamOptions};
507    use sqlx::SqlitePool;
508
509    /// The 2026 regular-season main slate for `week`.
510    fn slate(week: u8) -> SlateId {
511        SlateId((2026 * 1000 + i64::from(week)) * 10 + 1)
512    }
513
514    #[sqlx::test]
515    async fn by_fantasy_team_groups_entries_under_teams(pool: SqlitePool) {
516        // A bare league (no implicit commissioner fantasy team, unlike
517        // `factories::league`) so the two fantasy teams created below are the
518        // league's only fantasy teams.
519        let league = factories::bare_league(&pool, None).await;
520        let a = factories::team(
521            &pool,
522            TeamOptions {
523                league: Some(league.clone()),
524                ..Default::default()
525            },
526        )
527        .await;
528        let b = factories::team(
529            &pool,
530            TeamOptions {
531                league: Some(a.league.clone()),
532                ..Default::default()
533            },
534        )
535        .await;
536        let c1 = slate(1);
537        let c2 = slate(2);
538        factories::full_entry(&pool, c1, a.team.id, "00-A").await;
539        factories::full_entry(&pool, c2, a.team.id, "00-A").await;
540        factories::full_entry(&pool, c1, b.team.id, "00-B").await;
541
542        let teams = by_fantasy_team(&pool, a.league.id)
543            .await
544            .expect("aggregate");
545        assert_eq!(teams.len(), 2);
546        let ta = teams
547            .iter()
548            .find(|t| t.id == FantasyTeamId(a.team.id))
549            .unwrap();
550        let tb = teams
551            .iter()
552            .find(|t| t.id == FantasyTeamId(b.team.id))
553            .unwrap();
554        assert_eq!(ta.entries.len(), 2);
555        assert_eq!(tb.entries.len(), 1);
556        assert_eq!(tb.entries[0].slate_id, c1);
557        assert_eq!(tb.entries[0].lineup.rb1, NflPlayerId("00-B".into()));
558        assert_eq!(ta.name, a.team.name);
559        assert_eq!(ta.owner_name, a.team.owner_name);
560    }
561
562    #[sqlx::test]
563    async fn by_fantasy_team_includes_entryless_teams(pool: SqlitePool) {
564        // A bare league (no implicit commissioner fantasy team, unlike
565        // `factories::league`) so this is the league's only fantasy team.
566        let league = factories::bare_league(&pool, None).await;
567        let fixture = factories::team(
568            &pool,
569            TeamOptions {
570                league: Some(league),
571                ..Default::default()
572            },
573        )
574        .await;
575        let teams = by_fantasy_team(&pool, fixture.league.id)
576            .await
577            .expect("aggregate");
578        assert_eq!(teams.len(), 1);
579        assert!(teams[0].entries.is_empty());
580    }
581
582    #[sqlx::test]
583    async fn by_fantasy_team_joins_logo_media(pool: SqlitePool) {
584        // A bare league (no implicit commissioner fantasy team, unlike
585        // `factories::league`) so the two fantasy teams created below are the
586        // league's only fantasy teams.
587        let league = factories::bare_league(&pool, None).await;
588        let with_logo = factories::team(
589            &pool,
590            TeamOptions {
591                league: Some(league.clone()),
592                ..Default::default()
593            },
594        )
595        .await;
596        let without_logo = factories::team(
597            &pool,
598            TeamOptions {
599                league: Some(with_logo.league.clone()),
600                ..Default::default()
601            },
602        )
603        .await;
604        let media_id: MediaId = sqlx::query_scalar(
605            "INSERT INTO media (path, content_type, byte_size, width, height)
606             VALUES ('7.png', 'image/png', 1, 256, 256) RETURNING id",
607        )
608        .fetch_one(&pool)
609        .await
610        .unwrap();
611        sqlx::query("UPDATE fantasy_teams SET logo_media_id = ?1 WHERE id = ?2")
612            .bind(media_id)
613            .bind(with_logo.team.id)
614            .execute(&pool)
615            .await
616            .unwrap();
617
618        let teams = by_fantasy_team(&pool, with_logo.league.id)
619            .await
620            .expect("aggregate");
621        let logoed = teams
622            .iter()
623            .find(|t| t.id == FantasyTeamId(with_logo.team.id))
624            .unwrap();
625        let bare = teams
626            .iter()
627            .find(|t| t.id == FantasyTeamId(without_logo.team.id))
628            .unwrap();
629        let logo = logoed.logo.as_ref().expect("logo media");
630        assert_eq!(logo.id, media_id);
631        assert_eq!(logo.path, "7.png");
632        assert!(bare.logo.is_none());
633    }
634
635    #[sqlx::test]
636    async fn by_fantasy_team_rejects_incomplete_lineup(pool: SqlitePool) {
637        let fixture = factories::team(&pool, TeamOptions::default()).await;
638        let contest = slate(1);
639        let entry_id: i64 = sqlx::query_scalar(
640            "INSERT INTO entries (slate_id, fantasy_team_id) VALUES (?1, ?2) RETURNING id",
641        )
642        .bind(contest)
643        .bind(fixture.team.id)
644        .fetch_one(&pool)
645        .await
646        .unwrap();
647        sqlx::query(
648            "INSERT INTO entry_slots (entry_id, roster_slot, gsis_player_id) VALUES (?1, 'RB1', '00-X')",
649        )
650        .bind(entry_id)
651        .execute(&pool)
652        .await
653        .unwrap();
654
655        let err = by_fantasy_team(&pool, fixture.league.id).await.unwrap_err();
656        assert!(
657            matches!(err, EntriesError::Lineup { slate_id: c, .. } if c == contest),
658            "incomplete lineup is a lineup error naming the contest, got: {err:?}"
659        );
660    }
661
662    #[sqlx::test]
663    async fn for_fantasy_team_scopes_to_team_and_league(pool: SqlitePool) {
664        let league = factories::bare_league(&pool, None).await;
665        let a = factories::team(
666            &pool,
667            TeamOptions {
668                league: Some(league.clone()),
669                ..Default::default()
670            },
671        )
672        .await;
673        let b = factories::team(
674            &pool,
675            TeamOptions {
676                league: Some(a.league.clone()),
677                ..Default::default()
678            },
679        )
680        .await;
681        let c1 = slate(1);
682        factories::full_entry(&pool, c1, a.team.id, "00-A").await;
683        factories::full_entry(&pool, c1, b.team.id, "00-B").await;
684
685        let team = for_fantasy_team(&pool, a.league.id, FantasyTeamId(a.team.id))
686            .await
687            .expect("query")
688            .expect("team in league");
689        assert_eq!(team.name, a.team.name);
690        assert_eq!(team.owner_name, a.team.owner_name);
691        assert_eq!(team.entries.len(), 1, "only this team's entries");
692        assert_eq!(team.entries[0].lineup.rb1, NflPlayerId("00-A".into()));
693
694        let other_league = factories::bare_league(&pool, None).await;
695        let cross = for_fantasy_team(&pool, other_league.id, FantasyTeamId(a.team.id))
696            .await
697            .expect("query");
698        assert!(cross.is_none(), "wrong league resolves to None");
699    }
700
701    #[sqlx::test]
702    async fn for_fantasy_team_returns_entryless_team(pool: SqlitePool) {
703        let fixture = factories::team(&pool, TeamOptions::default()).await;
704        let team = for_fantasy_team(&pool, fixture.league.id, FantasyTeamId(fixture.team.id))
705            .await
706            .expect("query")
707            .expect("team present");
708        assert!(team.entries.is_empty());
709        assert!(team.logo.is_none());
710    }
711
712    #[sqlx::test]
713    async fn by_contest_returns_one_league_and_contest_only(pool: SqlitePool) {
714        // A bare league (no implicit commissioner fantasy team) so the fantasy
715        // teams created below are the league's only fantasy teams.
716        let league = factories::bare_league(&pool, None).await;
717        let a = factories::team(
718            &pool,
719            TeamOptions {
720                league: Some(league.clone()),
721                ..Default::default()
722            },
723        )
724        .await;
725        let b = factories::team(
726            &pool,
727            TeamOptions {
728                league: Some(a.league.clone()),
729                ..Default::default()
730            },
731        )
732        .await;
733        // A fantasy team in a *different* league (TeamOptions::default creates one).
734        let outsider = factories::team(&pool, TeamOptions::default()).await;
735
736        let c1 = slate(1);
737        let c2 = slate(2);
738        let entry_a = factories::full_entry(&pool, c1, a.team.id, "00-A").await;
739        factories::full_entry(&pool, c1, b.team.id, "00-B").await;
740        factories::full_entry(&pool, c2, a.team.id, "00-A").await; // other contest
741        factories::full_entry(&pool, c1, outsider.team.id, "00-C").await; // other league
742
743        let rows = by_contest(&pool, c1, a.league.id).await.expect("load");
744        assert_eq!(rows.len(), 2, "one row per entering league fantasy team");
745        assert_eq!(
746            rows.iter()
747                .find(|r| r.id == EntryId(entry_a))
748                .map(|r| r.fantasy_team),
749            Some(FantasyTeamId(a.team.id)),
750            "each row carries its own entry id, the /entries link target"
751        );
752        let ra = rows
753            .iter()
754            .find(|r| r.fantasy_team == FantasyTeamId(a.team.id))
755            .expect("team a");
756        assert_eq!(ra.team_name, a.team.name);
757        assert_eq!(ra.owner_name, a.team.owner_name);
758        assert_eq!(ra.lineup.rb1, NflPlayerId("00-A".into()));
759        assert!(
760            !rows
761                .iter()
762                .any(|r| r.fantasy_team == FantasyTeamId(outsider.team.id)),
763            "other league's entry excluded"
764        );
765    }
766
767    #[sqlx::test]
768    async fn by_contest_joins_logo_media(pool: SqlitePool) {
769        let fixture = factories::team(&pool, TeamOptions::default()).await;
770        let contest = slate(1);
771        factories::full_entry(&pool, contest, fixture.team.id, "00-A").await;
772        let media_id: MediaId = sqlx::query_scalar(
773            "INSERT INTO media (path, content_type, byte_size, width, height)
774             VALUES ('7.png', 'image/png', 1, 256, 256) RETURNING id",
775        )
776        .fetch_one(&pool)
777        .await
778        .unwrap();
779        sqlx::query("UPDATE fantasy_teams SET logo_media_id = ?1 WHERE id = ?2")
780            .bind(media_id)
781            .bind(fixture.team.id)
782            .execute(&pool)
783            .await
784            .unwrap();
785
786        let rows = by_contest(&pool, contest, fixture.league.id)
787            .await
788            .expect("load");
789        let logo = rows[0].logo.as_ref().expect("logo media");
790        assert_eq!(logo.path, "7.png");
791    }
792
793    #[sqlx::test]
794    async fn by_contest_rejects_incomplete_lineup(pool: SqlitePool) {
795        let fixture = factories::team(&pool, TeamOptions::default()).await;
796        let contest = slate(1);
797        let entry_id: i64 = sqlx::query_scalar(
798            "INSERT INTO entries (slate_id, fantasy_team_id) VALUES (?1, ?2) RETURNING id",
799        )
800        .bind(contest)
801        .bind(fixture.team.id)
802        .fetch_one(&pool)
803        .await
804        .unwrap();
805        sqlx::query(
806            "INSERT INTO entry_slots (entry_id, roster_slot, gsis_player_id) VALUES (?1, 'RB1', '00-X')",
807        )
808        .bind(entry_id)
809        .execute(&pool)
810        .await
811        .unwrap();
812
813        let err = by_contest(&pool, contest, fixture.league.id)
814            .await
815            .unwrap_err();
816        assert!(
817            matches!(err, EntriesError::Lineup { slate_id: c, .. } if c == contest),
818            "incomplete lineup is a lineup error naming the contest, got: {err:?}"
819        );
820    }
821
822    #[sqlx::test]
823    async fn by_id_loads_entry_with_context(pool: SqlitePool) {
824        let fixture = factories::team(&pool, TeamOptions::default()).await;
825        let contest = slate(5);
826        let entry_id = factories::full_entry(&pool, contest, fixture.team.id, "00-A").await;
827
828        let entry = by_id(&pool, EntryId(entry_id))
829            .await
830            .expect("load")
831            .expect("found");
832        assert_eq!(entry.id, EntryId(entry_id));
833        assert_eq!(entry.league_id, fixture.league.id);
834        assert_eq!(entry.slate_id, slate(5));
835        assert_eq!(entry.team.id, FantasyTeamId(fixture.team.id));
836        assert_eq!(entry.team.user_id, fixture.team.user_id);
837        assert_eq!(entry.team.name, fixture.team.name);
838        assert_eq!(entry.team.owner_name, fixture.team.owner_name);
839        assert!(entry.team.logo.is_none());
840        assert_eq!(entry.lineup.rb1, NflPlayerId("00-A".into()));
841        assert_eq!(entry.lineup.def, TeamAbbr::KC);
842    }
843
844    #[sqlx::test]
845    async fn league_id_of_walks_entry_to_team_to_league(pool: SqlitePool) {
846        let fixture = factories::team(&pool, TeamOptions::default()).await;
847        let contest = slate(1);
848        let entry_id: i64 = sqlx::query_scalar(
849            "INSERT INTO entries (slate_id, fantasy_team_id) VALUES (?1, ?2) RETURNING id",
850        )
851        .bind(contest)
852        .bind(fixture.team.id)
853        .fetch_one(&pool)
854        .await
855        .expect("seed entry");
856        assert_eq!(
857            league_id_of(&pool, entry_id).await.expect("lookup"),
858            Some(fixture.league.id)
859        );
860        assert_eq!(
861            league_id_of(&pool, entry_id + 99).await.expect("lookup"),
862            None
863        );
864    }
865
866    #[sqlx::test]
867    async fn entry_ids_for_team_maps_contest_to_entry(pool: SqlitePool) {
868        let a = factories::team(&pool, TeamOptions::default()).await;
869        let b = factories::team(
870            &pool,
871            TeamOptions {
872                league: Some(a.league.clone()),
873                ..Default::default()
874            },
875        )
876        .await;
877        let c1 = slate(1);
878        let c2 = slate(2);
879        let e1 = factories::full_entry(&pool, c1, a.team.id, "00-A").await;
880        let e2 = factories::full_entry(&pool, c2, a.team.id, "00-A").await;
881        // Another team's entry in the same contest must not leak in.
882        factories::full_entry(&pool, c1, b.team.id, "00-B").await;
883
884        let ids = entry_ids_for_team(&pool, FantasyTeamId(a.team.id))
885            .await
886            .expect("query");
887        assert_eq!(ids.len(), 2);
888        assert_eq!(ids.get(&c1), Some(&EntryId(e1)));
889        assert_eq!(ids.get(&c2), Some(&EntryId(e2)));
890    }
891}