Skip to main content

sunday_slate/admin/avatars/
handlers.rs

1use axum::Router;
2use axum::extract::State;
3use axum::response::Response;
4use axum::routing::{get, post};
5use axum_htmx::HxRequest;
6
7use crate::admin::avatars::view::AvatarsTemplate;
8use crate::avatars::start_fetch;
9use crate::web::form_response;
10use crate::{AppError, AppState};
11
12pub fn router() -> Router<AppState> {
13    Router::new()
14        .route("/", get(index))
15        .route("/fetch", post(fetch))
16}
17
18async fn index(
19    HxRequest(is_htmx): HxRequest,
20    State(state): State<AppState>,
21) -> Result<Response, AppError> {
22    form_response(is_htmx, &AvatarsTemplate::load(&state).await?)
23}
24
25async fn fetch(hx: HxRequest, State(state): State<AppState>) -> Result<Response, AppError> {
26    start_fetch(&state);
27    index(hx, State(state)).await
28}
29
30#[cfg(test)]
31mod tests {
32
33    use crate::media::store as media_store;
34    use crate::nfl_player_headshots::store as player_store;
35    use crate::tests::TestApp;
36    use crate::tests::factories::{self, UserOptions};
37    use crate::tests::{headshot_player, headshot_salary_games, publish_headshot_slate};
38    use http::StatusCode;
39    use nfl_model::NflPlayerId;
40
41    async fn link_all_teams(app: &TestApp) {
42        let media_id = media_store::insert(&app.pool, "admin-dummy.png", "image/png", 1, 1, 1)
43            .await
44            .expect("dummy media");
45        sqlx::query("UPDATE nfl_teams SET logo_media_id = ?1")
46            .bind(media_id)
47            .execute(&app.pool)
48            .await
49            .expect("link teams");
50    }
51
52    async fn admin_app() -> TestApp {
53        let app = TestApp::new().await;
54        let admin = factories::user(
55            &app.pool,
56            UserOptions {
57                is_admin: true,
58                ..Default::default()
59            },
60        )
61        .await;
62        app.login_as(&admin.user).await;
63        app
64    }
65
66    #[tokio::test]
67    async fn admin_avatar_index_shows_missing_counts() {
68        let app = admin_app().await;
69        let page = app.get("/admin/avatars").await;
70        page.assert_status_ok();
71        page.assert_text_contains("Players missing headshots");
72        page.assert_text_contains("Teams missing logos");
73        let body = page.text();
74        let team_count = body
75            .split("Teams missing logos</dt>")
76            .nth(1)
77            .expect("team count");
78        assert!(team_count.contains(">32</dd>"));
79        assert!(body.contains(r#"method="post" action="/admin/avatars/fetch""#));
80        assert!(body.contains("Fetch missing images"));
81    }
82
83    #[tokio::test]
84    async fn admin_avatar_index_counts_only_the_latest_slate() {
85        let app = admin_app().await;
86        let players = vec![
87            headshot_player(
88                NflPlayerId("00-OLD".into()),
89                "Old",
90                "Timer",
91                Some("http://assets.invalid/old.png"),
92            ),
93            headshot_player(
94                NflPlayerId("00-CACHED".into()),
95                "Cached",
96                "Runner",
97                Some("http://assets.invalid/cached.png"),
98            ),
99            headshot_player(
100                NflPlayerId("00-NEW".into()),
101                "New",
102                "Runner",
103                Some("http://assets.invalid/new.png"),
104            ),
105            headshot_player(NflPlayerId("00-NOSOURCE".into()), "No", "Source", None),
106        ];
107        app.nfl
108            .seed_for_test(&players, &headshot_salary_games())
109            .await
110            .expect("seed nflverse");
111        publish_headshot_slate(&app, 1, &players[..1]).await;
112        publish_headshot_slate(&app, 2, &players[1..]).await;
113        let media = media_store::insert(&app.pool, "admin-cached.png", "image/png", 1, 1, 1)
114            .await
115            .expect("cached media");
116        player_store::set_headshot_media_id(&app.pool, &NflPlayerId("00-CACHED".into()), media)
117            .await
118            .expect("prelink cached");
119        player_store::set_headshot_media_id(&app.pool, &NflPlayerId("00-CACHEONLY".into()), media)
120            .await
121            .expect("cache-only id");
122
123        let page = app.get("/admin/avatars").await;
124        page.assert_status_ok();
125        let body = page.text();
126        let count = body
127            .split("Players missing headshots</dt>")
128            .nth(1)
129            .expect("player count")
130            .split("</dd>")
131            .next()
132            .expect("count closes")
133            .rsplit('>')
134            .next()
135            .expect("count digits")
136            .trim();
137        assert_eq!(
138            count, "2",
139            "downloadable and sourceless latest-slate players are missing"
140        );
141    }
142
143    #[tokio::test]
144    async fn admin_avatar_fetch_starts_a_background_run_and_reports_it() {
145        let app = admin_app().await;
146        link_all_teams(&app).await;
147
148        let response = app.post_htmx("/admin/avatars/fetch", "").await;
149        response.assert_status_ok();
150        let body = response.text();
151        assert!(body.contains(r#"id="avatars-panel""#));
152        assert!(!body.contains("<!doctype html>"));
153        // Every team already has a logo and player discovery finds nothing, so
154        // the run is empty and finishes instantly: the response may already
155        // show the completed panel. Accept either the running panel's poll
156        // trigger or the completed panel's summary text.
157        assert!(body.contains(r#"hx-trigger="every 3s""#) || body.contains("Last fetch completed"));
158
159        app.state.avatar_runner.wait_idle().await;
160        let page = app.get("/admin/avatars").await;
161        page.assert_status_ok();
162        let body = page.text();
163        assert!(body.contains("Last fetch completed"));
164        assert!(body.contains("Fetched 0 headshots and 0 logos. 0 failed, 0 have no source."));
165    }
166
167    #[tokio::test]
168    async fn admin_avatar_routes_forbid_non_admin() {
169        let app = TestApp::new().await;
170        let user = factories::user(
171            &app.pool,
172            UserOptions {
173                is_admin: false,
174                ..Default::default()
175            },
176        )
177        .await;
178        app.login_as(&user.user).await;
179        app.get("/admin/avatars")
180            .await
181            .assert_status(StatusCode::FORBIDDEN);
182        app.post("/admin/avatars/fetch", "")
183            .await
184            .assert_status(StatusCode::FORBIDDEN);
185    }
186}