diff --git a/src/db/appointment.rs b/src/db/appointment.rs index 896ee17..78d649c 100644 --- a/src/db/appointment.rs +++ b/src/db/appointment.rs @@ -132,6 +132,22 @@ where Ok(appointment) } +/// The optional filters and the page of [`list_for_requester`], in one +/// struct — the fields outgrew a readable argument list. The default is +/// the unfiltered, unpaged read. +#[derive(Default)] +pub struct RequesterListParams<'a> { + pub status: Option, + /// The meeting's effective start bounds, `[after, before)`. + pub starts_after: Option, + pub starts_before: Option, + /// The booked slot's teacher. + pub teacher: Option<&'a UserId>, + /// `None` = the full list. + pub limit: Option, + pub offset: i64, +} + /// The caller's own bookings, newest first. The optional filters narrow the /// read: `status` matches the stored state, `starts_after`/`starts_before` /// bound the meeting's effective start — a standing proposal, the slot's @@ -145,13 +161,16 @@ where pub async fn list_for_requester( db: &Database, requester: &UserId, - status: Option, - starts_after: Option, - starts_before: Option, - teacher: Option<&UserId>, - limit: Option, - offset: i64, + params: RequesterListParams<'_>, ) -> Result<(Vec, i64), AppError> { + let RequesterListParams { + status, + starts_after, + starts_before, + teacher, + limit, + offset, + } = params; // Spell the appointment columns against the join alias, so the derived // table's row keeps the exact names [`Appointment`] decodes and the // slot's duplicate column names never leak in. The plain shape aliases diff --git a/src/db/exam.rs b/src/db/exam.rs index aae0c2d..24de3bb 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -206,6 +206,26 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> .await?) } +/// The schedule window and the page of [`list_windowed`], in one struct — +/// the fields outgrew a readable argument list. The four optional bounds +/// are [`crate::web::page::WindowParams`]'s schedule window, validated +/// upstream. The default is the windowless, unpaged read: all four bounds +/// absent keeps `id DESC` (newest first); any bound set drops window-less +/// exams (no `mode` → both schedule columns null, so every predicate is +/// `NULL`-rejecting) and flips the order to ascending by schedule — +/// `starts_at`, falling back to `ends_at`, ties by id — the order +/// `WindowParams::apply` used to produce in Rust. +#[derive(Default)] +pub struct WindowedListParams { + pub starts_after: Option, + pub ends_after: Option, + pub starts_before: Option, + pub ends_before: Option, + /// `None` = the full list. + pub limit: Option, + pub offset: i64, +} + /// The exams list behind `GET /exams`, paged by the database — visibility, /// the draft rule, the schedule window, the `LIMIT/OFFSET` and the `total` /// count all share one `WHERE` per branch, so a filtered page never decodes @@ -216,24 +236,20 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> /// exam), with `NOT draft OR owner ∈ managed`, today's rule unchanged — a /// draft shows only to someone who manages its owner instance. Both `None` is /// the manager+ whole-table read. -/// -/// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule -/// window, validated upstream. All four absent keeps `id DESC` (newest -/// first); any bound set drops window-less exams (no `mode` → both schedule -/// columns null, so every predicate is `NULL`-rejecting) and flips the order -/// to ascending by schedule — `starts_at`, falling back to `ends_at`, ties by -/// id — the order `WindowParams::apply` used to produce in Rust. pub async fn list_windowed( db: &Database, visible: Option<&[ClassCourseId]>, managed: Option<&[ClassCourseId]>, - starts_after: Option, - ends_after: Option, - starts_before: Option, - ends_before: Option, - limit: Option, - offset: i64, + params: WindowedListParams, ) -> Result<(Vec, i64), AppError> { + let WindowedListParams { + starts_after, + ends_after, + starts_before, + ends_before, + limit, + offset, + } = params; // Window predicates and binds move together: each bound appends its // predicate with the placeholder number its bind position lands on. The // two visibility binds of the non-manager branch claim $1 and $2, so the diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index 6d87313..4501cf0 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -440,7 +440,7 @@ mod tests { /// The whole unwindowed log — the read the old `list_for_user` gave — /// for tests that just want the sessions. - async fn whole_log<'a>(user: &UserId, db: &Database) -> Vec { + async fn whole_log(user: &UserId, db: &Database) -> Vec { page_for_user(db, user, None, None, None, 0) .await .unwrap() diff --git a/src/service/appointment.rs b/src/service/appointment.rs index 2314b38..206707e 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -32,6 +32,8 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +pub use crate::db::appointment::RequesterListParams; + /// Request `slot`. Lands `pending`: publishing availability is not consent /// to a specific person and topic. /// @@ -126,24 +128,9 @@ pub async fn read(db: &Database, id: &AppointmentId) -> Result, - starts_after: Option, - starts_before: Option, - teacher: Option<&UserId>, - limit: Option, - offset: i64, + params: RequesterListParams<'_>, ) -> Result<(Vec, i64), AppError> { - appointment::list_for_requester( - db, - requester, - status, - starts_after, - starts_before, - teacher, - limit, - offset, - ) - .await + appointment::list_for_requester(db, requester, params).await } /// Every booking aimed at `teacher`, newest first — the request inbox, @@ -909,13 +896,17 @@ mod tests { // Absent: all three, newest first — the shape today's callers see. let (rows, total) = - list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap(); + list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap(); assert_eq!((rows.len(), total), (3, 3)); // status: only the approved one, and total is the filtered count. - let (rows, total) = list_for_requester(&db, &veli, Some(AppointmentStatus::Approved), None, None, None, - None, - 0, + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + status: Some(AppointmentStatus::Approved), + ..Default::default() + }, ) .await .unwrap(); @@ -923,25 +914,41 @@ mod tests { assert_eq!(rows[0].get_id(), approved.get_id()); // No state matches: an empty page, not an error. - let (rows, total) = list_for_requester(&db, &veli, Some(AppointmentStatus::Rejected), None, None, None, - None, - 0, + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + status: Some(AppointmentStatus::Rejected), + ..Default::default() + }, ) .await .unwrap(); assert_eq!((rows.len(), total), (0, 0)); // teacher joins through the slot: only the bookings on ali's slots. - let (rows, total) = - list_for_requester(&db, &veli, None, None, None, Some(&ali), None, 0).await.unwrap(); + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + teacher: Some(&ali), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!((rows.len(), total), (2, 2)); assert!(rows.iter().all(|row| row.get_id() != approved.get_id())); // starts_after judges the effective start: the pending meeting (at // now + 60_000) is out; the approved and cancelled ones stay. - let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now + 150_000)), None, None, - None, - 0, + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + starts_after: Some(at(now + 150_000)), + ..Default::default() + }, ) .await .unwrap(); @@ -949,11 +956,28 @@ mod tests { assert!(rows.iter().all(|row| row.get_id() != pending.get_id())); // The window applies after the filter; total stays the filtered count. - let (page1, total) = - list_for_requester(&db, &veli, None, None, None, None, Some(1), 0).await.unwrap(); + let (page1, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + limit: Some(1), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!((page1.len(), total), (1, 3)); - let (page2, total) = - list_for_requester(&db, &veli, None, None, None, None, Some(1), 1).await.unwrap(); + let (page2, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + limit: Some(1), + offset: 1, + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!((page2.len(), total), (1, 3)); assert_ne!(page1[0].get_id(), page2[0].get_id()); @@ -963,9 +987,13 @@ mod tests { propose(&db, pending.get_id(), at(now + 500_000), at(now + 560_000), &ali) .await .unwrap(); - let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now + 400_000)), None, None, - None, - 0, + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + starts_after: Some(at(now + 400_000)), + ..Default::default() + }, ) .await .unwrap(); @@ -1005,18 +1033,30 @@ mod tests { .await .unwrap(); let (rows, total) = - list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap(); + list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap(); assert_eq!((rows.len(), total), (3, 3), "the windowless row still lists"); - let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now)), None, None, - None, - 0, + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + starts_after: Some(at(now)), + ..Default::default() + }, ) .await .unwrap(); assert_eq!((rows.len(), total), (2, 2), "the windowless row has no start to match"); assert!(rows.iter().all(|row| row.get_id() != cancelled.get_id())); - let (rows, total) = - list_for_requester(&db, &veli, None, None, None, Some(&ali), None, 0).await.unwrap(); + let (rows, total) = list_for_requester( + &db, + &veli, + RequesterListParams { + teacher: Some(&ali), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!((rows.len(), total), (1, 1), "a windowless row names no teacher"); assert_eq!(rows[0].get_id(), pending.get_id()); } @@ -1051,19 +1091,17 @@ mod tests { // Absent: both — the set is unchanged without the bound. let (rows, total) = - list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap(); + list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap(); assert_eq!((rows.len(), total), (2, 2)); // before: only the early booking survives. let (rows, total) = list_for_requester( &db, &veli, - None, - None, - Some(at(now + 150_000)), - None, - None, - 0, + RequesterListParams { + starts_before: Some(at(now + 150_000)), + ..Default::default() + }, ) .await .unwrap(); @@ -1076,12 +1114,10 @@ mod tests { let (rows, total) = list_for_requester( &db, &veli, - None, - None, - Some(at(now + 200_000)), - None, - None, - 0, + RequesterListParams { + starts_before: Some(at(now + 200_000)), + ..Default::default() + }, ) .await .unwrap(); @@ -1100,12 +1136,11 @@ mod tests { let (rows, total) = list_for_requester( &db, &veli, - None, - Some(at(now + 150_000)), - Some(at(now + 260_000)), - None, - None, - 0, + RequesterListParams { + starts_after: Some(at(now + 150_000)), + starts_before: Some(at(now + 260_000)), + ..Default::default() + }, ) .await .unwrap(); diff --git a/src/service/exam.rs b/src/service/exam.rs index 0c14e0a..86262c3 100644 --- a/src/service/exam.rs +++ b/src/service/exam.rs @@ -24,6 +24,8 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; use crate::service::exam_attempt::require_open; +pub use crate::db::exam::WindowedListParams; + /// Publish (or draft) an exam on one class×course instance, inside one term. /// /// Two refusals stand in front of the write. The instance's catalog course @@ -122,25 +124,9 @@ pub async fn list_windowed( db: &Database, visible: Option<&[ClassCourseId]>, managed: Option<&[ClassCourseId]>, - starts_after: Option, - ends_after: Option, - starts_before: Option, - ends_before: Option, - limit: Option, - offset: i64, + params: WindowedListParams, ) -> Result<(Vec, i64), AppError> { - exam::list_windowed( - db, - visible, - managed, - starts_after, - ends_after, - starts_before, - ends_before, - limit, - offset, - ) - .await + exam::list_windowed(db, visible, managed, params).await } /// One instance's exams, newest first — the read behind @@ -903,7 +889,7 @@ mod tests { let other_draft = exam_shaped(&db, &b, sync(now + 3_600_000), true, "other-draft").await; // Manager+: the whole table, newest first. - let (rows, total) = list_windowed(&db, None, None, None, None, None, None, None, 0) + let (rows, total) = list_windowed(&db, None, None, WindowedListParams::default()) .await .unwrap(); assert_eq!(total, 5); @@ -920,9 +906,17 @@ mod tests { // unaliased `exam` (the audience join only exists on the other // branch). This exact call 500'd with "missing FROM-clause entry for // table e" while the predicates were `e.`-qualified. - let (rows, total) = list_windowed(&db, None, None, None, Some(now), None, None, None, 0) - .await - .unwrap(); + let (rows, total) = list_windowed( + &db, + None, + None, + WindowedListParams { + ends_after: Some(now), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!(total, 3); let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect(); assert_eq!( @@ -932,10 +926,17 @@ mod tests { .map(|exam| exam.get_id().clone()) .collect::>() ); - let (_, total) = - list_windowed(&db, None, None, None, None, Some(now + 45 * 60_000), None, None, 0) - .await - .unwrap(); + let (_, total) = list_windowed( + &db, + None, + None, + WindowedListParams { + starts_before: Some(now + 45 * 60_000), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!(total, 1, "starts_before keeps only the already-run exam"); // A viewer of A who manages nothing: A's published exams only — both @@ -943,7 +944,7 @@ mod tests { let visible = vec![a.get_id().clone()]; let nothing: Vec = Vec::new(); let (rows, total) = - list_windowed(&db, Some(&visible), Some(¬hing), None, None, None, None, None, 0) + list_windowed(&db, Some(&visible), Some(¬hing), WindowedListParams::default()) .await .unwrap(); assert_eq!(total, 3); @@ -952,7 +953,7 @@ mod tests { // A's teacher manages A: sees A's draft — and still not B's. let manages_a = vec![a.get_id().clone()]; let (rows, total) = - list_windowed(&db, Some(&visible), Some(&manages_a), None, None, None, None, None, 0) + list_windowed(&db, Some(&visible), Some(&manages_a), WindowedListParams::default()) .await .unwrap(); assert_eq!(total, 4); @@ -967,12 +968,10 @@ mod tests { &db, Some(&visible), Some(&manages_a), - None, - Some(now), - None, - None, - None, - 0, + WindowedListParams { + ends_after: Some(now), + ..Default::default() + }, ) .await .unwrap(); @@ -985,12 +984,11 @@ mod tests { &db, Some(&visible), Some(&manages_a), - None, - Some(now), - None, - None, - Some(1), - 0, + WindowedListParams { + ends_after: Some(now), + limit: Some(1), + ..Default::default() + }, ) .await .unwrap(); @@ -1000,7 +998,7 @@ mod tests { // draft wall leaves them an empty page, not an error. let sees_b = vec![b.get_id().clone()]; let (rows, total) = - list_windowed(&db, Some(&sees_b), Some(¬hing), None, None, None, None, None, 0) + list_windowed(&db, Some(&sees_b), Some(¬hing), WindowedListParams::default()) .await .unwrap(); assert!(rows.is_empty() && total == 0); diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 8e1e35d..f1c502e 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -819,12 +819,14 @@ async fn list_appointments( service::appointment::list_for_requester( &st.db, user.get_id(), - status, - starts_after, - starts_before, - narrow_to.as_ref(), - limit, - offset, + service::appointment::RequesterListParams { + status, + starts_after, + starts_before, + teacher: narrow_to.as_ref(), + limit, + offset, + }, ) .await? }; diff --git a/src/web/courses.rs b/src/web/courses.rs index db67018..a20e12f 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -438,18 +438,31 @@ struct CourseListFilter { taught: Option, } +/// The parsed [`CourseListFilter`] — one named field per query parameter, +/// ready for [`visible_courses_filtered`]. +#[derive(Debug)] +struct ResolvedCourseFilter { + kind: Option, + q: Option, + taught: Option, +} + impl CourseListFilter { /// `kind` parses through the write-path validator, so an unknown or empty /// spelling is the same 400 a create/PATCH gets; `taught` needs no parse — /// the query extractor itself 400s a `?taught=` that is not `true`/`false`, /// naming the field; `q` passes through raw — each arm trims, folds and /// blanks it identically. - fn resolve(self) -> Result<(Option, Option, Option), AppError> { + fn resolve(self) -> Result { let kind = match self.kind { Some(kind) => Some(CourseKind::try_new(&kind)?), None => None, }; - Ok((kind, self.q, self.taught)) + Ok(ResolvedCourseFilter { + kind, + q: self.q, + taught: self.taught, + }) } } @@ -483,11 +496,13 @@ async fn list_courses( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (kind, q, taught) = filter.resolve()?; + let filters = filter.resolve()?; // The filters ride inside the visible set — SQL for a manager, the // union's tail in Rust below one — so total is the filtered length // before the window is cut. - let courses = visible_courses_filtered(&user, &st.db, kind, q.as_deref(), taught).await?; + let courses = + visible_courses_filtered(&user, &st.db, filters.kind, filters.q.as_deref(), filters.taught) + .await?; let total = courses.len() as i64; // Paged in the web layer: the visible set is a Rust union of two lists. let window = paginate(&courses, limit, offset); @@ -1009,16 +1024,16 @@ mod tests { "{kind:?}: {err:?}" ); } - let (kind, q, taught) = CourseListFilter { + let resolved = CourseListFilter { kind: Some("club".to_string()), q: Some(" ".to_string()), taught: None, } .resolve() .unwrap(); - assert_eq!(kind.as_ref().map(CourseKind::as_str), Some("club")); - assert_eq!(q.as_deref(), Some(" ")); - assert_eq!(taught, None); + assert_eq!(resolved.kind.as_ref().map(CourseKind::as_str), Some("club")); + assert_eq!(resolved.q.as_deref(), Some(" ")); + assert_eq!(resolved.taught, None); } /// Manager arm: kind and q narrow the catalog, total is the filtered diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index faf7422..e4b29d0 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -255,22 +255,19 @@ async fn list_exams( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; window.validate()?; + let params = service::exam::WindowedListParams { + starts_after: window.starts_after, + ends_after: window.ends_after, + starts_before: window.starts_before, + ends_before: window.ends_before, + limit, + offset, + }; // Visibility and the draft rule ride the same WHERE as the page and the // count: a manager+ reads the whole table, everyone else the exams of // their visible instances — a draft only where they manage the instance. let (exams, total) = if user.get_role().at_least(Role::Manager) { - service::exam::list_windowed( - &st.db, - None, - None, - window.starts_after, - window.ends_after, - window.starts_before, - window.ends_before, - limit, - offset, - ) - .await? + service::exam::list_windowed(&st.db, None, None, params).await? } else { let instances = visible_instances(&user, &st.db).await?; let visible: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect(); @@ -281,18 +278,7 @@ async fn list_exams( .filter(|(_, manages)| *manages) .map(|(instance, _)| instance.get_id().clone()) .collect(); - service::exam::list_windowed( - &st.db, - Some(&visible), - Some(&managed), - window.starts_after, - window.ends_after, - window.starts_before, - window.ends_before, - limit, - offset, - ) - .await? + service::exam::list_windowed(&st.db, Some(&visible), Some(&managed), params).await? }; let items = exams.iter().map(ExamResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset)))