1#[cfg(test)]
5use crate::draft_entry::service::CapState;
6use axum::Form;
7use std::str::FromStr;
8
9use askama::Template;
10use axum::Router;
11use axum::extract::{Path, State};
12use axum::response::{Html, Response};
13use axum::routing::{get, post};
14use axum_htmx::HxRequest;
15use serde::Deserialize;
16
17use crate::chrome::Chrome;
18use crate::draft_entry::service::{self, EditorPage, SlotChoice};
19use crate::entries::RosterSlot;
20use crate::fantasy_teams::{CurrentTeam, FantasyTeamId};
21use crate::web::redirect;
22use crate::{AppError, AppState};
23use nfl_data::slates::SlateId;
24
25pub fn router() -> Router<AppState> {
27 Router::new()
28 .route("/contests/{id}/draft-entry", get(editor))
29 .route(
30 "/contests/{id}/draft-entry/{slot}",
31 get(pick).post(set_slot),
32 )
33 .route("/contests/{id}/draft-entry/{slot}/clear", post(clear_slot))
34 .route("/contests/{id}/draft-entry/save", post(save))
35 .route("/contests/{id}/draft-entry/discard", post(discard))
36}
37
38fn parse_slot(slot: &str) -> Result<RosterSlot, AppError> {
40 RosterSlot::from_str(slot).map_err(|_| AppError::NotFound)
41}
42
43#[derive(Template)]
44#[template(path = "draft_entry/editor.html")]
45struct EditorView {
46 page: EditorPage,
47 chrome: Chrome,
48 contest_id: i64,
49}
50
51pub async fn editor(
53 State(state): State<AppState>,
54 CurrentTeam(team): CurrentTeam,
55 Path(id): Path<i64>,
56) -> Result<Html<String>, AppError> {
57 let page = service::editor_page(&state, FantasyTeamId(team.id), team.name, SlateId(id)).await?;
58 let chrome = Chrome::focused("Edit Lineup", format!("/contests/{id}"));
59 Ok(Html(
60 EditorView {
61 page,
62 chrome,
63 contest_id: id,
64 }
65 .render()?,
66 ))
67}
68
69#[derive(Template)]
70#[template(path = "draft_entry/picks.html")]
71struct PickView {
72 chrome: Chrome,
73 contest_id: i64,
74 slot: RosterSlot,
75 choices: Vec<SlotChoice>,
76}
77
78pub async fn pick(
81 State(state): State<AppState>,
82 CurrentTeam(team): CurrentTeam,
83 Path((id, slot)): Path<(i64, String)>,
84) -> Result<Html<String>, AppError> {
85 let slot = parse_slot(&slot)?;
86 let choices = service::choices(&state, FantasyTeamId(team.id), SlateId(id), slot).await?;
87 let chrome = Chrome::focused(
88 format!("Select {}", slot.position_label()),
89 format!("/contests/{id}/draft-entry"),
90 );
91 Ok(Html(
92 PickView {
93 chrome,
94 contest_id: id,
95 slot,
96 choices,
97 }
98 .render()?,
99 ))
100}
101
102#[derive(Deserialize)]
103pub struct SetSlotForm {
104 value: String,
105}
106
107pub async fn set_slot(
110 HxRequest(is_htmx): HxRequest,
111 State(state): State<AppState>,
112 CurrentTeam(team): CurrentTeam,
113 Path((id, slot)): Path<(i64, String)>,
114 Form(form): Form<SetSlotForm>,
115) -> Result<Response, AppError> {
116 let slot = parse_slot(&slot)?;
117 let contest_id = SlateId(id);
118 let value = slot.parse_value(form.value).map_err(AppError::BadRequest)?;
119 service::set_slot(&state, FantasyTeamId(team.id), contest_id, slot, value).await?;
120 Ok(redirect(is_htmx, format!("/contests/{id}/draft-entry")))
121}
122
123pub async fn clear_slot(
125 HxRequest(is_htmx): HxRequest,
126 State(state): State<AppState>,
127 CurrentTeam(team): CurrentTeam,
128 Path((id, slot)): Path<(i64, String)>,
129) -> Result<Response, AppError> {
130 let slot = parse_slot(&slot)?;
131 service::clear_slot(&state, FantasyTeamId(team.id), SlateId(id), slot).await?;
132 Ok(redirect(is_htmx, format!("/contests/{id}/draft-entry")))
133}
134
135pub async fn save(
137 HxRequest(is_htmx): HxRequest,
138 State(state): State<AppState>,
139 CurrentTeam(team): CurrentTeam,
140 Path(id): Path<i64>,
141) -> Result<Response, AppError> {
142 let entry_id = service::save(&state, FantasyTeamId(team.id), SlateId(id)).await?;
143 Ok(redirect(is_htmx, format!("/entries/{}", entry_id.0)))
144}
145
146pub async fn discard(
148 HxRequest(is_htmx): HxRequest,
149 State(state): State<AppState>,
150 CurrentTeam(team): CurrentTeam,
151 Path(id): Path<i64>,
152) -> Result<Response, AppError> {
153 service::discard(&state, FantasyTeamId(team.id), SlateId(id)).await?;
154 Ok(redirect(is_htmx, format!("/contests/{id}")))
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use crate::draft_entry::service::EditorSlotRow;
161 use crate::entries::service::PickInfo;
162 use crate::entries::{NflPlayerId, RosterSlot};
163 use crate::tests::factories;
164 use nfl_data::salaried_players::SalariedPlayer;
165 use nfl_data::{DfsPosition, InjuryDesignation, TeamAbbr};
166 use std::sync::Arc;
167 use strum::IntoEnumIterator;
168 use time::macros::datetime;
169
170 fn salaried(
172 name: &str,
173 position: DfsPosition,
174 salary: u32,
175 pace: Option<(f64, u32)>,
176 ) -> SalariedPlayer {
177 SalariedPlayer {
178 id: (!position.is_defense()).then(|| NflPlayerId(format!("00-{name}"))),
179 game: Arc::new(factories::game_at(
180 "2025_01_BUF_KC",
181 1,
182 datetime!(2025-09-07 13:00 -4),
183 )),
184 name: name.into(),
185 position,
186 team: TeamAbbr::KC,
187 salary,
188 games_played: pace.map_or(0, |(_, games)| u8::try_from(games).unwrap_or(0)),
189 fppg: pace.map_or(0.0, |(avg, _)| avg),
190 injury: None,
191 scored_stats: None,
192 }
193 }
194
195 fn player_info(name: &str, salary: i64, pace: Option<(f64, u32)>) -> PickInfo {
196 PickInfo::new(salaried(name, DfsPosition::Qb, salary as u32, pace), None)
197 }
198
199 fn empty_page() -> EditorPage {
200 EditorPage {
201 contest_name: "Week 1".into(),
202 team_name: "Sunday Funday".into(),
203 cap: CapState {
204 filled: 0,
205 remaining: 60_000,
206 per_open: 6_666,
207 },
208 slots: RosterSlot::iter()
209 .map(|slot| EditorSlotRow { slot, info: None })
210 .collect(),
211 locked: false,
212 entry_id: None,
213 }
214 }
215
216 #[test]
217 fn editor_header_offers_save_and_footer_is_in_flow() {
218 let mut page = empty_page();
219 page.cap.filled = 9;
220 page.cap.remaining = 0;
221 let html = EditorView {
222 page,
223 chrome: Chrome::focused("Edit Lineup", "/contests/1"),
224 contest_id: 1,
225 }
226 .render()
227 .expect("editor renders");
228 assert!(
229 html.contains(r#"hx-post="/contests/1/draft-entry/save""#),
230 "save action present: {html}"
231 );
232 assert!(
233 html.matches("draft-entry/save").count() == 2,
234 "save posts from both header and footer once saveable: {html}"
235 );
236 assert!(
237 !html.contains("sticky bottom-0"),
238 "the action footer is in flow, not sticky: {html}"
239 );
240 assert!(
241 html.contains("hx-confirm"),
242 "discard asks for confirmation: {html}"
243 );
244 }
245
246 #[test]
247 fn editor_hides_the_header_save_until_saveable() {
248 let html = EditorView {
249 page: empty_page(),
250 chrome: Chrome::focused("Edit Lineup", "/contests/1"),
251 contest_id: 1,
252 }
253 .render()
254 .expect("editor renders");
255 assert!(
256 html.matches("draft-entry/save").count() == 1,
257 "only the footer posts save while the draft can't save: {html}"
258 );
259 assert!(
260 html.contains("9 positions left to fill"),
261 "the save blocker echoes in the salary band: {html}"
262 );
263 }
264
265 #[test]
266 fn editor_renders_empty() {
267 EditorView {
268 page: empty_page(),
269 chrome: Chrome::focused("Edit Lineup", "/contests/1"),
270 contest_id: 1,
271 }
272 .render()
273 .expect("editor renders with no picks");
274 }
275
276 #[test]
277 fn editor_renders_filled_over_cap_locked() {
278 let mut page = empty_page();
279 page.cap.remaining = -1_200;
280 page.cap.per_open = 0;
281 page.cap.filled = 9;
282 page.locked = true;
283 page.slots = RosterSlot::iter()
284 .map(|slot| EditorSlotRow {
285 slot,
286 info: Some(player_info(
287 &format!("Player {slot}"),
288 6_800,
289 Some((15.5, 3)),
290 )),
291 })
292 .collect();
293 EditorView {
294 page,
295 chrome: Chrome::focused("Edit Lineup", "/contests/1"),
296 contest_id: 1,
297 }
298 .render()
299 .expect("editor renders a full locked lineup");
300 }
301
302 #[test]
303 fn picks_renders_a_player_slot() {
304 PickView {
305 chrome: Chrome::focused("Select QB", "/contests/1/draft-entry"),
306 contest_id: 1,
307 slot: RosterSlot::Qb,
308 choices: vec![
309 SlotChoice {
310 is_picked: true,
311 over_cap: false,
312 info: player_info("Quinn Back", 8_000, Some((20.5, 2))),
313 },
314 SlotChoice {
315 is_picked: false,
316 over_cap: false,
317 info: player_info("Ryan Arm", 7_500, None),
318 },
319 ],
320 }
321 .render()
322 .expect("picks partial renders");
323 }
324
325 #[test]
326 fn picks_flag_an_unaffordable_salary_in_red() {
327 let html = PickView {
328 chrome: Chrome::focused("Select QB", "/contests/1/draft-entry"),
329 contest_id: 1,
330 slot: RosterSlot::Qb,
331 choices: vec![SlotChoice {
332 is_picked: false,
333 over_cap: true,
334 info: player_info("Quinn Back", 8_000, Some((20.5, 2))),
335 }],
336 }
337 .render()
338 .expect("picks render");
339 assert!(
340 html.contains(r#"text-error">$8,000"#),
341 "unaffordable salary shows red: {html}"
342 );
343 }
344
345 #[test]
346 fn picks_renders_the_def_slot() {
347 let info = PickInfo::new(salaried("KC DST", DfsPosition::Dst, 4_000, None), None);
348 PickView {
349 chrome: Chrome::focused("Select DEF", "/contests/1/draft-entry"),
350 contest_id: 1,
351 slot: RosterSlot::Def,
352 choices: vec![SlotChoice {
353 is_picked: true,
354 over_cap: false,
355 info,
356 }],
357 }
358 .render()
359 .expect("def picks partial renders");
360 }
361
362 #[test]
363 fn pick_rows_show_the_report_designation() {
364 let info = |name: &str, injury: Option<InjuryDesignation>| {
365 PickInfo::new(
366 SalariedPlayer {
367 injury,
368 ..salaried(name, DfsPosition::Qb, 7_500, None)
369 },
370 None,
371 )
372 };
373 let html = pick_view(
374 RosterSlot::Qb,
375 vec![
376 qb_choice("Adjusted"),
377 SlotChoice {
378 info: info("Questionable", Some(InjuryDesignation::Questionable)),
379 ..qb_choice("Questionable")
380 },
381 SlotChoice {
382 info: info("Benched", Some(InjuryDesignation::InjuredReserve)),
383 ..qb_choice("Benched")
384 },
385 ],
386 )
387 .render()
388 .expect("picks render");
389 assert!(
390 html.contains(r#"title="Questionable" aria-label="Questionable""#)
391 && html.contains(">Q</span>"),
392 "the injured carry their short code: {html}"
393 );
394 assert!(html.contains(">IR</span>"), "IR shows its two-letter code");
395 let adjusted = html.find("Adjusted").unwrap();
396 let questionable = html.find("Questionable").unwrap();
397 let benched = html.find("Benched").unwrap();
398 assert!(
399 adjusted < questionable && questionable < benched,
400 "each chip sits with its own row: {html}"
401 );
402 }
403
404 #[test]
405 fn editor_renders_swap_control_only_on_filled_slots() {
406 let mut page = empty_page();
407 page.cap.filled = 1;
408 for row in &mut page.slots {
409 if row.slot == RosterSlot::Qb {
410 row.info = Some(player_info("Quinn Back", 8_000, Some((20.5, 2))));
411 }
412 }
413 let html = EditorView {
414 page,
415 chrome: Chrome::focused("Edit Lineup", "/contests/1"),
416 contest_id: 7,
417 }
418 .render()
419 .expect("editor renders with a filled slot");
420 assert!(
421 html.contains(r#"aria-label="Swap QB""#),
422 "a filled slot gets a swap control: {html}"
423 );
424 assert!(
425 !html.contains(r#"aria-label="Swap RB1""#),
426 "an empty slot offers select, not swap: {html}"
427 );
428 assert!(
429 !html.contains("/clear"),
430 "clearing lives in the picker, not on the lineup rows: {html}"
431 );
432 assert!(html.contains("1:00pm"), "kickoff time shown: {html}");
433 }
434
435 #[test]
436 fn picks_renders_remove_control_only_on_the_current_pick() {
437 let html = PickView {
438 chrome: Chrome::focused("Select QB", "/contests/1/draft-entry"),
439 contest_id: 1,
440 slot: RosterSlot::Qb,
441 choices: vec![
442 SlotChoice {
443 is_picked: true,
444 over_cap: false,
445 info: player_info("Quinn Back", 8_000, Some((20.5, 2))),
446 },
447 SlotChoice {
448 is_picked: false,
449 over_cap: false,
450 info: player_info("Ryan Arm", 7_500, None),
451 },
452 ],
453 }
454 .render()
455 .expect("picks partial renders");
456 assert_eq!(
457 html.matches("/contests/1/draft-entry/QB/clear").count(),
458 1,
459 "exactly the current pick gets a remove control: {html}"
460 );
461 assert!(
462 !html.contains("Selected"),
463 "the badge is replaced by a remove control: {html}"
464 );
465 }
466
467 fn pick_view(slot: RosterSlot, choices: Vec<SlotChoice>) -> PickView {
468 PickView {
469 chrome: Chrome::focused(
470 format!("Select {}", slot.position_label()),
471 "/contests/1/draft-entry",
472 ),
473 contest_id: 1,
474 slot,
475 choices,
476 }
477 }
478
479 fn qb_choice(name: &str) -> SlotChoice {
480 SlotChoice {
481 is_picked: false,
482 over_cap: false,
483 info: player_info(name, 7_500, None),
484 }
485 }
486
487 #[test]
488 fn picks_offer_a_search_that_swaps_the_header() {
489 let html = pick_view(RosterSlot::Qb, vec![qb_choice("Quinn Back")])
490 .render()
491 .expect("picks render");
492 assert!(
493 html.contains(r#"aria-label="Search""#),
494 "the idle header offers a search control: {html}"
495 );
496 assert!(
497 html.contains(r#"placeholder="Search QBs""#),
498 "the field names what it searches: {html}"
499 );
500 assert!(
501 html.contains(r#"aria-label="Clear search""#) && html.contains(">Cancel<"),
502 "the open search offers both clear and cancel: {html}"
503 );
504 assert!(
505 html.contains(r#"aria-label="Back""#) && html.contains("ph-caret-left"),
506 "the picker pops back rather than closing: {html}"
507 );
508 }
509
510 #[test]
511 fn picks_tag_every_row_with_its_lowercased_name() {
512 let mut picked = qb_choice("Quinn Back");
513 picked.is_picked = true;
514 let html = pick_view(RosterSlot::Qb, vec![picked, qb_choice("Ryan Arm")])
515 .render()
516 .expect("picks render");
517 assert!(
518 html.contains(r#"data-name="quinn back""#),
519 "the current pick filters like any other row: {html}"
520 );
521 assert!(
522 html.contains(r#"data-name="ryan arm""#),
523 "unpicked rows carry their name too: {html}"
524 );
525 }
526
527 #[test]
528 fn search_placeholder_reads_as_english_for_every_slot() {
529 let phrasing: Vec<String> = RosterSlot::iter()
530 .map(|slot| slot.search_placeholder())
531 .collect();
532 assert_eq!(
533 phrasing,
534 [
535 "Search QBs",
536 "Search RBs",
537 "Search RBs",
538 "Search WRs",
539 "Search WRs",
540 "Search WRs",
541 "Search TEs",
542 "Search players",
543 "Search defenses",
544 ]
545 );
546 }
547
548 #[test]
549 fn parse_slot_accepts_the_enum_strings_and_rejects_garbage() {
550 assert_eq!(parse_slot("QB").unwrap(), RosterSlot::Qb);
551 assert_eq!(parse_slot("RB2").unwrap(), RosterSlot::Rb2);
552 assert_eq!(parse_slot("DEF").unwrap(), RosterSlot::Def);
553 assert!(matches!(parse_slot("rb1"), Err(AppError::NotFound)));
554 assert!(matches!(parse_slot("WRAP"), Err(AppError::NotFound)));
555 }
556}