From d8dad926f1eaa0a040d734a6379e8813064bf907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 25 Sep 2026 17:15:46 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(api):=20server-side=20filters?= =?UTF-8?q?=20on=20the=20list=20doors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A caller no longer has to download a capped collection and narrow it in the client: - events, exams: the WindowParams pair is SQL (no whole-table load) and gains starts_before/ends_before, so a past/completed view is expressible - sessions: starts_after/starts_before, half-open months - homework: due_after/due_before (the open/past tabs), class_course - meals menus: slot (was a post-page JS filter — page counts lied) - users (admin): roles= comma set; courses: kind, q, taught - appointments + slots: teacher (or me), starts_after/starts_before, status - pomodoro log: from/to, with the focus total summed in SQL - messages and boards: q (folded literal substring) - pool questions: ?status= is a WHERE, not a post-filter - bank/course-notes id filters: garbage is a 400 naming the field, not an empty page Absent params return today's response byte-shape; page and count share one WHERE. --- src/db/appointment.rs | 178 ++++++--- src/db/appointment_slot.rs | 70 ++-- src/db/board.rs | 127 ++++++- src/db/course.rs | 60 ++- src/db/course_session.rs | 127 ++++++- src/db/event.rs | 184 ++++++++- src/db/exam.rs | 112 +++++- src/db/homework.rs | 293 +++++++++++++-- src/db/menu.rs | 13 +- src/db/message.rs | 191 +++++++++- src/db/pomodoro.rs | 243 ++++++++++-- src/db/pool_question.rs | 137 +++++-- src/db/user.rs | 88 ++++- src/domain/event.rs | 2 +- src/domain/exam.rs | 2 +- src/domain/pool_question.rs | 2 +- src/service/appointment.rs | 279 +++++++++++++- src/service/appointment_slot.rs | 114 +++++- src/service/board.rs | 3 +- src/service/course.rs | 12 +- src/service/course_session.rs | 28 +- src/service/event.rs | 25 +- src/service/exam.rs | 208 ++++++++++- src/service/homework.rs | 48 ++- src/service/menu.rs | 7 +- src/service/message.rs | 3 +- src/service/pomodoro.rs | 16 +- src/service/pool_question.rs | 22 +- src/service/user.rs | 7 +- src/web/appointments.rs | 640 +++++++++++++++++++++++++++++++- src/web/bank_questions.rs | 123 +++++- src/web/boards.rs | 20 +- src/web/course_notes.rs | 89 ++++- src/web/courses.rs | 332 ++++++++++++++++- src/web/events.rs | 44 +-- src/web/exams/mod.rs | 68 ++-- src/web/homework.rs | 524 ++++++++++++++++++++++++-- src/web/instances.rs | 98 ++++- src/web/meals.rs | 58 ++- src/web/messages.rs | 21 +- src/web/page.rs | 119 +++++- src/web/pomodoro.rs | 158 ++++++-- src/web/questions.rs | 31 +- src/web/users.rs | 104 +++++- tests/regress_meals.rs | 158 +++++++- 45 files changed, 4698 insertions(+), 490 deletions(-) diff --git a/src/db/appointment.rs b/src/db/appointment.rs index d1dd943..896ee17 100644 --- a/src/db/appointment.rs +++ b/src/db/appointment.rs @@ -132,86 +132,142 @@ where Ok(appointment) } +/// 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 +/// window otherwise — from below (inclusive) and above (exclusive, so a +/// month is `[start, next_start)`), and `teacher` is the booked slot's +/// teacher — which needs the slot row, so the read runs over a derived table +/// the window and its count share. A booking whose slot is gone has no +/// meeting time and no teacher, so any of those three filters drops it; with +/// no filter the read stays the plain single-table one, so today's rows +/// (dangling bookings included) are untouched. 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, ) -> Result<(Vec, i64), AppError> { - PagedList::new("appointment WHERE requester = $1", "ORDER BY id DESC") - .bind(requester.uuid()) - .run(limit, offset, db) - .await + // 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 + // the table too, so the one clause builder speaks both shapes. + const JOINED: &str = "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \ + a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \ + a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \ + FROM appointment a LEFT JOIN appointment_slot s ON a.slot = s.id \ + WHERE a.requester = $1"; + let joined = teacher.is_some() || starts_after.is_some() || starts_before.is_some(); + let mut from_where = if joined { + JOINED.to_string() + } else { + "appointment a WHERE a.requester = $1".to_string() + }; + // The meeting's start: a standing proposal overrides the slot's window + // (the same rule [`Appointment::window`] applies), so the predicate + // coalesces them — and these clauses only ever ride the joined shape, + // where the slot row is in hand. + let mut next = 2; + if status.is_some() { + from_where.push_str(&format!(" AND a.status = ${next}")); + next += 1; + } + if starts_after.is_some() { + from_where.push_str(&format!( + " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}" + )); + next += 1; + } + if starts_before.is_some() { + from_where.push_str(&format!( + " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}" + )); + next += 1; + } + if teacher.is_some() { + from_where.push_str(&format!(" AND s.teacher = ${next}")); + } + // Close the derived table when the read is the joined shape; the plain + // single-table shape opened none. + if joined { + from_where.push(')'); + } + let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(requester.uuid()); + if let Some(status) = status { + list = list.bind(status.as_str().to_string()); + } + if let Some(after) = starts_after { + list = list.bind(after.as_millis()); + } + if let Some(before) = starts_before { + list = list.bind(before.as_millis()); + } + if let Some(teacher) = teacher { + list = list.bind(teacher.uuid()); + } + list.run(limit, offset, db).await } /// Every booking aimed at `teacher`, across all their slots — the /// teacher's request inbox. The teacher lives on the slot row now, so /// this is a join; the page and its count share the one predicate, and /// the columns are spelled out so the join's duplicate slot-column names -/// can never leak into the row decode. +/// can never leak into the row decode. `status` narrows to one booking +/// state and `starts_after`/`starts_before` to meetings whose effective +/// start (a standing proposal, the slot's window otherwise) sits in +/// `[after, before)` — both bounds optional, both in the SQL, so the +/// count always describes exactly the rows the window pages over. pub async fn list_for_teacher( db: &Database, teacher: &UserId, + status: Option, + starts_after: Option, + starts_before: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - match limit { - None => { - let rows = query_as!( - Appointment, - "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \ - a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \ - a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ - a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ - a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \ - a.cancelled_by AS \"cancelled_by: UserId\", \ - a.cancel_reason AS \"cancel_reason: AppointmentReason\", \ - a.reject_reason AS \"reject_reason: AppointmentReason\", \ - a.created_at AS \"created_at: Timestamp\" \ - FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ - WHERE s.teacher = $1 \ - ORDER BY a.id DESC", - teacher.uuid() - ) - .fetch_all(db) - .await?; - let total = rows.len() as i64; - Ok((rows, total)) - } - Some(limit) => { - let rows = query_as!( - Appointment, - "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \ - a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \ - a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ - a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ - a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \ - a.cancelled_by AS \"cancelled_by: UserId\", \ - a.cancel_reason AS \"cancel_reason: AppointmentReason\", \ - a.reject_reason AS \"reject_reason: AppointmentReason\", \ - a.created_at AS \"created_at: Timestamp\" \ - FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ - WHERE s.teacher = $1 \ - ORDER BY a.id DESC LIMIT $2 OFFSET $3", - teacher.uuid(), - limit, - offset - ) - .fetch_all(db) - .await?; - let total = query!( - "SELECT count(*) AS total \ - FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ - WHERE s.teacher = $1", - teacher.uuid() - ) - .fetch_one(db) - .await? - .total - .unwrap_or(0); - Ok((rows, total)) - } + // The join wrapped as one derived table, so [`PagedList`]'s `SELECT *` + // still sees exactly the appointment columns. + let mut from_where = String::from( + "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \ + a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \ + a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \ + FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ + WHERE s.teacher = $1", + ); + let mut next = 2; + if status.is_some() { + from_where.push_str(&format!(" AND a.status = ${next}")); + next += 1; + } + if starts_after.is_some() { + from_where.push_str(&format!( + " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}" + )); + next += 1; + } + if starts_before.is_some() { + from_where.push_str(&format!( + " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}" + )); + } + // Close the derived table the clauses were appended into. + from_where.push(')'); + let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(teacher.uuid()); + if let Some(status) = status { + list = list.bind(status.as_str().to_string()); + } + if let Some(after) = starts_after { + list = list.bind(after.as_millis()); + } + if let Some(before) = starts_before { + list = list.bind(before.as_millis()); } + list.run(limit, offset, db).await } pub async fn list_for_slot( diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs index a564697..b8e63d9 100644 --- a/src/db/appointment_slot.rs +++ b/src/db/appointment_slot.rs @@ -11,6 +11,7 @@ //! texts; the constraint is the authority a racing publish answers to. use crate::database::{Database, exclusion_violation, tx_with_retry, unique_violation}; +use crate::db::page::PagedList; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -184,23 +185,28 @@ pub async fn read( Ok(slot) } -/// A teacher's own calendar, earliest first. +/// A teacher's own calendar, earliest first. `starts_after` cuts the read in +/// the SQL, so asking for the upcoming window never loads the whole past to +/// slice it in the caller — a calendar of years of weekly publishes stays a +/// bounded scan. The predicate is the same either way, so the filtered and +/// unfiltered reads answer in one shared shape. pub async fn list_for_teacher( db: &Database, teacher: &UserId, + starts_after: Option, ) -> Result, AppError> { - let slots = query_as!( - AppointmentSlot, - "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ - ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ - series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ - FROM appointment_slot WHERE teacher = $1 \ - ORDER BY starts_at ASC, id ASC", - teacher.uuid() - ) - .fetch_all(db) - .await?; - Ok(slots) + let mut from_where = String::from("appointment_slot WHERE teacher = $1"); + if starts_after.is_some() { + from_where.push_str(" AND starts_at >= $2"); + } + let mut list = + PagedList::new(from_where, "ORDER BY starts_at ASC, id ASC").bind(teacher.uuid()); + if let Some(after) = starts_after { + list = list.bind(after.as_millis()); + } + // Unpaged on purpose: the callers slice the window in the web layer. + let (rows, _) = list.run(None, 0, db).await?; + Ok(rows) } /// Every slot whose window has not opened yet, earliest first — the bookable @@ -216,19 +222,33 @@ pub async fn list_for_teacher( pub async fn list_upcoming( db: &Database, from: Timestamp, + teacher: Option<&UserId>, + starts_after: Option, ) -> Result, AppError> { - let slots = query_as!( - AppointmentSlot, - "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ - ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ - series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ - FROM appointment_slot WHERE starts_at > $1 \ - ORDER BY starts_at ASC, id ASC", - from.as_millis() - ) - .fetch_all(db) - .await?; - Ok(slots) + // The strict `starts_at > from` bound is the bookable calendar itself and + // never moves; the optional filters only narrow inside it, each taking + // the placeholder number its bind position gives it. + let mut from_where = String::from("appointment_slot WHERE starts_at > $1"); + let mut next = 2; + if starts_after.is_some() { + from_where.push_str(&format!(" AND starts_at >= ${next}")); + next += 1; + } + if teacher.is_some() { + from_where.push_str(&format!(" AND teacher = ${next}")); + } + let mut list = + PagedList::new(from_where, "ORDER BY starts_at ASC, id ASC").bind(from.as_millis()); + if let Some(after) = starts_after { + list = list.bind(after.as_millis()); + } + if let Some(teacher) = teacher { + list = list.bind(teacher.uuid()); + } + // Unpaged on purpose: the web layer retains the live teachers' rows and + // slices the page after that filter, so the window cannot move into SQL. + let (rows, _) = list.run(None, 0, db).await?; + Ok(rows) } pub async fn list_for_series( diff --git a/src/db/board.rs b/src/db/board.rs index 38a97bd..6f16823 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; use crate::domain::timestamp::Timestamp; +use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::user::UserId; use crate::error::AppError; @@ -130,24 +131,38 @@ pub async fn read(db: &Database, id: &BoardId) -> Result, AppError /// that is locked, or full at its lifetime cap but never drawn on again, is /// never stamped and so reads as **open** — because it is. Only a creator's /// `/close` and the lifetime cap's own refusal ever stamp one. +/// +/// `q` is an optional free-text needle over the title, folded case- and +/// diacritic-insensitively on both sides ([`search_fold`] / +/// [`search_fold_sql`]); a blank needle searches nothing. pub async fn list_for_user( db: &Database, user: &UserId, open: Option, + q: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { + // A blank needle searches nothing, exactly like an absent one. + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); let open_clause = match open { Some(true) => " AND b.closed_at IS NULL", Some(false) => " AND b.closed_at IS NOT NULL", None => "", }; + // The needle rides the same fold on both sides (`position`, not `LIKE`, + // keeps `%` and `_` literal); `$1` and `$2` are always spent on the + // membership predicate, so the needle is `$3`. + let q_clause = match needle { + Some(_) => format!(" AND position($3 in {}) > 0", search_fold_sql("b.title")), + None => String::new(), + }; // `PagedList` wraps `from_where` in `SELECT * FROM (…)`, so the window // is a whole derived table: the row columns plus the roster // re-assembled from `board_participant`, and the membership half of the // predicate as an `EXISTS` over it (the participant-side index covers // it, as the GIN index once did). - PagedList::new( + let mut builder = PagedList::new( format!( "(SELECT b.id, b.creator, b.title, ARRAY(SELECT p.participant FROM board_participant p @@ -156,14 +171,16 @@ pub async fn list_for_user( FROM board b WHERE (b.creator = $1 OR EXISTS (SELECT 1 FROM board_participant bp - WHERE bp.board = b.id AND bp.participant = $2)){open_clause})" + WHERE bp.board = b.id AND bp.participant = $2)){open_clause}{q_clause})" ), "ORDER BY id DESC", ) .bind(user.uuid()) - .bind(user.uuid()) - .run::(limit, offset, db) - .await + .bind(user.uuid()); + if let Some(needle) = needle { + builder = builder.bind(needle); + } + builder.run::(limit, offset, db).await } /// Re-invite: the creator-driven roster replace. The write is the @@ -461,7 +478,7 @@ mod tests { .await; assert!(matches!(over, Err(AppError::Conflict(_)))); - let last = list_for_user(&db, &creator, None, None, 0) + let last = list_for_user(&db, &creator, None, None, None, 0) .await .unwrap() .0 @@ -479,4 +496,102 @@ mod tests { .await; assert!(again.is_ok()); } + + /// `q` narrows by title through the search fold (`geometri` finds + /// `Geometri`), composes with `open`, and pages after the filter + /// (`total` counts matches, not rows) — while the membership predicate + /// still scopes every row: a non-participant searching a real title + /// sees nothing. + #[tokio::test] + async fn q_searches_titles_and_composes_with_open() { + let (db, _leases) = crate::database::init_test_db().await; + let creator = crate::db::class_member::tests::fixture_user(&db, "q-board-kurucu").await; + let outsider = crate::db::class_member::tests::fixture_user(&db, "q-board-disari").await; + + let open_hit = create( + &db, + &creator, + BoardTitle::try_new("Geometri Kampı").unwrap(), + Vec::new(), + ) + .await + .unwrap(); + create( + &db, + &creator, + BoardTitle::try_new("Cebir").unwrap(), + Vec::new(), + ) + .await + .unwrap(); + let closed_hit = create( + &db, + &creator, + BoardTitle::try_new("Geometri Kapanış").unwrap(), + Vec::new(), + ) + .await + .unwrap(); + close(&db, &closed_hit).await.unwrap(); + + // Absent and blank needles both see every board. + let (_, total) = list_for_user(&db, &creator, None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 3); + let (_, total) = list_for_user(&db, &creator, None, Some(" "), None, 0) + .await + .unwrap(); + assert_eq!(total, 3); + + // Title hits through the fold, in both directions. + for needle in ["geometri", "GEOMETRİ"] { + let (hits, total) = + list_for_user(&db, &creator, None, Some(needle), None, 0) + .await + .unwrap(); + assert_eq!(total, 2); + let keys: Vec = hits + .iter() + .map(|board| board.get_id().key().to_string()) + .collect(); + assert!(keys.contains(&open_hit.get_id().key().to_string())); + assert!(keys.contains(&closed_hit.get_id().key().to_string())); + } + + // Composes with `open`. + let (hits, total) = + list_for_user(&db, &creator, Some(true), Some("geometri"), None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(hits[0].get_id().key().to_string(), open_hit.get_id().key().to_string()); + let (_, total) = list_for_user(&db, &creator, Some(false), Some("geometri"), None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + + // The window runs after the filter: `total` counts matches. + let (hits, total) = list_for_user(&db, &creator, None, Some("geometri"), Some(1), 0) + .await + .unwrap(); + assert_eq!(total, 2); + assert_eq!(hits.len(), 1); + + // A needle matching nothing: an empty page, not an error. + let (hits, total) = list_for_user(&db, &creator, None, Some("yok boyle bir tahta"), None, 0) + .await + .unwrap(); + assert_eq!(total, 0); + assert!(hits.is_empty()); + + // The membership predicate still scopes the search: a non-participant + // searching a title that exists finds nothing. + let (hits, total) = + list_for_user(&db, &outsider, None, Some("geometri"), None, 0) + .await + .unwrap(); + assert_eq!(total, 0); + assert!(hits.is_empty()); + } } diff --git a/src/db/course.rs b/src/db/course.rs index 6730597..d0d64d7 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -10,8 +10,9 @@ use crate::constant::COURSE_TABLE; use crate::database::{Database, tx_with_retry, unique_violation}; -use crate::db::page::PagedList; +use crate::db::page::{PagedList, Param}; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; +use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::user::UserId; use crate::error::AppError; use sqlx::PgConnection; @@ -118,6 +119,63 @@ pub async fn list_all(db: &Database) -> Result, AppError> { Ok(rows.into_iter().map(CourseRow::into_course).collect()) } +/// The catalog the visible list's manager arm serves — the whole table, +/// newest first — with the `GET /courses` optional filters pushed into the +/// SQL `WHERE`, so listing one kind (or searching, or the taught/untaught +/// axis) is not a full-catalog pull the caller then throws most of away. +/// `kind` is the exact flavor; `q` is a case- and diacritic-insensitive +/// fragment of the title or the description (blank = no text filter): needle +/// and columns both go through [`crate::domain::text_fold`], so `satranc` +/// finds `Satranç` and back. `position` rather than `LIKE` keeps the needle +/// a *literal* substring — no `%`/`_` wildcard surprises. `taught` keys on +/// the row's own attachment counter: `true` keeps the courses a class +/// section teaches (`class_course_count > 0`), `false` the ones nothing +/// attaches yet. Every filter is part of the one `WHERE` the window and any +/// count share ([`PagedList`]), so a filtered total can never disagree with +/// the rows it counts. +pub async fn list_filtered( + db: &Database, + kind: Option, + q: Option<&str>, + taught: Option, +) -> Result, AppError> { + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); + let mut clauses: Vec = Vec::new(); + let mut binds: Vec = Vec::new(); + if let Some(kind) = &kind { + binds.push(Param::Text(kind.as_str().to_string())); + clauses.push(format!("kind = ${}", binds.len())); + } + if let Some(taught) = taught { + binds.push(Param::I64(0)); + clauses.push(format!( + "class_course_count {} ${}", + if taught { ">" } else { "=" }, + binds.len() + )); + } + if let Some(needle) = &needle { + binds.push(Param::Text(needle.clone())); + let at = binds.len(); + clauses.push(format!( + "(position(${at} in {}) > 0 OR position(${at} in {}) > 0)", + search_fold_sql("title"), + search_fold_sql("description"), + )); + } + let from_where = if clauses.is_empty() { + "course WHERE true".to_string() + } else { + format!("course WHERE {}", clauses.join(" AND ")) + }; + let mut page = PagedList::new(from_where, "ORDER BY id DESC"); + for bind in binds { + page = page.bind(bind); + } + let (rows, _) = page.run::(None, 0, db).await?; + Ok(rows.into_iter().map(CourseRow::into_course).collect()) +} + /// The courses `user` is enrolled in — read through the *instances* their /// enrollments name, since an enrollment keys on the class×course instance. /// The spine of `/courses/me` and the marks report. diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 044f8f9..0cdf42f 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -173,19 +173,36 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result, + starts_before: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "course_session WHERE class_course = $1", - "ORDER BY starts_at DESC, id DESC", - ) - .bind(class_course.uuid()) - .run::(limit, offset, db) - .await + let from_where = match (starts_after, starts_before) { + (Some(_), Some(_)) => { + "course_session WHERE class_course = $1 AND starts_at >= $2 AND starts_at < $3" + } + (Some(_), None) => "course_session WHERE class_course = $1 AND starts_at >= $2", + (None, Some(_)) => "course_session WHERE class_course = $1 AND starts_at < $2", + (None, None) => "course_session WHERE class_course = $1", + }; + let mut list = PagedList::new(from_where, "ORDER BY starts_at DESC, id DESC") + .bind(class_course.uuid()); + if let Some(after) = starts_after { + list = list.bind(after); + } + if let Some(before) = starts_before { + list = list.bind(before); + } + list.run::(limit, offset, db).await } /// Request-scoped: the handler holds nothing across its read and this @@ -339,4 +356,100 @@ mod tests { ) .await; } + + /// One section, three lessons an hour apart across `now`. Starts differ + /// per row: the section's `UNIQUE (class_course, starts_at)` refuses a + /// shared instant, and the window bounds below hang off that middle + /// lesson's exact start. + async fn three_sessions(db: &Database) -> (ClassCourseId, i64) { + let (instance, _) = crate::db::course::a_test_instance(db).await; + let teacher = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", + ) + .bind(teacher.uuid()) + .bind(format!("session-window-{}", &teacher.key()[30..])) + .execute(db) + .await + .unwrap(); + let now = Timestamp::now().as_millis(); + for starts_at in [now - 3_600_000, now, now + 3_600_000] { + create( + db, + &instance, + &teacher, + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(starts_at), + None, + ) + .await + .unwrap(); + } + (instance, now) + } + + #[tokio::test] + async fn the_session_window_is_half_open_on_starts_at() { + let (db, _leases) = crate::database::init_test_db().await; + let (instance, now) = three_sessions(&db).await; + + // Absent bounds: every session, most recent lesson first. + let (rows, total) = list_for_class_course(&db, &instance, None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 3); + let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect(); + assert_eq!(starts, vec![now + 3_600_000, now, now - 3_600_000]); + + // starts_after is inclusive: the middle lesson (exactly `now`) stays, + // and the order does not flip. + let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, None, 0) + .await + .unwrap(); + assert_eq!(total, 2); + let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect(); + assert_eq!(starts, vec![now + 3_600_000, now]); + + // starts_before is strict: the middle lesson is out. + let (rows, total) = list_for_class_course(&db, &instance, None, Some(now), None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(rows[0].get_starts_at().as_millis(), now - 3_600_000); + + // The half-open pair pins exactly the middle lesson. + let (rows, total) = list_for_class_course( + &db, + &instance, + Some(now), + Some(now + 3_600_000), + None, + 0, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_starts_at().as_millis(), now); + + // The limit pages the filtered set; total is the filtered count. + let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, Some(1), 0) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 2)); + assert_eq!(rows[0].get_starts_at().as_millis(), now + 3_600_000); + + // An instant naming no lesson is an empty page, not an error. + let (rows, total) = list_for_class_course( + &db, + &instance, + Some(now + 30 * 86_400_000), + None, + None, + 0, + ) + .await + .unwrap(); + assert!(rows.is_empty() && total == 0); + } } diff --git a/src/db/event.rs b/src/db/event.rs index 2402511..0c1ca83 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -4,7 +4,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; -use crate::db::page::Param; +use crate::db::page::{PagedList, Param}; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::event::{ @@ -68,7 +68,7 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result Result, AppError> { match event.get_audience_kind() { crate::domain::event::EventAudienceKind::School => { - Ok(crate::db::user::list_all(db, None, 0) + Ok(crate::db::user::list_all(db, None, None, 0) .await? .0 .iter() @@ -164,21 +164,55 @@ pub async fn read(db: &Database, id: &EventId) -> Result, AppError Ok(event) } -pub async fn list_all(db: &Database) -> Result, AppError> { - let events = query_as!( - Event, - "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ - audience_kind AS \"audience_kind: EventAudienceKind\", \ - audience_role AS \"audience_role: Role\", \ - audience_course AS \"audience_course: CourseId\", \ - audience_class AS \"audience_class: ClassGroupId\", \ - audience_capacity, starts_at AS \"starts_at: Timestamp\", \ - ends_at AS \"ends_at: Timestamp\" \ - FROM event ORDER BY id DESC", - ) - .fetch_all(db) - .await?; - Ok(events) +/// The event list behind `GET /events`, paged by the database — the window is +/// `LIMIT/OFFSET` in SQL, and `total` a `count(*)` over the same `WHERE`, so +/// a schedule query never decodes the whole table to slice ten rows off it. +/// +/// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule +/// window, validated upstream. All four absent is the unfiltered read, +/// `ORDER BY id DESC` (newest first). Any bound set drops schedule-less rows +/// (every predicate is `NULL`-rejecting) and flips the order to ascending by +/// schedule — `starts_at`, falling back to `ends_at`, ties by id — the same +/// order `WindowParams::apply` used to produce in Rust. +pub async fn list_windowed( + db: &Database, + starts_after: Option, + ends_after: Option, + starts_before: Option, + ends_before: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + // Conditions and binds move together: each bound appends its predicate + // with the placeholder number its bind position lands on. + let mut conds: Vec = Vec::new(); + let mut bounds: Vec = Vec::new(); + let mut bound = |column: &str, op: &str, value: Option| { + if let Some(value) = value { + conds.push(format!("{column} {op} ${}", bounds.len() + 1)); + bounds.push(value); + } + }; + bound("starts_at", ">", starts_after); + bound("starts_at", "<", starts_before); + bound("COALESCE(ends_at, starts_at)", ">", ends_after); + bound("COALESCE(ends_at, starts_at)", "<", ends_before); + let windowed = !conds.is_empty(); + let from_where = if windowed { + format!("event WHERE {}", conds.join(" AND ")) + } else { + "event".to_owned() + }; + let order = if windowed { + "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC" + } else { + "ORDER BY id DESC" + }; + let mut list = PagedList::new(from_where, order); + for value in bounds { + list = list.bind(value); + } + list.run::(limit, offset, db).await } /// Request-scoped: the handler reads the event, then awaits the clock and a @@ -418,4 +452,120 @@ mod tests { ); } } + + /// Four schedule shapes; creation order is id order (uuidv7), so the + /// unfiltered read is exactly the reverse of the creation order. + async fn four_events(db: &Database) -> (UserId, [EventId; 4]) { + let creator = a_person(db, "event-window").await; + let school = EventAudience { + kind: EventAudienceKind::School, + role: None, + course: None, + class: None, + capacity: None, + }; + let now = Timestamp::now().as_millis(); + let past = Timestamp::from_millis(now - 60_000); + let soon = Timestamp::from_millis(now + 30 * 60_000); + let future = Timestamp::from_millis(now + 3_600_000); + let later = Timestamp::from_millis(now + 2 * 3_600_000); + let mut ids = Vec::new(); + for (starts_at, ends_at) in [ + (None, None), // timeless — never survives a window + (Some(past), None), // already started + (Some(soon), None), // ends-only deadline... starts soon + (Some(future), Some(later)), // fully scheduled ahead + ] { + ids.push( + create( + db, + &creator, + EventTitle::try_new("window").unwrap(), + EventDescription::try_new("").unwrap(), + school.clone(), + starts_at, + ends_at, + ) + .await + .unwrap() + .get_id() + .clone(), + ); + } + (creator, ids.try_into().unwrap()) + } + + #[tokio::test] + async fn absent_window_is_the_unfiltered_newest_first_read() { + let (db, _leases) = crate::database::init_test_db().await; + let (_, ids) = four_events(&db).await; + let (events, total) = list_windowed(&db, None, None, None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 4); + let listed: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); + let expected: Vec<_> = ids.iter().rev().cloned().collect(); + assert_eq!(listed, expected); + } + + #[tokio::test] + async fn the_window_filters_and_orders_in_sql_with_a_filtered_total() { + let (db, _leases) = crate::database::init_test_db().await; + let (_, ids) = four_events(&db).await; + let [_, started, soon, ahead] = &ids; + let now = Timestamp::now().as_millis(); + + // ends_after: the timeless and the already-started drop; the ends-only + // event survives on its `ends_at` COALESCE fallback. + let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 2); + let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); + assert_eq!(keys, vec![soon.clone(), ahead.clone()]); + + // A limit applies after the filter: one row out, total still two. + let (events, total) = list_windowed(&db, None, Some(now), None, None, Some(1), 0) + .await + .unwrap(); + assert_eq!((events.len(), total), (1, 2)); + assert_eq!(events[0].get_id(), soon); + // Offset runs inside the filtered set, not past it. + let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 1) + .await + .unwrap(); + assert_eq!((events.len(), total), (1, 2)); + assert_eq!(events[0].get_id(), ahead); + + // starts_before drops the start-less rows and everything starting at + // or after the cut (strict): the cut sits between `soon` (+30 min) + // and `ahead` (+1 h), so `started` and `soon` survive, schedule + // ascending. + let (events, total) = list_windowed( + &db, + None, + None, + Some(now + 45 * 60_000), + None, + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 2); + let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); + assert_eq!(keys, vec![started.clone(), soon.clone()]); + + // ends_before: only the already-started, on its starts_at fallback. + let (_, total) = list_windowed(&db, None, None, None, Some(now - 30_000), None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + + // A well-formed instant naming no row is an empty page, not an error. + let (events, total) = list_windowed(&db, Some(now + 30 * 86_400_000), None, None, None, None, 0) + .await + .unwrap(); + assert!((events.is_empty()) && total == 0); + } } diff --git a/src/db/exam.rs b/src/db/exam.rs index 08d91aa..aae0c2d 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -5,6 +5,7 @@ use sqlx::PgConnection; use crate::database::{Database, foreign_key_violation, tx_with_retry}; +use crate::db::page::{PagedList, Param}; use crate::domain::class_course::ClassCourseId; use crate::domain::course::CourseId; use crate::domain::exam::{ @@ -205,24 +206,96 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> .await?) } -/// The exams, newest first — `ORDER BY id` on a UUIDv7 column is creation -/// order, the sort the old record ids gave for free. -pub async fn list_all(db: &Database) -> Result, AppError> { - Ok(sqlx::query_as!( - Exam, - r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", - class_course AS "class_course: ClassCourseId", term AS "term: TermId", - title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: ExamMode", - starts_at AS "starts_at: Timestamp", - ends_at AS "ends_at: Timestamp", - duration_ms AS "duration_ms: ExamDuration", - max_attempts AS "max_attempts: ExamAttemptLimit", - allow_rejoin, allow_review, draft - FROM exam ORDER BY id DESC"#, - ) - .fetch_all(db) - .await?) +/// 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 +/// the exams it skips. +/// +/// `visible`/`managed` are the non-manager read: the exams addressed to any +/// of `visible` (through `exam_audience`, deduplicated — a shared exam is one +/// 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, +) -> Result<(Vec, i64), AppError> { + // 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 + // window numbering continues after them. + let base = usize::from(visible.is_some()) * 2; + let mut conds: Vec = Vec::new(); + let mut bounds: Vec = Vec::new(); + let mut bound = |column: &str, op: &str, value: Option| { + if let Some(value) = value { + conds.push(format!("{column} {op} ${}", base + bounds.len() + 1)); + bounds.push(value); + } + }; + bound("starts_at", ">", starts_after); + bound("starts_at", "<", starts_before); + bound("COALESCE(ends_at, starts_at)", ">", ends_after); + bound("COALESCE(ends_at, starts_at)", "<", ends_before); + let window = if conds.is_empty() { + String::new() + } else { + format!(" AND {}", conds.join(" AND ")) + }; + let (from_where, mut binds): (String, Vec) = match visible { + None => ( + if conds.is_empty() { + "exam".to_owned() + } else { + format!("exam WHERE {}", conds.join(" AND ")) + }, + Vec::new(), + ), + Some(visible) => { + let managed = managed.expect("visible and managed travel together"); + ( + format!( + "(SELECT DISTINCT ON (e.id) e.* \ + FROM exam e \ + JOIN exam_audience a ON a.exam = e.id \ + WHERE a.class_course = ANY($1::uuid[]) \ + AND (NOT e.draft OR e.class_course = ANY($2::uuid[])){window} \ + ORDER BY e.id)" + ), + vec![ + Param::Texts(visible.iter().map(ClassCourseId::key).collect()), + Param::Texts(managed.iter().map(ClassCourseId::key).collect()), + ], + ) + } + }; + let order = if conds.is_empty() { + "ORDER BY id DESC" + } else { + "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC" + }; + let mut list = PagedList::new(from_where, order); + for bind in binds.drain(..) { + list = list.bind(bind); + } + for value in bounds { + list = list.bind(value); + } + list.run::(limit, offset, db).await } /// The exams of one instance, newest first. @@ -737,7 +810,8 @@ mod tests { /// route funnels through `class_course_of`, which answers /// `Internal("exam references a missing course")`, so an orphan **500s /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while - /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`. + /// [`crate::db::exam::list_windowed`] still hands it to every manager+ on + /// `GET /exams`. /// /// [`create`] therefore *writes* the course row rather than reading /// it ([`cap::touch_and_create`]); the harness and the window it races in diff --git a/src/db/homework.rs b/src/db/homework.rs index 045d437..3ba0a4f 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -13,6 +13,8 @@ use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use sqlx::PgConnection; +use crate::db::page::{PagedList, Param}; + /// The answer a link to a subject that is not there gets, on create and on /// re-tag alike — the conditional claim on the subject row matches nothing, /// and the caller says exactly what the web layer's pre-flight lookup would @@ -199,56 +201,113 @@ pub async fn list_for_class_course( .await?) } +/// The homework table as `SELECT *` cannot read it: the assigned-student +/// roster is not a column but the `homework_assignment` junction, aggregated +/// per row. Every runtime ([`PagedList`]) read of homework selects through +/// this derived table, so its rows decode exactly like the `query_as!` reads +/// beside them; the alias names the row set the outer WHERE filters. +const HOMEWORK_WITH_ASSIGNED: &str = "(SELECT h.*, \ + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a \ + WHERE a.homework = h.id) AS assigned \ + FROM homework h) AS homework"; + /// Every homework in the system, newest first — the manager+ view of the -/// cross-course "my homework" list. -pub async fn list_all(db: &Database) -> Result, AppError> { - Ok(sqlx::query_as!( - Homework, - r#"SELECT id AS "id: HomeworkId", - class_course AS "class_course: ClassCourseId", - subject AS "subject: SubjectId", - title AS "title: HomeworkTitle", - description AS "description: HomeworkDescription", - due_at AS "due_at: Timestamp", - (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a - WHERE a.homework = homework.id) AS "assigned: Vec", - created_by AS "created_by: UserId", - created_at AS "created_at: Timestamp" - FROM homework ORDER BY id DESC"#, - ) - .fetch_all(db) - .await?) +/// cross-course "my homework" list, narrowed by the optional due window and +/// instance scope before anything leaves the database, so a manager asking +/// for open homework never loads the school's whole history. Paged in SQL: +/// a manager retains nothing in Rust, so the window and the count are the +/// database's to do. +pub async fn list_all( + db: &Database, + due_after: Option, + due_before: Option, + class_course: Option<&ClassCourseId>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let mut from_where = HOMEWORK_WITH_ASSIGNED.to_string(); + let mut next = 1; + let mut conds: Vec = Vec::new(); + if due_after.is_some() { + conds.push(format!("due_at >= ${next}")); + next += 1; + } + if due_before.is_some() { + conds.push(format!("due_at < ${next}")); + next += 1; + } + if class_course.is_some() { + conds.push(format!("class_course = ${next}")); + } + if !conds.is_empty() { + from_where.push_str(" WHERE "); + from_where.push_str(&conds.join(" AND ")); + } + let mut list = PagedList::new(from_where, "ORDER BY id DESC"); + if let Some(after) = due_after { + list = list.bind(after); + } + if let Some(before) = due_before { + list = list.bind(before); + } + if let Some(course) = class_course { + list = list.bind(course.uuid()); + } + list.run::(limit, offset, db).await } /// Every homework of every instance in `instances`, newest first (one -/// query) — the cross-instance list over a caller's visible courses. The web -/// layer still trims each instance's rows to what the caller may see (a -/// student to the ones they `student_sees`). +/// query) — the cross-instance list over a caller's visible courses, with +/// the same optional due-window and instance narrowing as the manager view. +/// Unbounded by design: the web layer still trims each instance's rows to +/// what the caller may see (a student to the ones they `student_sees`), and +/// a window here could only hide rows that trim was about to keep. pub async fn list_for_class_courses( db: &Database, instances: &[ClassCourseId], + due_after: Option, + due_before: Option, + class_course: Option<&ClassCourseId>, ) -> Result, AppError> { if instances.is_empty() { return Ok(Vec::new()); } - let ids: Vec = instances.iter().map(ClassCourseId::uuid).collect(); - Ok(sqlx::query_as!( - Homework, - r#"SELECT id AS "id: HomeworkId", - class_course AS "class_course: ClassCourseId", - subject AS "subject: SubjectId", - title AS "title: HomeworkTitle", - description AS "description: HomeworkDescription", - due_at AS "due_at: Timestamp", - (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a - WHERE a.homework = homework.id) AS "assigned: Vec", - created_by AS "created_by: UserId", - created_at AS "created_at: Timestamp" - FROM homework WHERE class_course = ANY($1) ORDER BY id DESC"#, - &ids - ) - .fetch_all(db) - .await?) + // The instance set rides as TEXT: `Param` (the closed bind enum of + // db::page) has no uuid-array arm, and `uuid::text` is the canonical + // lowercase spelling both sides of the comparison agree on. + let scope: Vec = instances.iter().map(|id| id.uuid().to_string()).collect(); + let mut conds: Vec = vec![String::from("class_course::text = ANY($1)")]; + let mut next = 2; + if due_after.is_some() { + conds.push(format!("due_at >= ${next}")); + next += 1; + } + if due_before.is_some() { + conds.push(format!("due_at < ${next}")); + next += 1; + } + if class_course.is_some() { + conds.push(format!("class_course = ${next}")); + } + let from_where = format!( + "{} WHERE {}", + HOMEWORK_WITH_ASSIGNED, + conds.join(" AND ") + ); + let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(Param::Texts(scope)); + if let Some(after) = due_after { + list = list.bind(after); + } + if let Some(before) = due_before { + list = list.bind(before); + } + if let Some(course) = class_course { + list = list.bind(course.uuid()); + } + // No window: the rows in hand are the whole filtered read, which the + // caller retains and pages in the web layer. + let (rows, _) = list.run::(None, 0, db).await?; + Ok(rows) } /// The homework of one instance that `user` is meant to see — whole-class @@ -932,4 +991,160 @@ mod tests { "whole-instance reaches the never-named student" ); } + + /// A real teacher row — `created_by` is a foreign key. + async fn a_teacher(db: &Database) -> UserId { + let teacher = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", + ) + .bind(teacher.uuid()) + .bind(format!("homework-filter-{}", &teacher.key()[30..])) + .execute(db) + .await + .unwrap(); + teacher + } + + /// One homework with a chosen due instant on `instance`. + async fn homework_due( + db: &Database, + instance: &ClassCourseId, + subject: &SubjectId, + due_at: i64, + title: &str, + ) -> Homework { + create( + db, + instance, + subject, + HomeworkTitle::try_new(title).unwrap(), + None, + Timestamp::from_millis(due_at), + None, + &a_teacher(db).await, + ) + .await + .unwrap() + } + + /// The SQL predicates the cross-instance lists gained: the due window and + /// the instance scope both run in the WHERE, and (for the manager path) + /// the page window sits after them, with the count over the same clause. + #[tokio::test] + async fn list_all_filters_by_due_window_and_instance_in_sql() { + let (db, _leases) = crate::database::init_test_db().await; + let (here, _) = crate::db::course::a_test_instance(&db).await; + let (there, course2) = crate::db::course::a_test_instance(&db).await; + let subject = a_subject("matematik", &db).await; + let subject2 = crate::db::subject::create( + &db, + &course2, + SubjectName::try_new("fizik").unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + let now = Timestamp::now().as_millis(); + let day = 86_400_000_i64; + let past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await; + let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await; + let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await; + + // The open tab: due at or after the bound. + let (rows, total) = list_all(&db, Some(now), None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 2); + assert_eq!( + rows.iter().map(Homework::get_id).collect::>(), + vec![other.get_id(), open.get_id()], + "newest first, past rows left out" + ); + // The past tab: due strictly before the bound — the bounds share no + // instant and leave no gap. + let (rows, total) = list_all(&db, None, Some(now), None, None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(rows[0].get_id(), past.get_id()); + // The instance scope: the other instance's rows stay behind. + let (rows, total) = list_all(&db, None, None, Some(&there), None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(rows[0].get_id(), other.get_id()); + // A well-formed id that names no row is an empty page, not an error. + let (rows, total) = list_all(&db, None, None, Some(&ClassCourseId::generate()), None, 0) + .await + .unwrap(); + assert_eq!((rows.len(), total), (0, 0)); + // The page window applies after the filter, and the count stays the + // filtered length, not the page size. + let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 0) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 2)); + let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 1) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 2)); + assert_eq!(rows[0].get_id(), open.get_id()); + // Absent params: every row, unchanged. + let (_, total) = list_all(&db, None, None, None, None, 0).await.unwrap(); + assert_eq!(total, 3); + } + + /// The per-instance path: the caller's instances scope the read in SQL, + /// and the due window and single-instance filter apply on top of it. + #[tokio::test] + async fn list_for_class_courses_applies_the_same_predicates() { + let (db, _leases) = crate::database::init_test_db().await; + let (here, _) = crate::db::course::a_test_instance(&db).await; + let (there, course2) = crate::db::course::a_test_instance(&db).await; + let subject = a_subject("matematik", &db).await; + let subject2 = crate::db::subject::create( + &db, + &course2, + SubjectName::try_new("fizik").unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + let now = Timestamp::now().as_millis(); + let day = 86_400_000_i64; + let _past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await; + let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await; + let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await; + let both = vec![here.clone(), there.clone()]; + + let rows = list_for_class_courses(&db, &both, Some(now), None, None) + .await + .unwrap(); + assert_eq!( + rows.iter().map(Homework::get_id).collect::>(), + vec![other.get_id(), open.get_id()] + ); + let rows = list_for_class_courses(&db, &both, None, Some(now), None) + .await + .unwrap(); + assert_eq!(rows.len(), 1, "the past tab keeps only the past row"); + // A filter naming an instance outside the caller's visible set matches + // nothing — the scopes intersect, they do not override each other. + let rows = list_for_class_courses(&db, &both, None, None, Some(&here)) + .await + .unwrap(); + assert_eq!(rows.len(), 2, "both here rows, past and open"); + let stranger = ClassCourseId::generate(); + let rows = list_for_class_courses(&db, &both, None, None, Some(&stranger)) + .await + .unwrap(); + assert!(rows.is_empty(), "an unknown instance names no row"); + // Absent filters: the whole visible read, unchanged. + let rows = list_for_class_courses(&db, &both, None, None, None) + .await + .unwrap(); + assert_eq!(rows.len(), 3); + } } diff --git a/src/db/menu.rs b/src/db/menu.rs index 010bc82..90c4924 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -135,21 +135,30 @@ pub async fn find( /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; /// either may be omitted (`NULL` bound). The comparison is lexical, which -/// is chronological for this format. +/// is chronological for this format. `slot`, when given, keeps only menus +/// published under that exact snapshotted slot text — deliberately not +/// checked against the school's current `meal_slots`, so a retired slot +/// still finds its menus and an unknown name matches nothing. pub async fn list( db: &Database, from: Option<&MenuDate>, to: Option<&MenuDate>, + slot: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { + // One WHERE for the page and the count alike: a slot filter moves + // `total` with the items, so page numbers count the rows actually + // returned. PagedList::new( "menu WHERE ($1::text IS NULL OR date >= $1::text) \ - AND ($2::text IS NULL OR date <= $2::text)", + AND ($2::text IS NULL OR date <= $2::text) \ + AND ($3::text IS NULL OR slot = $3::text)", "ORDER BY date DESC, slot ASC, id DESC", ) .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) + .bind(Param::OptText(slot.map(|slot| slot.to_string()))) .run(limit, offset, db) .await } diff --git a/src/db/message.rs b/src/db/message.rs index 21abb93..facbe9b 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -8,6 +8,7 @@ use crate::db::page::{PagedList, Param}; use crate::domain::message::{ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, }; +use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -55,14 +56,21 @@ pub async fn send( /// dynamic string assembled, minus the interpolation. They ride the /// [`PagedList`] builder (the paged-list exemption), so the page and its /// count always see the same predicate. +/// +/// `q` is an optional free-text needle over subject and body, folded +/// case- and diacritic-insensitively on both sides ([`search_fold`] / +/// [`search_fold_sql`]); a blank needle searches nothing. pub async fn list_folder( db: &Database, user: &UserId, folder: Folder, read: Option, + q: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { + // A blank needle searches nothing, exactly like an absent one. + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); let home_arm = folder == Folder::Inbox; let mut from = match folder { Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(), @@ -76,8 +84,20 @@ pub async fn list_folder( }; // The `read` filter binds after whichever placeholders the folder shape // spent (`$1` is always the user; the home-folder arm spends `$2`). + let mut next = if home_arm { 3 } else { 2 }; if read.is_some() { - from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 })); + from.push_str(&format!(" AND read = ${next}")); + next += 1; + } + // The needle rides the same fold on both sides (`position`, not `LIKE`, + // keeps `%` and `_` literal). Subject or body — this query joins no + // counterparty, so names are not searched. + if needle.is_some() { + from.push_str(&format!( + " AND (position(${next} in {}) > 0 OR position(${next} in {}) > 0)", + search_fold_sql("subject"), + search_fold_sql("body"), + )); } let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user.uuid()); if home_arm { @@ -86,6 +106,9 @@ pub async fn list_folder( if let Some(read) = read { builder = builder.bind(Param::Bool(read)); } + if let Some(needle) = needle { + builder = builder.bind(needle); + } builder.run(limit, offset, db).await } @@ -280,9 +303,10 @@ mod tests { sent.push(message.get_id().key().to_string()); } - let (listed, total) = list_folder(&db, &recipient, Folder::Inbox, None, None, 0) - .await - .unwrap(); + let (listed, total) = + list_folder(&db, &recipient, Folder::Inbox, None, None, None, 0) + .await + .unwrap(); assert_eq!(total, 25); sent.reverse(); let read_back: Vec = listed @@ -291,4 +315,163 @@ mod tests { .collect(); assert_eq!(read_back, sent); } + + /// `q` folds case and Turkish diacritics on both sides, matches subject + /// or body, composes with `read`, and pages after the filter (`total` + /// counts matches, not rows). The folder predicate still scopes the + /// search: a stranger's folders stay empty no matter what the needle + /// matches in someone else's mail. + #[tokio::test] + async fn q_searches_subject_and_body_and_composes_with_read() { + let (db, _leases) = crate::database::init_test_db().await; + let sender = crate::db::class_member::tests::fixture_user(&db, "q-gonderen").await; + let recipient = crate::db::class_member::tests::fixture_user(&db, "q-alici").await; + let stranger = crate::db::class_member::tests::fixture_user(&db, "q-yabanci").await; + + let subject_hit = send( + &db, + &sender, + &recipient, + MessageSubject::try_new("Matematik Etüt").unwrap(), + MessageBody::try_new("saat üçte").unwrap(), + None, + ) + .await + .unwrap(); + let body_hit = send( + &db, + &sender, + &recipient, + MessageSubject::try_new("duyuru").unwrap(), + MessageBody::try_new("İSTANBUL gezisi etüt sonrası").unwrap(), + None, + ) + .await + .unwrap(); + send( + &db, + &sender, + &recipient, + MessageSubject::try_new("toplantı").unwrap(), + MessageBody::try_new("alakasız").unwrap(), + None, + ) + .await + .unwrap(); + let subject_key = subject_hit.get_id().key().to_string(); + let body_key = body_hit.get_id().key().to_string(); + + // Absent and blank needles both see the whole folder. + let (_, total) = + list_folder(&db, &recipient, Folder::Inbox, None, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 3); + let (_, total) = + list_folder(&db, &recipient, Folder::Inbox, None, Some(" "), None, 0) + .await + .unwrap(); + assert_eq!(total, 3); + + // Subject hit through the fold: `etut` finds `Etüt`. + let (hits, total) = + list_folder(&db, &recipient, Folder::Inbox, None, Some("etut"), None, 0) + .await + .unwrap(); + assert_eq!(total, 2); + let keys: Vec = hits + .iter() + .map(|message| message.get_id().key().to_string()) + .collect(); + assert!(keys.contains(&subject_key)); + assert!(keys.contains(&body_key)); + + // Body hit, case-insensitive in both directions. + let (hits, total) = list_folder( + &db, + &recipient, + Folder::Inbox, + None, + Some("İsTaNbUl"), + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(hits[0].get_id().key().to_string(), body_key); + + // A needle matching nothing: an empty page, not an error. + let (hits, total) = list_folder( + &db, + &recipient, + Folder::Inbox, + None, + Some("yok boyle bir sey"), + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 0); + assert!(hits.is_empty()); + + // The window runs after the filter: `total` counts matches. + let (hits, total) = list_folder( + &db, + &recipient, + Folder::Inbox, + None, + Some("etut"), + Some(1), + 0, + ) + .await + .unwrap(); + assert_eq!(total, 2); + assert_eq!(hits.len(), 1); + + // Composes with `read`: one match read, the other not. + set_read(&db, subject_hit, true).await.unwrap(); + let (_, total) = list_folder( + &db, + &recipient, + Folder::Inbox, + Some(true), + Some("etut"), + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 1); + let (hits, total) = list_folder( + &db, + &recipient, + Folder::Inbox, + Some(false), + Some("etut"), + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 1); + assert_eq!(hits[0].get_id().key().to_string(), body_key); + + // The folder predicate still scopes the search: the stranger's own + // folders are empty even though the needle matches other users' mail. + let (hits, total) = + list_folder(&db, &stranger, Folder::Inbox, None, Some("etut"), None, 0) + .await + .unwrap(); + assert_eq!(total, 0); + assert!(hits.is_empty()); + let (hits, total) = + list_folder(&db, &stranger, Folder::Sent, None, Some("etut"), None, 0) + .await + .unwrap(); + assert_eq!(total, 0); + assert!(hits.is_empty()); + } } diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index d8e41de..6d87313 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -5,11 +5,14 @@ use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS}; use crate::database::{Database, tx_with_retry}; +use crate::db::page::{Param, PagedList}; use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::postgres::PgArguments; use sqlx::query_as; +use sqlx::AssertSqlSafe; /// Start a session for `user`, stamped with the server clock. The open slot /// is the partial unique index (`pomodoro_session_open_stint`): one row per @@ -215,24 +218,94 @@ pub async fn finish(db: &Database, user: &UserId) -> Result Result, AppError> { - let sessions = query_as!( - PomodoroSession, - "SELECT id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ - started_at AS \"started_at: Timestamp\", \ - finished_at AS \"finished_at: Timestamp\", counted, label \ - FROM pomodoro_session WHERE app_user = $1 \ - ORDER BY started_at DESC, id DESC", - user.uuid() - ) - .fetch_all(db) - .await?; - Ok(sessions) +/// One read of the log: the page's rows, the filtered session count, and the +/// filtered focus total — three answers over one `WHERE`, so they can never +/// disagree. +pub(crate) struct PomodoroLogPage { + pub(crate) items: Vec, + /// Sessions in the filtered set, before the page window is applied. + pub(crate) total: i64, + /// `SUM(finished_at - started_at)` over the filtered set, unpaged. + pub(crate) total_focus_ms: i64, +} + +/// The `FROM … WHERE` the page, the count, and the focus sum share, assembled +/// once per read. Placeholders are positional: `$1` is the user, and the +/// bounds follow in `from`, `to` order, present exactly when the arm names +/// them. +fn log_from_where(from: bool, to: bool) -> &'static str { + match (from, to) { + (true, true) => { + "pomodoro_session WHERE app_user = $1 AND started_at >= $2 AND started_at < $3" + } + (true, false) => "pomodoro_session WHERE app_user = $1 AND started_at >= $2", + (false, true) => "pomodoro_session WHERE app_user = $1 AND started_at < $2", + (false, false) => "pomodoro_session WHERE app_user = $1", + } +} + +/// A page of `user`'s log, newest first — the running session (if any) +/// included — with the half-open window `[from, to)` applied *before* both +/// the page window and the sums. Ordered by `started_at`, never by id alone: +/// the log is a chronology, and the id tie-break only ever separates two +/// *finished* stints sharing a `started_at` — there is one running row per +/// user, so it can never tie with itself. +/// +/// With no bounds this is the whole-history read the unpaged `list` used to give. +/// With bounds, answering the page never materializes the log beyond +/// the page itself — the count and the focus total are database scalars over +/// the same `WHERE`. +pub(crate) async fn page_for_user( + db: &Database, + user: &UserId, + from: Option, + to: Option, + limit: Option, + offset: i64, +) -> Result { + let from_where = log_from_where(from.is_some(), to.is_some()); + let mut list = PagedList::new(from_where, "ORDER BY started_at DESC, id DESC").bind(user.uuid()); + if let Some(ms) = from { + list = list.bind(ms); + } + if let Some(ms) = to { + list = list.bind(ms); + } + let (items, total) = list.run(limit, offset, db).await?; + let total_focus_ms = focus_total_ms(db, from_where, user, from, to).await?; + Ok(PomodoroLogPage { + items, + total, + total_focus_ms, + }) +} + +/// `SUM(finished_at - started_at)` over the same filtered set the page reads — +/// one SQL scalar, so the focus total never folds the log in Rust. A running +/// stint contributes nothing (its `finished_at` is `NULL` and `SUM` skips +/// `NULL`), and an empty set `COALESCE`s to zero. `SUM(bigint)` answers +/// `numeric`, hence the `::BIGINT` cast. +async fn focus_total_ms( + db: &Database, + from_where: &str, + user: &UserId, + from: Option, + to: Option, +) -> Result { + let sql = format!( + "SELECT COALESCE(SUM(finished_at - started_at), 0)::BIGINT FROM {from_where}" + ); + let mut args = PgArguments::default(); + Param::Uuid(user.uuid()).add_to(&mut args); + if let Some(ms) = from { + Param::I64(ms).add_to(&mut args); + } + if let Some(ms) = to { + Param::I64(ms).add_to(&mut args); + } + Ok(sqlx::query_scalar_with(AssertSqlSafe(sql), args) + .fetch_one(db) + .await?) } #[cfg(test)] mod tests { @@ -347,6 +420,33 @@ mod tests { finish(db, user).await.unwrap(); } + /// Insert one closed stint at explicit unix-ms stamps — a row the + /// windowed-log tests below can aim bounds at, no clock involved. + /// `counted = NULL` (a pre-rule row) is the honest verdict for a stint no + /// transaction judged. + async fn seeded_stint(user: &UserId, db: &Database, started_at: i64, finished_at: i64) { + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + VALUES ($1, $2, $3, $4, NULL, NULL)", + ) + .bind(PomodoroSessionId::generate().uuid()) + .bind(user.uuid()) + .bind(started_at) + .bind(finished_at) + .execute(db) + .await + .unwrap(); + } + + /// 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 { + page_for_user(db, user, None, None, None, 0) + .await + .unwrap() + .items + } + #[tokio::test] async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { let (db, _leases) = crate::database::init_test_db().await; @@ -569,7 +669,7 @@ mod tests { // Not a study day either — and no streak column was even opened. assert_eq!(streak(&user, &db).await, (0, 0, -1)); // But it happened, and the log says so. - let log = list_for_user(&db, &user).await.unwrap(); + let log = whole_log(&user, &db).await; assert_eq!(log.len(), 1); assert_eq!(log[0].get_finished_at(), short.get_finished_at()); @@ -590,7 +690,7 @@ mod tests { ) ); assert_eq!(streak(&user, &db).await.0, 1); - assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 2); + assert_eq!(whole_log(&user, &db).await.len(), 2); } /// The day quota: it stops the counter, it never stops the log, and it @@ -617,7 +717,7 @@ mod tests { } assert_eq!(counters(&user, &db).await, (finished, focus_ms)); assert_eq!( - list_for_user(&db, &user).await.unwrap().len() as i64, + whole_log(&user, &db).await.len() as i64, MAX_COUNTED_POMODORO_PER_DAY + 3 ); // The quota is a day's, not a lifetime's. @@ -645,7 +745,7 @@ mod tests { assert_eq!(counters(&user, &db).await, (0, 0)); assert_eq!(streak(&user, &db).await, (0, 0, -1)); // Every one of them is still the student's own history. - assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 200); + assert_eq!(whole_log(&user, &db).await.len(), 200); assert!( crate::db::badge::list_for(&db, &user) .await @@ -679,7 +779,7 @@ mod tests { // A restart replaces the dangling session: still one row, fresh clock. let second = start(&db, &user, None).await.unwrap(); assert!(second.get_started_at() >= first.get_started_at()); - let sessions = list_for_user(&db, &user).await.unwrap(); + let sessions = whole_log(&user, &db).await; assert_eq!(sessions.len(), 1); let closed = finish(&db, &user).await.unwrap(); @@ -691,7 +791,7 @@ mod tests { Err(AppError::Conflict(_)) )); start(&db, &user, None).await.unwrap(); - let sessions = list_for_user(&db, &user).await.unwrap(); + let sessions = whole_log(&user, &db).await; assert_eq!(sessions.len(), 2); } @@ -722,4 +822,99 @@ mod tests { assert_eq!(stats.get_pomodoro_sessions(), 1); assert_eq!(stats.get_pomodoro_focus_ms(), 0); } + + /// A timeline the windowed reads aim at: three finished stints + /// (5000 + 500 + 6000 ms of focus) and one still running, which the sums + /// must never mistake for focus. + async fn a_seeded_timeline(db: &Database) -> UserId { + let user = a_user(db).await; + seeded_stint(&user, db, 1000, 6000).await; + seeded_stint(&user, db, 2000, 2500).await; + seeded_stint(&user, db, 3000, 9000).await; + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + VALUES ($1, $2, 4000, NULL, NULL, NULL)", + ) + .bind(PomodoroSessionId::generate().uuid()) + .bind(user.uuid()) + .execute(db) + .await + .unwrap(); + user + } + + fn starts(page: &PomodoroLogPage) -> Vec { + page.items + .iter() + .map(|session| session.get_started_at().as_millis()) + .collect() + } + + #[tokio::test] + async fn the_window_bounds_the_page_the_count_and_the_focus_total_alike() { + let (db, _leases) = crate::database::init_test_db().await; + let user = a_seeded_timeline(&db).await; + + // No bounds: today's whole-history read — every session, newest + // first, and the focus total over all of it (running adds nothing). + let page = page_for_user(&db, &user, None, None, None, 0).await.unwrap(); + assert_eq!(page.total, 4); + assert_eq!(starts(&page), [4000, 3000, 2000, 1000]); + assert_eq!(page.total_focus_ms, 11_500); + + // `from` only: half-open at the start, so the stint opening at 2500 + // itself is out and the ones from 3000 on are in. + let page = page_for_user(&db, &user, Some(2500), None, None, 0) + .await + .unwrap(); + assert_eq!(page.total, 2); + assert_eq!(starts(&page), [4000, 3000]); + assert_eq!(page.total_focus_ms, 6_000); + + // `to` only: exclusive, so the stint starting exactly at 2000 is out. + let page = page_for_user(&db, &user, None, Some(2000), None, 0) + .await + .unwrap(); + assert_eq!(page.total, 1); + assert_eq!(starts(&page), [1000]); + assert_eq!(page.total_focus_ms, 5_000); + + // Both bounds AND together. + let page = page_for_user(&db, &user, Some(1000), Some(3000), None, 0) + .await + .unwrap(); + assert_eq!(page.total, 2); + assert_eq!(starts(&page), [2000, 1000]); + assert_eq!(page.total_focus_ms, 5_500); + + // A window over empty ground answers an empty page, not an error. + let page = page_for_user(&db, &user, Some(10_000), None, None, 0) + .await + .unwrap(); + assert!(page.items.is_empty()); + assert_eq!(page.total, 0); + assert_eq!(page.total_focus_ms, 0); + } + + #[tokio::test] + async fn the_page_window_slices_after_the_time_window() { + let (db, _leases) = crate::database::init_test_db().await; + let user = a_seeded_timeline(&db).await; + + // limit slices the filtered set; `total` stays the filtered count and + // the focus total the filtered sum — not the one listed row's. + let page = page_for_user(&db, &user, Some(2500), None, Some(1), 0) + .await + .unwrap(); + assert_eq!(starts(&page), [4000]); + assert_eq!(page.total, 2); + assert_eq!(page.total_focus_ms, 6_000); + + // offset paging lands inside the filtered order, and the unpaged sums + // span the whole filtered log — 11_500, not the two listed rows' 11_000. + let page = page_for_user(&db, &user, None, None, Some(2), 1).await.unwrap(); + assert_eq!(starts(&page), [3000, 2000]); + assert_eq!(page.total, 4); + assert_eq!(page.total_focus_ms, 11_500); + } } diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index 05990cf..a3eeb0c 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -6,6 +6,7 @@ use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; use crate::database::{Database, tx_with_retry}; +use crate::db::page::{PagedList, Param}; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::{ PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, @@ -51,40 +52,50 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result Result, AppError> { - let rows = sqlx::query_as!( - PoolQuestion, - r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", - title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", - status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId" - FROM pool_question ORDER BY asked_at DESC, id DESC"#, - ) - .fetch_all(db) - .await?; - Ok(rows) -} - -/// The pool as a non-staff user sees it, newest first: every approved -/// question, plus the caller's own pending ones. -pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { - let rows = sqlx::query_as!( - PoolQuestion, - r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", - title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", - status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId" - FROM pool_question - WHERE status = $1 OR asker = $2 - ORDER BY asked_at DESC, id DESC"#, - STATUS_APPROVED, - user.uuid() - ) - .fetch_all(db) - .await?; - Ok(rows) +/// One page of the question list, newest first — plus the `total` count of +/// every row under the *same* filters, so a client can page past the window. +/// +/// `viewer` is the security gate, and it is a WHERE clause, never a +/// post-filter: `None` (teacher+ only) sees every row — the approval queue +/// and the pool together; `Some(me)` sees every `approved` question plus +/// their own pending ones. `status` is the caller's filter, ANDed on top of +/// that gate so it can only ever narrow: `pending` for a student is exactly +/// their own unapproved questions, `approved` the pool, and for teacher+ +/// `pending` is the approval queue. Gate and filter share one statement pair +/// ([`PagedList`]: the shape is runtime-conditional, that builder's named +/// exemption from the compile-time macros), so a `pending` request never +/// loads the approved pool into a `Vec` first and `total` can never disagree +/// with what paging through the list actually yields. +pub async fn list( + db: &Database, + viewer: Option<&UserId>, + status: Option<&str>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let mut clauses: Vec = Vec::new(); + let mut binds: Vec = Vec::new(); + if let Some(viewer) = viewer { + binds.push(Param::Text(STATUS_APPROVED.to_string())); + let pool_arm = format!("status = ${}", binds.len()); + binds.push(Param::Uuid(viewer.uuid())); + let own_arm = format!("asker = ${}", binds.len()); + clauses.push(format!("({pool_arm} OR {own_arm})")); + } + if let Some(status) = status { + binds.push(Param::Text(status.to_string())); + clauses.push(format!("status = ${}", binds.len())); + } + let from_where = if clauses.is_empty() { + "pool_question WHERE true".to_string() + } else { + format!("pool_question WHERE {}", clauses.join(" AND ")) + }; + let mut page = PagedList::new(from_where, "ORDER BY asked_at DESC, id DESC"); + for bind in binds { + page = page.bind(bind); + } + page.run(limit, offset, db).await } /// Publish a pending question into the pool, stamping who approved it. @@ -483,15 +494,65 @@ mod tests { .unwrap(); // The asker sees their own pending question plus the pool; a stranger - // sees only the pool; the teacher view (list_all) sees everything. - assert_eq!(list_visible_to(&db, &asker).await.unwrap().len(), 2); - let stranger_view = list_visible_to(&db, &other).await.unwrap(); + // sees only the pool; the teacher view (viewer = None) sees everything. + let (asker_view, total) = list(&db, Some(&asker), None, None, 0).await.unwrap(); + assert_eq!(asker_view.len(), 2); + assert_eq!(total, 2); + let (stranger_view, total) = list(&db, Some(&other), None, None, 0).await.unwrap(); assert_eq!(stranger_view.len(), 1); + assert_eq!(total, 1); assert_eq!(stranger_view[0].get_id(), published.get_id()); - assert_eq!(list_all(&db).await.unwrap().len(), 2); + let (everything, total) = list(&db, None, None, None, 0).await.unwrap(); + assert_eq!(everything.len(), 2); + assert_eq!(total, 2); assert!(read(&db, pending.get_id()).await.unwrap().is_some()); } + /// The status filter rides the same WHERE as the visibility gate: a + /// student's `pending` page is exactly their own unapproved questions — + /// another student's pending one exists but is not in it — and `total` + /// is the filtered count. Teacher+ `pending` is the whole approval + /// queue, and the window applies after the filter. + #[tokio::test] + async fn status_filter_narrows_within_the_visibility_gate() { + let (db, _leases) = database::init_test_db().await; + let asker = a_user(&db).await; + let other = a_user(&db).await; + let teacher = a_user(&db).await; + + let mine_pending = insert(&db, question(&asker)).await.unwrap(); + let theirs_pending = insert(&db, question(&other)).await.unwrap(); + let mine_pool = insert(&db, question(&asker)).await.unwrap(); + approve(&db, mine_pool.get_id(), &teacher).await.unwrap().unwrap(); + let theirs_pool = insert(&db, question(&other)).await.unwrap(); + approve(&db, theirs_pool.get_id(), &teacher).await.unwrap().unwrap(); + + // Student, pending: their own queue only. + let (items, total) = + list(&db, Some(&asker), Some(STATUS_PENDING), None, 0).await.unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(total, 1); + assert_eq!(items[0].get_id(), mine_pending.get_id()); + assert_ne!(items[0].get_id(), theirs_pending.get_id()); + + // Student, approved: the pool (their gate already was pool + own). + let (items, total) = + list(&db, Some(&asker), Some(STATUS_APPROVED), None, 0).await.unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(total, 2); + + // Teacher+, pending: the full approval queue, whoever asked. + let (items, total) = list(&db, None, Some(STATUS_PENDING), None, 0).await.unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(total, 2); + + // A paged pending request counts the filtered set, not the page. + let (items, total) = + list(&db, None, Some(STATUS_PENDING), Some(1), 0).await.unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(total, 2); + } + #[tokio::test] async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { let (db, _leases) = database::init_test_db().await; diff --git a/src/db/user.rs b/src/db/user.rs index 9659aec..3caee1e 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -172,14 +172,29 @@ pub async fn read(db: &Database, id: &UserId) -> Result, AppError> Ok(user) } +/// Every account, newest first — the web layer's paging read — or, when +/// `roles` is `Some`, only the rows whose role is in the set (the admin +/// directory's tabs; `manager,admin` is one OR, not an AND). The narrowing +/// is the `WHERE` itself, so [`PagedList`] counts the filtered set and a +/// later page stays inside it: page and `total` share this one predicate. pub async fn list_all( db: &Database, + roles: Option<&[Role]>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("app_user", "ORDER BY id DESC") - .run(limit, offset, db) - .await + let list = match roles { + None => PagedList::new("app_user", "ORDER BY id DESC"), + Some(roles) => PagedList::new("app_user WHERE role = ANY($1)", "ORDER BY id DESC").bind( + Param::Texts( + roles + .iter() + .map(|role| role.as_str().to_string()) + .collect(), + ), + ), + }; + list.run(limit, offset, db).await } /// Fetch the users behind `ids` in one query. Ids with no row are simply @@ -1248,4 +1263,71 @@ mod tests { "a missing row is None, not an error" ); } + + /// The admin directory's role tabs: `roles` is the query's `WHERE`, so + /// the page and the `total` share one filtered predicate — a window + /// never leaks another role, and `total` counts the filtered set, not + /// the roster. + #[tokio::test] + async fn the_roles_filter_is_one_where_across_page_and_total() { + let (db, _leases) = init_test_db().await; + let admin = a_user("tabor-admin", &db).await; + crate::service::user::set_role(&db, admin.get_id(), Role::Admin) + .await + .unwrap(); + let manager = a_user("tabor-mgr", &db).await; + crate::service::user::set_role(&db, manager.get_id(), Role::Manager) + .await + .unwrap(); + let _student1 = a_user("tabor-s1", &db).await; + let _student2 = a_user("tabor-s2", &db).await; + + // Matched: only the staff pair, `total` = the filtered count. + let (staff, total) = + list_all(&db, Some(&[Role::Manager, Role::Admin]), None, 0) + .await + .unwrap(); + assert_eq!(total, 2, "total counts the filtered set, not the roster"); + assert!( + staff + .iter() + .all(|user| matches!(user.get_role(), Role::Manager | Role::Admin)), + "no student may ride a staff tab" + ); + + // Unmatched: a well-formed set naming nobody is an empty page, not + // an error. + let (none, total) = list_all(&db, Some(&[Role::Parent]), None, 0) + .await + .unwrap(); + assert!(none.is_empty()); + assert_eq!(total, 0); + + // Absent: the whole roster, exactly the unfiltered read. + let (all, total) = list_all(&db, None, None, 0).await.unwrap(); + assert_eq!(total, 4); + assert_eq!(all.len(), 4); + + // The window applies AFTER the filter: a page of 1 inside the staff + // set still counts 2, and walking the windows collects exactly the + // staff pair — never a student. + let (page1, total) = + list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 0) + .await + .unwrap(); + assert_eq!(total, 2); + assert_eq!(page1.len(), 1); + let (page2, _) = + list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 1) + .await + .unwrap(); + assert_eq!(page2.len(), 1); + let mut both: Vec<_> = page1 + .iter() + .chain(page2.iter()) + .map(|user| user.get_role()) + .collect(); + both.sort(); + assert_eq!(both, vec![Role::Manager, Role::Admin]); + } } diff --git a/src/domain/event.rs b/src/domain/event.rs index 5d0e9f3..a06389f 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -15,7 +15,7 @@ pub struct EventId(uuid::Uuid); impl EventId { /// Minted from the process-wide monotonic generator, not a plain random /// UUID: events list `id DESC` (newest first, - /// [`crate::db::event::list_all`]), + /// [`crate::db::event::list_windowed`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(next_uuid()) diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 3aeaa80..6bb39e2 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -28,7 +28,7 @@ pub struct ExamId(uuid::Uuid); impl ExamId { /// Minted from the process-wide monotonic generator, not a plain random /// UUID: exams list `id DESC` (newest first, - /// [`crate::db::exam::list_all`]), + /// [`crate::db::exam::list_windowed`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(next_uuid()) diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index f8eb885..8d949fa 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -33,7 +33,7 @@ pub struct PoolQuestionId(Uuid); impl PoolQuestionId { /// Minted from the process-wide monotonic generator, not a random v4: /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break - /// ([`crate::db::pool_question::list_all`]), + /// ([`crate::db::pool_question::list`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(next_uuid()) diff --git a/src/service/appointment.rs b/src/service/appointment.rs index a0e6e36..2314b38 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -119,24 +119,48 @@ pub async fn read(db: &Database, id: &AppointmentId) -> Result, + starts_after: Option, + starts_before: Option, + teacher: Option<&UserId>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - appointment::list_for_requester(db, requester, limit, offset).await + appointment::list_for_requester( + db, + requester, + status, + starts_after, + starts_before, + teacher, + limit, + offset, + ) + .await } -/// Every booking aimed at `teacher`, newest first — the request inbox. +/// Every booking aimed at `teacher`, newest first — the request inbox, +/// narrowed by the door's optional `status` and `starts_after`/`starts_before` +/// filters. The inbox is the teacher's own universe already, so it takes no +/// teacher filter: narrowing is the web layer's call. pub async fn list_for_teacher( db: &Database, teacher: &UserId, + status: Option, + starts_after: Option, + starts_before: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - appointment::list_for_teacher(db, teacher, limit, offset).await + appointment::list_for_teacher(db, teacher, status, starts_after, starts_before, limit, offset) + .await } /// Confirm the meeting at the slot's own window. Re-runs the double-booking @@ -841,4 +865,251 @@ mod tests { assert_eq!(second.get_status(), AppointmentStatus::Pending); assert_eq!(occupied(slot.get_id(), &db).await, 1); } + + /// The listing filters narrow each side's own universe: `status` to one + /// state, `starts_after` to meetings whose effective start (a standing + /// proposal, the slot's window otherwise) is at or after the instant, + /// `teacher` to the booked slot's teacher — and the paging window applies + /// after all of it, with `total` counting the filtered set, not the page. + /// Absent filters, the listings answer exactly as before, dangling rows + /// included. + #[tokio::test] + async fn listings_filter_by_status_start_and_teacher() { + let (db, _leases) = init_test_db().await; + let ali = a_person(&db, "ali", "teacher").await; + let ayse = a_person(&db, "ayse", "teacher").await; + let veli = a_person(&db, "veli", "student").await; + let reason = AppointmentReason::try_new("görüşme").unwrap(); + let now = Timestamp::now().as_millis(); + let at = |millis: i64| Timestamp::from_millis(millis); + + let ali_slot = + appointment_slot::create(&db, &ali, at(now + 60_000), at(now + 120_000), None) + .await + .unwrap(); + let ayse_slot = + appointment_slot::create(&db, &ayse, at(now + 200_000), at(now + 260_000), None) + .await + .unwrap(); + let pending = book(&db, ali_slot.get_id(), &veli, reason.clone()) + .await + .unwrap(); + let approved = book(&db, ayse_slot.get_id(), &veli, reason.clone()) + .await + .unwrap(); + approve(&db, approved.get_id(), &ayse).await.unwrap(); + let settled_slot = + appointment_slot::create(&db, &ali, at(now + 300_000), at(now + 360_000), None) + .await + .unwrap(); + let cancelled = book(&db, settled_slot.get_id(), &veli, reason.clone()) + .await + .unwrap(); + cancel(&db, cancelled.get_id(), &veli, None).await.unwrap(); + + // 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(); + 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, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + 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, + ) + .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(); + 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, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (2, 2)); + 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(); + assert_eq!((page1.len(), total), (1, 3)); + let (page2, total) = + list_for_requester(&db, &veli, None, None, None, None, Some(1), 1).await.unwrap(); + assert_eq!((page2.len(), total), (1, 3)); + assert_ne!(page1[0].get_id(), page2[0].get_id()); + + // A standing proposal moves the meeting's start for the cut: the + // pending booking proposes itself to now + 500_000, so it alone + // clears a cut at now + 400_000. + 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, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), pending.get_id()); + + // The inbox: ali's two bookings and never ayse's — the join's + // teacher predicate is the whole visibility universe here. + let (rows, total) = + list_for_teacher(&db, &ali, None, None, None, None, 0).await.unwrap(); + assert_eq!((rows.len(), total), (2, 2)); + let (rows, total) = list_for_teacher(&db, &ali, Some(AppointmentStatus::Cancelled), None, None, None, + 0, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), cancelled.get_id()); + let (_, total) = + list_for_teacher(&db, &ali, None, Some(at(now + 400_000)), None, None, 0) + .await + .unwrap(); + assert_eq!(total, 1); + let (rows, total) = + list_for_teacher(&db, &ali, None, None, None, Some(1), 0).await.unwrap(); + assert_eq!((rows.len(), total), (1, 2)); + + // A settled booking whose slot is withdrawn still lists unfiltered — + // today's shape — and the time and teacher filters drop it: it has + // neither a meeting window nor a teacher any more. The guarded + // delete sweeps its settled bookings along, so the dangling shape is + // forced here the way a demotion sweep leaves it: the slot row goes, + // and the slot's `ON DELETE SET NULL` strands the booking. + sqlx::query("DELETE FROM appointment_slot WHERE id = $1") + .bind(settled_slot.get_id().uuid()) + .execute(&db) + .await + .unwrap(); + let (rows, total) = + list_for_requester(&db, &veli, None, None, None, None, None, 0).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, + ) + .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(); + assert_eq!((rows.len(), total), (1, 1), "a windowless row names no teacher"); + assert_eq!(rows[0].get_id(), pending.get_id()); + } + + /// `starts_before` is the upper edge of a half-open month window: a row + /// starting before the bound is out, a row inside it stays, the bound + /// instant itself is excluded, and absent the set is unchanged. + #[tokio::test] + async fn starts_before_bounds_the_meeting_exclusively() { + let (db, _leases) = init_test_db().await; + let teacher = a_person(&db, "t1", "teacher").await; + let veli = a_person(&db, "veli", "student").await; + let reason = AppointmentReason::try_new("görüşme").unwrap(); + let now = Timestamp::now().as_millis(); + let at = |millis: i64| Timestamp::from_millis(millis); + + // Two bookings: one before the bound, one after it. + let early_slot = + appointment_slot::create(&db, &teacher, at(now + 60_000), at(now + 120_000), None) + .await + .unwrap(); + let late_slot = + appointment_slot::create(&db, &teacher, at(now + 200_000), at(now + 260_000), None) + .await + .unwrap(); + let early = book(&db, early_slot.get_id(), &veli, reason.clone()) + .await + .unwrap(); + let late = book(&db, late_slot.get_id(), &veli, reason.clone()) + .await + .unwrap(); + + // 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(); + 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, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), early.get_id()); + + // Half-open: the bound instant itself is outside the window, so a + // cut exactly at the late meeting's start keeps only the early one — + // and the inbox answers the same way. + let (rows, total) = list_for_requester( + &db, + &veli, + None, + None, + Some(at(now + 200_000)), + None, + None, + 0, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), early.get_id()); + + let (rows, total) = + list_for_teacher(&db, &teacher, None, None, Some(at(now + 150_000)), None, 0) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), early.get_id()); + + // Composed with starts_after, the pair is the month window: only the + // late meeting sits in [now + 150_000, now + 260_000). + let (rows, total) = list_for_requester( + &db, + &veli, + None, + Some(at(now + 150_000)), + Some(at(now + 260_000)), + None, + None, + 0, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 1)); + assert_eq!(rows[0].get_id(), late.get_id()); + } } diff --git a/src/service/appointment_slot.rs b/src/service/appointment_slot.rs index 503ed25..c3ca2bd 100644 --- a/src/service/appointment_slot.rs +++ b/src/service/appointment_slot.rs @@ -27,21 +27,37 @@ pub async fn read( appointment_slot::read(db, id).await } -/// A teacher's own calendar, earliest first — the web layer's calendar read. +/// A teacher's own calendar, earliest first — the plain, unfiltered read. pub async fn list_for_teacher( db: &Database, teacher: &UserId, ) -> Result, AppError> { - appointment_slot::list_for_teacher(db, teacher).await + appointment_slot::list_for_teacher(db, teacher, None).await +} + +/// The calendar read the slots door runs: `teacher`'s published rows, +/// earliest first, cut to windows starting at or after `starts_after` when +/// the caller asked. The cut is the SQL's, so a calendar with years of past +/// publishes answers from the asked-for window onward without loading its +/// whole history to slice it afterwards. +pub async fn list_calendar( + db: &Database, + teacher: &UserId, + starts_after: Option, +) -> Result, AppError> { + appointment_slot::list_for_teacher(db, teacher, starts_after).await } /// Every slot whose window has not opened yet, earliest first — the bookable -/// calendar a requester browses. +/// calendar a requester browses, narrowed by the door's optional `teacher` +/// and `starts_after` filters (which only cut inside the upcoming set). pub async fn list_upcoming( db: &Database, from: Timestamp, + teacher: Option<&UserId>, + starts_after: Option, ) -> Result, AppError> { - appointment_slot::list_upcoming(db, from).await + appointment_slot::list_upcoming(db, from, teacher, starts_after).await } /// Every slot of one recurring publish, earliest first. @@ -563,4 +579,94 @@ mod tests { )); assert!(list_for_teacher(&db, &teacher).await.unwrap().is_empty()); } + + /// The calendar read stays within the named teacher's rows after the + /// rewrite to the runtime builder — the slots door's whole visibility + /// universe hangs on that predicate. + #[tokio::test] + async fn the_calendar_read_names_only_its_own_teachers_rows() { + let (db, _leases) = crate::database::init_test_db().await; + let ali = a_person(&db, "ali", "teacher").await; + let ayse = a_person(&db, "ayse", "teacher").await; + create(&db, &ali, at(1_000), at(2_000), None).await.unwrap(); + create(&db, &ayse, at(3_000), at(4_000), None).await.unwrap(); + + let calendar = list_for_teacher(&db, &ali).await.unwrap(); + assert_eq!(calendar.len(), 1); + assert_eq!(calendar[0].get_teacher(), &ali); + } + + /// The calendar cut is the SQL's: `starts_after` drops the past + /// occurrences from the read instead of loading the whole history for the + /// caller to slice, so the filtered length the web layer reports is the + /// filtered count. The instant is inclusive. + #[tokio::test] + async fn the_calendar_start_cut_is_sql_side_and_inclusive() { + let (db, _leases) = crate::database::init_test_db().await; + let teacher = a_person(&db, "t1", "teacher").await; + let now = Timestamp::now().as_millis(); + create(&db, &teacher, at(now - 10_000), at(now - 5_000), None) + .await + .unwrap(); + create(&db, &teacher, at(now + 10_000), at(now + 20_000), None) + .await + .unwrap(); + + // Absent: both, earliest first — the calendar as it has always read. + let all = list_for_teacher(&db, &teacher).await.unwrap(); + assert_eq!(all.len(), 2); + assert!(all[0].get_starts_at().as_millis() < all[1].get_starts_at().as_millis()); + + // Filtered: only the future one; the cut instant itself would match. + let upcoming = list_calendar(&db, &teacher, Some(at(now))).await.unwrap(); + assert_eq!(upcoming.len(), 1); + assert_eq!(upcoming[0].get_starts_at().as_millis(), now + 10_000); + } + + /// The bookable read narrows inside the upcoming set: the strict + /// `starts_at > now` bound never moves, the teacher filter names one + /// publisher, and the instant cut is inclusive. Absent, the read is the + /// whole calendar exactly as before. + #[tokio::test] + async fn the_upcoming_read_narrows_without_moving_the_bound() { + let (db, _leases) = crate::database::init_test_db().await; + let ali = a_person(&db, "ali", "teacher").await; + let ayse = a_person(&db, "ayse", "teacher").await; + let now = Timestamp::now().as_millis(); + create(&db, &ali, at(now - 10_000), at(now - 5_000), None) + .await + .unwrap(); + create(&db, &ali, at(now + 5_000), at(now + 10_000), None) + .await + .unwrap(); + create(&db, &ali, at(now + 60_000), at(now + 90_000), None) + .await + .unwrap(); + create(&db, &ayse, at(now + 30_000), at(now + 40_000), None) + .await + .unwrap(); + + let from = at(now); + // Absent: the strict bound holds — ali's past slot is out, three in. + let all = list_upcoming(&db, from, None, None).await.unwrap(); + assert_eq!(all.len(), 3); + + // teacher: only that teacher, past stays out. + let ali_only = list_upcoming(&db, from, Some(&ali), None).await.unwrap(); + assert_eq!(ali_only.len(), 2); + assert!(ali_only.iter().all(|slot| slot.get_teacher() == &ali)); + + // starts_after is inclusive: the two slots at or after the cut. + let cut = list_upcoming(&db, from, None, Some(at(now + 30_000))) + .await + .unwrap(); + assert_eq!(cut.len(), 2); + + // Both filters together. + let both = list_upcoming(&db, from, Some(&ayse), Some(at(now + 30_000))) + .await + .unwrap(); + assert_eq!(both.len(), 1); + assert_eq!(both[0].get_teacher(), &ayse); + } } diff --git a/src/service/board.rs b/src/service/board.rs index faec9f7..f022bed 100644 --- a/src/service/board.rs +++ b/src/service/board.rs @@ -181,10 +181,11 @@ pub async fn list_for_user( db: &Database, user: &UserId, open: Option, + q: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - board::list_for_user(db, user, open, limit, offset).await + board::list_for_user(db, user, open, q, limit, offset).await } pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { diff --git a/src/service/course.rs b/src/service/course.rs index d786db4..4a31e6d 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -31,8 +31,16 @@ pub async fn read(db: &Database, id: &CourseId) -> Result, AppErr course::read(db, id).await } -pub async fn list_all(db: &Database) -> Result, AppError> { - course::list_all(db).await +/// The catalog the visible list's manager arm serves, optionally narrowed by +/// the `GET /courses` filters (`kind`, folded `q`) — pushed into the SQL so +/// listing one kind is not a full-catalog pull. +pub async fn list_filtered( + db: &Database, + kind: Option, + q: Option<&str>, + taught: Option, +) -> Result, AppError> { + course::list_filtered(db, kind, q, taught).await } pub async fn list_enrolled( diff --git a/src/service/course_session.rs b/src/service/course_session.rs index 7b2a9c8..b06a105 100644 --- a/src/service/course_session.rs +++ b/src/service/course_session.rs @@ -73,14 +73,38 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result, offset: i64, ) -> Result<(Vec, i64), AppError> { - course_session::list_for_class_course(db, class_course, limit, offset).await + list_windowed(db, class_course, None, None, limit, offset).await +} + +/// The same timetable read narrowed to a half-open `[starts_after, +/// starts_before)` on `starts_at` — a calendar month is +/// `[month_start, next_month_start)`. The page and the count share the one +/// SQL `WHERE`; the order does not flip. +pub async fn list_windowed( + db: &Database, + class_course: &ClassCourseId, + starts_after: Option, + starts_before: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course_session::list_for_class_course( + db, + class_course, + starts_after, + starts_before, + limit, + offset, + ) + .await } /// Only what the request carried is written: an omitted field (`None`) is diff --git a/src/service/event.rs b/src/service/event.rs index 35bb942..91d9cf2 100644 --- a/src/service/event.rs +++ b/src/service/event.rs @@ -37,9 +37,28 @@ pub async fn read(db: &Database, id: &EventId) -> Result, AppError event::read(db, id).await } -/// Every event, newest first. -pub async fn list_all(db: &Database) -> Result, AppError> { - event::list_all(db).await +/// The `GET /events` list — visibility-free (every authenticated user sees +/// every event), the schedule window and the page pushed into SQL. All four +/// window bounds absent is the unfiltered, newest-first read. +pub async fn list_windowed( + db: &Database, + starts_after: Option, + ends_after: Option, + starts_before: Option, + ends_before: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + event::list_windowed( + db, + starts_after, + ends_after, + starts_before, + ends_before, + limit, + offset, + ) + .await } /// Only what the request carried is written: an omitted field (`None`) is diff --git a/src/service/exam.rs b/src/service/exam.rs index ac2de48..0c14e0a 100644 --- a/src/service/exam.rs +++ b/src/service/exam.rs @@ -113,8 +113,34 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> exam::read(db, id).await } -pub async fn list_all(db: &Database) -> Result, AppError> { - exam::list_all(db).await +/// The `GET /exams` list. `visible`/`managed` are the non-manager read (the +/// exams of the caller's visible instances, a draft only where they manage +/// the owner instance); both `None` is the manager+ whole-table read. The +/// schedule window, the visibility, the draft rule, the page, and the count +/// share one SQL `WHERE` — see [`exam::list_windowed`]. +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, +) -> Result<(Vec, i64), AppError> { + exam::list_windowed( + db, + visible, + managed, + starts_after, + ends_after, + starts_before, + ends_before, + limit, + offset, + ) + .await } /// One instance's exams, newest first — the read behind @@ -126,16 +152,6 @@ pub async fn list_for_class_course( exam::list_for_class_course(db, class_course).await } -/// Every exam of every instance in `instances` (one query) — the report-card -/// and marks reports' cross-instance read, and the list behind a caller's -/// visible instances. -pub async fn list_for_class_course_courses( - db: &Database, - instances: &[ClassCourseId], -) -> Result, AppError> { - exam::list_for_class_course_courses(db, instances).await -} - /// Every exam of every catalog course in `courses` (one query) — the catalog /// as one user sees it, across the instances those courses are taught in. pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result, AppError> { @@ -821,4 +837,172 @@ mod tests { "neither refusal wrote" ); } + + /// An exam with full control over the schedule and the draft flag — the + /// window and draft-rule tests need shapes [`exam_on`] does not make. + async fn exam_shaped( + db: &Database, + instance: &ClassCourse, + schedule: ExamSchedule, + draft: bool, + title: &str, + ) -> Exam { + let creator = crate::db::class_member::tests::fixture_user(db, "window-author").await; + let term = crate::db::term::a_test_term(db).await; + let allowed = Settings::defaults().get_exam_kinds().to_vec(); + crate::db::exam::create( + db, + &creator, + instance.get_id(), + &term, + ExamTitle::try_new(title).unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("yazili", &allowed).unwrap(), + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + draft, + ) + .await + .unwrap() + } + + /// `list_windowed` in SQL must answer exactly what the old + /// list-and-retain read answered: visibility (any addressed instance), + /// the draft rule (only where the caller manages the owner instance), + /// the schedule window (schedule-less rows out, ascending order), and a + /// `total` that is the filtered count even when the page is short. + #[tokio::test] + async fn the_exam_list_window_keeps_visibility_and_draft_rules() { + let (db, _leases) = crate::database::init_test_db().await; + let manager = staff(&db, "window-mudur", Role::Manager).await; + let algebra = crate::db::class_member::tests::a_course("algebra", &db).await; + let geometry = crate::db::class_member::tests::a_course("geometry", &db).await; + let a = instance_in(&db, manager.get_id(), "8-A", &algebra, None).await; + let b = instance_in(&db, manager.get_id(), "8-B", &geometry, None).await; + + let now = Timestamp::now().as_millis(); + let sync = + |starts_at: i64| -> ExamSchedule { + ExamSchedule::try_new( + Some(ExamMode::try_new("sync").unwrap()), + Some(Timestamp::from_millis(starts_at)), + Some(Timestamp::from_millis(starts_at + 3_600_000)), + None, + ) + .unwrap() + }; + // On A: a scheduled exam ahead, a scheduled draft ahead, a + // window-less (`sync`-less, so no-mode) published exam, and one that + // already ran. On B: a draft of *another* instance. + let ahead = exam_shaped(&db, &a, sync(now + 3_600_000), false, "ahead").await; + let ahead_draft = exam_shaped(&db, &a, sync(now + 3_600_000), true, "ahead-draft").await; + let open = exam_shaped(&db, &a, ExamSchedule::default(), false, "open").await; + let ran = exam_shaped(&db, &a, sync(now - 3_600_000), false, "ran").await; + 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) + .await + .unwrap(); + assert_eq!(total, 5); + let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect(); + assert_eq!( + listed, + [&other_draft, &ran, &open, &ahead_draft, &ahead] + .into_iter() + .map(|exam| exam.get_id().clone()) + .collect::>() + ); + + // Manager+ WITH a window: the window predicates must name the + // 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(); + assert_eq!(total, 3); + let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect(); + assert_eq!( + listed, + [&ahead, &ahead_draft, &other_draft] + .into_iter() + .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(); + 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 + // drafts (A's own and the other instance's) stay hidden. + 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) + .await + .unwrap(); + assert_eq!(total, 3); + assert!(rows.iter().all(|exam| !exam.is_draft())); + + // 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) + .await + .unwrap(); + assert_eq!(total, 4); + assert!(rows.iter().any(|exam| exam.get_id() == ahead_draft.get_id())); + assert!(!rows.iter().any(|exam| exam.get_id() == other_draft.get_id())); + + // The window rides the same WHERE: `ends_after=now` keeps the + // scheduled ahead pair (the draft included — a draft is visible where + // it is visible), drops the open exam (no schedule) and the one that + // ran, and flips the order to schedule ascending, id tie-break. + let (rows, total) = list_windowed( + &db, + Some(&visible), + Some(&manages_a), + None, + Some(now), + None, + None, + None, + 0, + ) + .await + .unwrap(); + assert_eq!(total, 2); + let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect(); + assert_eq!(listed, vec![ahead.get_id().clone(), ahead_draft.get_id().clone()]); + + // A short page of the filtered set still reports the filtered total. + let (rows, total) = list_windowed( + &db, + Some(&visible), + Some(&manages_a), + None, + Some(now), + None, + None, + Some(1), + 0, + ) + .await + .unwrap(); + assert_eq!((rows.len(), total), (1, 2)); + + // A viewer of B manages nothing, and B's only exam is a draft: the + // 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) + .await + .unwrap(); + assert!(rows.is_empty() && total == 0); + } } diff --git a/src/service/homework.rs b/src/service/homework.rs index 3a0cb20..205e440 100644 --- a/src/service/homework.rs +++ b/src/service/homework.rs @@ -63,8 +63,38 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result, Ap homework::read(db, id).await } -pub async fn list_all(db: &Database) -> Result, AppError> { - homework::list_all(db).await +/// The optional predicates of the cross-instance homework reads — the +/// `?due_after=&due_before=&class_course=` scoping of `GET /homework`. +/// Absent fields widen the read; none of them widens the caller's +/// visibility, which the web layer still applies on top. +#[derive(Debug, Clone, Default)] +pub struct HomeworkListFilter { + /// Keep homework due at or after this instant (Unix ms) — the open tab. + pub due_after: Option, + /// Keep homework due before this instant (Unix ms) — the past tab. + pub due_before: Option, + /// Keep only this class×course instance's homework. + pub class_course: Option, +} + +/// Every homework, newest first — the manager+ view, narrowed by `filter` +/// in SQL and paged in the database (a manager retains nothing in Rust, so +/// the window and the count are both the database's). +pub async fn list_all( + db: &Database, + filter: &HomeworkListFilter, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + homework::list_all( + db, + filter.due_after, + filter.due_before, + filter.class_course.as_ref(), + limit, + offset, + ) + .await } /// The homework of one class×course instance, newest first — the read behind @@ -77,12 +107,22 @@ pub async fn list_for_class_course( } /// Every homework of every instance in `instances` (one query) — the read -/// behind a caller's visible courses. +/// behind a caller's visible courses, narrowed by `filter` in SQL. Unpaged: +/// the caller may still drop rows in Rust (a student's audience), so a +/// window here could only hide rows that trim was about to keep. pub async fn list_for_class_courses( db: &Database, instances: &[ClassCourseId], + filter: &HomeworkListFilter, ) -> Result, AppError> { - homework::list_for_class_courses(db, instances).await + homework::list_for_class_courses( + db, + instances, + filter.due_after, + filter.due_before, + filter.class_course.as_ref(), + ) + .await } /// The homework of one instance that `user` is meant to see — the per-instance diff --git a/src/service/menu.rs b/src/service/menu.rs index 1895b06..fc89ec6 100644 --- a/src/service/menu.rs +++ b/src/service/menu.rs @@ -42,15 +42,18 @@ pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> menu::read(db, id).await } -/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds. +/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds. `slot`, +/// when given, narrows to menus published under that exact snapshotted +/// slot text. pub async fn list( db: &Database, from: Option<&MenuDate>, to: Option<&MenuDate>, + slot: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - menu::list(db, from, to, limit, offset).await + menu::list(db, from, to, slot, limit, offset).await } /// Change a menu's seat cap; `None` keeps it, `Some(None)` clears it. diff --git a/src/service/message.rs b/src/service/message.rs index 0c15040..e3013b5 100644 --- a/src/service/message.rs +++ b/src/service/message.rs @@ -29,10 +29,11 @@ pub async fn list_folder( user: &UserId, folder: Folder, read: Option, + q: Option<&str>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - message::list_folder(db, user, folder, read, limit, offset).await + message::list_folder(db, user, folder, read, q, limit, offset).await } pub async fn read_for( diff --git a/src/service/pomodoro.rs b/src/service/pomodoro.rs index 7994e20..8c7d217 100644 --- a/src/service/pomodoro.rs +++ b/src/service/pomodoro.rs @@ -5,6 +5,7 @@ use crate::database::Database; use crate::db::pomodoro; +pub(crate) use crate::db::pomodoro::PomodoroLogPage; use crate::domain::pomodoro::PomodoroSession; use crate::domain::user::UserId; use crate::error::AppError; @@ -25,7 +26,16 @@ pub async fn finish(db: &Database, user: &UserId) -> Result Result, AppError> { - pomodoro::list_for_user(db, user).await +/// A page of `user`'s log, newest first — the running one included — with the +/// half-open `[from, to)` window (unix ms) applied before the count and the +/// focus sum. +pub(crate) async fn page_for_user( + db: &Database, + user: &UserId, + from: Option, + to: Option, + limit: Option, + offset: i64, +) -> Result { + pomodoro::page_for_user(db, user, from, to, limit, offset).await } diff --git a/src/service/pool_question.rs b/src/service/pool_question.rs index d918545..2ab01ae 100644 --- a/src/service/pool_question.rs +++ b/src/service/pool_question.rs @@ -20,16 +20,18 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result Result, AppError> { - pool_question::list_all(db).await -} - -/// The pool as a non-staff user sees it, newest first: every approved -/// question, plus the caller's own pending ones. -pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { - pool_question::list_visible_to(db, user).await +/// One page of the caller's question list — visibility gate and optional +/// status filter in one SQL `WHERE`, so `total` counts the filtered set. +/// `viewer = None` is the teacher+ view (everything); `Some(me)` the pool +/// plus the caller's own pending questions. +pub async fn list( + db: &Database, + viewer: Option<&UserId>, + status: Option<&str>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + pool_question::list(db, viewer, status, limit, offset).await } /// Approve a pending question, stamping `approver`. A `None` from the diff --git a/src/service/user.rs b/src/service/user.rs index 8c0f2e5..f01bdaf 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -131,13 +131,16 @@ pub async fn read(db: &Database, id: &UserId) -> Result, AppError> user::read(db, id).await } -/// Every account, newest first — the web layer's paging read. +/// Every account, newest first — or only the roles `roles` names, when the +/// set is `Some` (the admin directory's tabs). The narrowing is the query's +/// `WHERE`, so `total` counts the filtered set and paging stays inside it. pub async fn list_all( db: &Database, + roles: Option<&[Role]>, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - user::list_all(db, limit, offset).await + user::list_all(db, roles, limit, offset).await } /// The users behind `ids` in one query; missing ids simply absent. diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 289fbf4..8e1e35d 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -5,12 +5,14 @@ use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason}; +use crate::domain::appointment::{ + Appointment, AppointmentId, AppointmentReason, AppointmentStatus, +}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -379,6 +381,72 @@ async fn publish_slots( Ok((StatusCode::CREATED, Json(items))) } +/// One teacher's window filter, shared by both doors: `me` is the caller, +/// blank is refused, and a well-formed-but-unknown id stands — it names no +/// row, so the filtered page is simply empty — while a malformed one is a +/// 400. Never [`UserId::from_key`] into a nil id: that would read as an +/// empty 200 instead of the caller's error. +fn teacher_filter(raw: Option<&str>, caller: &UserId) -> Result, AppError> { + let Some(raw) = raw else { + return Ok(None); + }; + let key = raw.trim(); + if key.is_empty() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher", + reason: "must not be empty", + })); + } + Ok(Some(match key { + "me" => *caller, + other => { + let id = UserId::from_key(other); + if id.uuid().is_nil() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher", + reason: "must be a hyphenated uuid", + })); + } + id + } + })) +} + +/// A `?starts_after=`/`?starts_before=` instant: unix milliseconds, negative +/// refused, absent left absent. +fn starts_bound_filter(field: &'static str, raw: Option) -> Result, AppError> { + match raw { + None => Ok(None), + Some(value) if value < 0 => Err(AppError::Validation(ValidationError::Invalid { + field, + reason: "must not be negative", + })), + Some(value) => Ok(Some(Timestamp::from_millis(value))), + } +} + +/// Optional list filters on the slots door. Absent, the response is the +/// unfiltered calendar exactly as it has always been. +#[derive(Debug, Deserialize, IntoParams)] +struct SlotFilter { + /// Narrow to one teacher's slots: `me` for the caller, else a user id. + #[param(example = "me")] + teacher: Option, + /// Keep only slots starting at or after this unix-millisecond instant. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + starts_after: Option, +} + +impl SlotFilter { + fn resolve_teacher(&self, caller: &UserId) -> Result, AppError> { + teacher_filter(self.teacher.as_deref(), caller) + } + + fn resolve_starts_after(&self) -> Result, AppError> { + starts_bound_filter("starts_after", self.starts_after) + } +} + /// List slots, earliest first. Teacher+ see their own calendar, past occurrences /// included; everyone else sees every slot that has not started yet — the /// bookable calendar, bounded exactly as booking is, so a slot already underway @@ -390,6 +458,17 @@ async fn publish_slots( /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope. /// +/// Optional filters narrow the answer without ever widening it. `?teacher=` +/// names one teacher — `me` for the caller, else a user id — and +/// `?starts_after=` (unix milliseconds, inclusive) keeps the windows that +/// start at or after the instant, in the SQL so the past is never loaded to +/// be thrown away. A teacher+ caller's universe is their own calendar, so +/// `teacher=me` reads the same as absent and naming another teacher is the +/// empty intersection: a colleague's slots, past ones included, stay +/// private. For everyone else the universe is the bookable calendar, so a +/// named teacher's upcoming slots are exactly what the absent call already +/// offered. +/// /// Each slot carries its teacher's `PersonRef` (id, username, name) to *every* /// authenticated caller, parents included — deliberate, and not to be /// "tightened". A parent's three direct routes to that identity all refuse @@ -406,10 +485,10 @@ async fn publish_slots( path = "/slots", tag = "appointments", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, SlotFilter), responses( (status = 200, description = "A page of slots (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -417,15 +496,39 @@ async fn list_slots( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, + Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; + let narrow_to = filter.resolve_teacher(user.get_id())?; + let starts_after = filter.resolve_starts_after()?; let (slots, people) = if user.get_role().at_least(Role::Teacher) { - ( - service::appointment_slot::list_for_teacher(&st.db, user.get_id()).await?, - PersonRef::map_of(&[&user]), - ) + // The calendar arm's universe is the caller's own published rows, + // past occurrences included. The `teacher` filter narrows inside it: + // `me` is the caller's own calendar (the same rows as absent), and + // naming anyone else is the empty intersection — which it must be, + // or the param would hand over a colleague's calendar. + match narrow_to { + Some(other) if other != *user.get_id() => { + (Vec::new(), PersonRef::map_of(&[&user])) + } + _ => ( + service::appointment_slot::list_calendar( + &st.db, + user.get_id(), + starts_after, + ) + .await?, + PersonRef::map_of(&[&user]), + ), + } } else { - let mut slots = service::appointment_slot::list_upcoming(&st.db, Timestamp::now()).await?; + let mut slots = service::appointment_slot::list_upcoming( + &st.db, + Timestamp::now(), + narrow_to.as_ref(), + starts_after, + ) + .await?; // The teachers' live rows, not the slots' word for it: a demotion // leaves the calendar behind, and an inert slot must not be offered. // Keying the person map off that same read makes the filter free. @@ -587,20 +690,98 @@ async fn book( )) } +/// Optional list filters on the bookings door. Absent, the response is the +/// caller's listing exactly as it has always been. +#[derive(Debug, Deserialize, IntoParams)] +struct AppointmentFilter { + /// Narrow to one booking state: `pending`, `approved`, `rejected` or + /// `cancelled`. + #[param(example = "pending")] + status: Option, + /// Keep only meetings starting at or after this unix-millisecond instant. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + starts_after: Option, + /// Keep only meetings starting before this unix-millisecond instant — + /// exclusive, so `[starts_after, starts_before)` is a closed-open month. + #[param(minimum = 0, example = 1_760_259_199_999_i64)] + starts_before: Option, + /// Narrow to bookings on one teacher's slots: `me` for the caller, else + /// a user id. + #[param(example = "me")] + teacher: Option, +} + +impl AppointmentFilter { + /// The wire word against the closed vocabulary the rows store + /// ([`AppointmentStatus::as_str`]): an unknown or blank word is a 400 + /// naming the field, never a silent whole-list read. + fn resolve_status(&self) -> Result, AppError> { + const STATUSES: [AppointmentStatus; 4] = [ + AppointmentStatus::Pending, + AppointmentStatus::Approved, + AppointmentStatus::Rejected, + AppointmentStatus::Cancelled, + ]; + let Some(raw) = self.status.as_deref() else { + return Ok(None); + }; + let word = raw.trim(); + if word.is_empty() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "status", + reason: "must not be empty", + })); + } + STATUSES + .into_iter() + .find(|status| status.as_str() == word) + .map(Some) + .ok_or_else(|| { + AppError::Validation(ValidationError::Invalid { + field: "status", + reason: "must be one of: pending, approved, rejected, cancelled", + }) + }) + } + + fn resolve_starts_after(&self) -> Result, AppError> { + starts_bound_filter("starts_after", self.starts_after) + } + + fn resolve_starts_before(&self) -> Result, AppError> { + starts_bound_filter("starts_before", self.starts_before) + } + + fn resolve_teacher(&self, caller: &UserId) -> Result, AppError> { + teacher_filter(self.teacher.as_deref(), caller) + } +} + /// List bookings, newest first. Students and parents see the ones they /// requested; teacher+ see the ones aimed at their own slots — their request /// inbox. Managers and admins read their own inbox too (they may still decide /// any booking by id). Paged via `?limit=&offset=` (omit `limit` for every /// booking); returns a `{items, total, limit, offset}` envelope. +/// +/// Optional filters narrow the answer without ever widening it. `?status=` +/// is one of `pending`, `approved`, `rejected`, `cancelled`; `?starts_after=` +/// and `?starts_before=` (unix milliseconds) keep the meetings whose start +/// sits in `[after, before)` — a standing proposal's time when one stands, +/// the slot's window otherwise, so a booking whose slot is gone (no window +/// at all) is left out; `?teacher=` names the booked slot's teacher, `me` or +/// a user id, joined through the slot. A teacher+ caller's universe is their +/// own inbox, so `teacher=me` reads the same as absent and naming another +/// teacher is the empty intersection rather than a read of that teacher's +/// inbox. #[utoipa::path( get, path = "/", tag = "appointments", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, AppointmentFilter), responses( (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -608,12 +789,44 @@ async fn list_appointments( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, + Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; + let status = filter.resolve_status()?; + let starts_after = filter.resolve_starts_after()?; + let starts_before = filter.resolve_starts_before()?; + let narrow_to = filter.resolve_teacher(user.get_id())?; let (rows, total) = if user.get_role().at_least(Role::Teacher) { - service::appointment::list_for_teacher(&st.db, user.get_id(), limit, offset).await? + // The inbox arm's universe is the caller's own bookings; the + // `teacher` filter narrows inside it, so naming another teacher is + // the empty intersection — see the slots door, same rule. + match narrow_to { + Some(other) if other != *user.get_id() => (Vec::new(), 0), + _ => { + service::appointment::list_for_teacher( + &st.db, + user.get_id(), + status, + starts_after, + starts_before, + limit, + offset, + ) + .await? + } + } } else { - service::appointment::list_for_requester(&st.db, user.get_id(), limit, offset).await? + service::appointment::list_for_requester( + &st.db, + user.get_id(), + status, + starts_after, + starts_before, + narrow_to.as_ref(), + limit, + offset, + ) + .await? }; // Join slots and people onto the page alone — the lookup shrinks with it. let items = appointment_responses(&rows, &st.db).await?; @@ -951,4 +1164,405 @@ mod tests { let boss = user("mudur", Role::Manager, &db).await; assert!(can_manage(&slot, &boss)); } + + // ---- the list filters --------------------------------------------------- + + /// The handlers under test touch `db` alone, but [`AppState`] wants all + /// of its pieces — built here off the sandboxed per-test database. + async fn a_state(db: &Database) -> AppState { + AppState { + db: db.clone(), + tenants: crate::database::init_test_tenants().await, + files_path: std::env::temp_dir(), + cookie_secure: false, + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + rag_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + ai: None, + metrics: crate::telemetry::Metrics::noop(), + } + } + + /// One published slot at an absolute instant. + async fn a_slot(db: &Database, teacher: &UserId, starts_at: i64, ends_at: i64) { + service::appointment_slot::create( + db, + teacher, + Timestamp::from_millis(starts_at), + Timestamp::from_millis(ends_at), + None, + ) + .await + .unwrap(); + } + + /// The slots door, unpaged. + async fn slots(st: &AppState, who: &User, filter: SlotFilter) -> Page { + list_slots( + State(st.clone()), + CurrentUser(who.clone()), + Query(PageParams { + limit: None, + offset: None, + }), + Query(filter), + ) + .await + .unwrap() + .0 + } + + /// The bookings door, unpaged. + async fn bookings( + st: &AppState, + who: &User, + filter: AppointmentFilter, + ) -> Page { + list_appointments( + State(st.clone()), + CurrentUser(who.clone()), + Query(PageParams { + limit: None, + offset: None, + }), + Query(filter), + ) + .await + .unwrap() + .0 + } + + /// Blank, malformed, and negative filter words are 400s naming the + /// field; `me` is the caller; a well-formed stranger stands (and names + /// an empty page — pinned by the handler-level tests). + #[test] + fn filter_words_refuse_blank_malformed_and_negative() { + let caller = UserId::generate(); + + for word in ["", " ", "not-a-uuid"] { + let filter = SlotFilter { + teacher: Some(word.into()), + starts_after: None, + }; + assert!( + matches!( + filter.resolve_teacher(&caller), + Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "teacher" + ), + "`{word}` must refuse as `teacher`" + ); + } + assert_eq!( + SlotFilter { + teacher: Some("me".into()), + starts_after: None, + } + .resolve_teacher(&caller) + .unwrap(), + Some(caller) + ); + let stranger = UserId::generate(); + assert_eq!( + SlotFilter { + teacher: Some(stranger.key()), + starts_after: None, + } + .resolve_teacher(&caller) + .unwrap(), + Some(stranger) + ); + + let filter = SlotFilter { + teacher: None, + starts_after: Some(-1), + }; + assert!(matches!( + filter.resolve_starts_after(), + Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_after" + )); + assert_eq!( + SlotFilter { + teacher: None, + starts_after: Some(0), + } + .resolve_starts_after() + .unwrap() + .map(|instant| instant.as_millis()), + Some(0) + ); + + let filter = AppointmentFilter { + status: None, + starts_after: None, + starts_before: Some(-5), + teacher: None, + }; + assert!(matches!( + filter.resolve_starts_before(), + Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_before" + )); + + // The closed status vocabulary: exact wire words only — no case + // play, no blank, no synonym — mirroring what the rows store. + let status = |word: Option<&str>| AppointmentFilter { + status: word.map(str::to_string), + starts_after: None, + starts_before: None, + teacher: None, + }; + assert_eq!(status(None).resolve_status().unwrap(), None); + assert_eq!( + status(Some(" pending ")).resolve_status().unwrap(), + Some(AppointmentStatus::Pending) + ); + assert_eq!( + status(Some("cancelled")).resolve_status().unwrap(), + Some(AppointmentStatus::Cancelled) + ); + for word in ["", " ", "APPROVED", "live", "confirmed"] { + assert!( + matches!( + status(Some(word)).resolve_status(), + Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "status" + ), + "`{word}` must refuse as `status`" + ); + } + } + + /// The slots door: absent filters are today's response per role — + /// teacher+ read their own calendar with the past included, everyone + /// else reads the bookable calendar — `teacher=me` is the caller's own + /// set, a named other teacher narrows the bookable calendar but never + /// opens a colleague's calendar, and `starts_after` cuts with `total` + /// reporting the filtered count. + #[tokio::test] + async fn slot_filters_narrow_without_widening() { + let (db, _leases) = init_test_db().await; + let st = a_state(&db).await; + let now = Timestamp::now().as_millis(); + let ali = user("ali-ogretmen", Role::Teacher, &db).await; + let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; + let veli = user("veli-veli", Role::Student, &db).await; + + a_slot(&db, ali.get_id(), now - 10_000, now - 5_000).await; // ali's past + a_slot(&db, ali.get_id(), now + 5_000, now + 10_000).await; + a_slot(&db, ali.get_id(), now + 60_000, now + 90_000).await; + a_slot(&db, ayse.get_id(), now + 30_000, now + 40_000).await; + + let none = || SlotFilter { + teacher: None, + starts_after: None, + }; + let me = || SlotFilter { + teacher: Some("me".into()), + starts_after: None, + }; + let of = |who: &UserId| SlotFilter { + teacher: Some(who.key()), + starts_after: None, + }; + + // Student, no filters: the bookable calendar — ali's past stays out, + // earliest first, exactly as the absent call has always answered. + let page = slots(&st, &veli, none()).await; + assert_eq!(page.total, 3); + let starts: Vec = page.items.iter().map(|slot| slot.starts_at).collect(); + let mut sorted = starts.clone(); + sorted.sort_unstable(); + assert_eq!(starts, sorted); + + // Student, teacher=me: they publish nothing — an empty page, not an + // error. + let page = slots(&st, &veli, me()).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + + // Student, teacher=ali: exactly ali's upcoming pair — a narrowing of + // the calendar they may already see, his past slot still private. + let page = slots(&st, &veli, of(ali.get_id())).await; + assert_eq!(page.total, 2); + assert!( + page.items + .iter() + .all(|slot| slot.teacher.id == ali.get_id().key() && slot.starts_at > now) + ); + + // Student, teacher=: an empty page, not a 404. + let page = slots(&st, &veli, of(&UserId::generate())).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + + // Teacher, no filters: their own calendar, past occurrences + // included — today's arm. + let page = slots(&st, &ali, none()).await; + assert_eq!(page.total, 3); + + // Teacher, teacher=me: the same calendar as absent. + let page = slots(&st, &ali, me()).await; + assert_eq!(page.total, 3); + + // Teacher, teacher=ayse: the empty intersection. Naming a colleague + // must not hand over their calendar, past rows included. + let page = slots(&st, &ali, of(ayse.get_id())).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + + // Teacher, starts_after=now: the past occurrence is cut in the SQL, + // and total is the filtered count. + let page = slots( + &st, + &ali, + SlotFilter { + teacher: None, + starts_after: Some(now), + }, + ) + .await; + assert_eq!(page.total, 2); + assert!(page.items.iter().all(|slot| slot.starts_at >= now)); + + // Both filters together, on the student arm. + let page = slots( + &st, + &veli, + SlotFilter { + teacher: Some(ayse.get_id().key()), + starts_after: Some(now), + }, + ) + .await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].starts_at, now + 30_000); + } + + /// The bookings door: `status` and `starts_after` (the meeting's + /// effective start) narrow each side's own listing, `teacher` joins + /// through the slot, and a teacher+ caller naming another teacher gets + /// the empty intersection — never that teacher's inbox. + #[tokio::test] + async fn booking_filters_narrow_without_widening() { + let (db, _leases) = init_test_db().await; + let st = a_state(&db).await; + let now = Timestamp::now().as_millis(); + let ali = user("ali-ogretmen", Role::Teacher, &db).await; + let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; + let veli = user("veli-veli", Role::Student, &db).await; + let reason = AppointmentReason::try_new("görüşme").unwrap(); + + let ali_slot = service::appointment_slot::create( + &db, + ali.get_id(), + Timestamp::from_millis(now + 60_000), + Timestamp::from_millis(now + 120_000), + None, + ) + .await + .unwrap(); + let ayse_slot = service::appointment_slot::create( + &db, + ayse.get_id(), + Timestamp::from_millis(now + 200_000), + Timestamp::from_millis(now + 260_000), + None, + ) + .await + .unwrap(); + let pending = + service::appointment::book(&db, ali_slot.get_id(), veli.get_id(), reason.clone()) + .await + .unwrap(); + let approved = + service::appointment::book(&db, ayse_slot.get_id(), veli.get_id(), reason.clone()) + .await + .unwrap(); + service::appointment::approve(&db, approved.get_id(), ayse.get_id()) + .await + .unwrap(); + + let none = || AppointmentFilter { + status: None, + starts_after: None, + starts_before: None, + teacher: None, + }; + let status = |word: &str| AppointmentFilter { + status: Some(word.into()), + starts_after: None, + starts_before: None, + teacher: None, + }; + let after = |millis: i64| AppointmentFilter { + status: None, + starts_after: Some(millis), + starts_before: None, + teacher: None, + }; + let with_teacher = |who: &User| AppointmentFilter { + status: None, + starts_after: None, + starts_before: None, + teacher: Some(who.get_id().key()), + }; + + // Student, no filters: both bookings — today's response. + let page = bookings(&st, &veli, none()).await; + assert_eq!(page.total, 2); + + // status: only the approved one; total is the filtered count. + let page = bookings(&st, &veli, status("approved")).await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].id, approved.get_id().key()); + assert_eq!(page.items[0].status, "approved"); + + // A state nothing carries: an empty page, not an error. + let page = bookings(&st, &veli, status("rejected")).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + + // teacher: joined through the slot — only the bookings on ali's. + let page = bookings(&st, &veli, with_teacher(&ali)).await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].id, pending.get_id().key()); + + // starts_after judges the meeting's effective start: the slot's + // window while no proposal stands. + let page = bookings(&st, &veli, after(now + 150_000)).await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].id, approved.get_id().key()); + + // starts_before through the door: the late meeting sits outside a + // window ending at now + 150_000, the early one inside it. + let page = bookings( + &st, + &veli, + AppointmentFilter { + status: None, + starts_after: None, + starts_before: Some(now + 150_000), + teacher: None, + }, + ) + .await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].id, pending.get_id().key()); + + // Teacher+ inbox: only the bookings aimed at their own slots. + let page = bookings(&st, &ali, none()).await; + assert_eq!(page.total, 1); + assert_eq!(page.items[0].id, pending.get_id().key()); + + // Inbox, teacher=me: the same rows. + let page = bookings(&st, &ali, with_teacher(&ali)).await; + assert_eq!(page.total, 1); + + // Inbox, teacher=ayse: the empty intersection — never her inbox. + let page = bookings(&st, &ali, with_teacher(&ayse)).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + + // Inbox, starts_after: ali's meeting is the earlier one, so a cut + // past it empties his inbox while ayse keeps hers. + let page = bookings(&st, &ali, after(now + 150_000)).await; + assert_eq!((page.items.len(), page.total), (0, 0)); + let page = bookings(&st, &ayse, after(now + 150_000)).await; + assert_eq!(page.total, 1); + } } diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 872d0c7..015f395 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -168,6 +168,44 @@ struct BankQuestionFilter { visibility: Option, } +impl BankQuestionFilter { + /// Validate + canonicalize: a malformed `subject`/`owner` key is a 400 + /// naming the field, never the nil id silently matching nothing — same + /// as [`super::offerings::OfferingFilter`]. `owner=me` is the caller. + fn resolve(&self, caller: &UserId) -> Result<(Option, Option), AppError> { + let subject = match self.subject.as_deref().map(str::trim) { + None => None, + Some(key) => { + let id = SubjectId::from_key(key); + if id.uuid().is_nil() { + return Err(ValidationError::Invalid { + field: "subject", + reason: "must be a hyphenated uuid", + } + .into()); + } + Some(id) + } + }; + let owner = match self.owner.as_deref().map(str::trim) { + None => None, + Some("me") => Some(*caller), + Some(key) => { + let id = UserId::from_key(key); + if id.uuid().is_nil() { + return Err(ValidationError::Invalid { + field: "owner", + reason: "must be a hyphenated uuid", + } + .into()); + } + Some(id) + } + }; + Ok((subject, owner)) + } +} + /// A bank template as its readers see it — `correct` included (teacher+ only, /// so the answer key is theirs to see). Its images, if any, are fetched /// through the image endpoints. @@ -482,6 +520,10 @@ async fn create_question( /// carries the resolved `subject_name`/`owner_name` so a client needn't look /// them up per row, plus `used_count` — how many exam questions were copied out /// of that template (one grouped query for the page, not one per row). +/// +/// A `subject`/`owner` key that is empty or not a hyphenated uuid is a 400 +/// naming the field; a well-formed id that names nothing is just an empty +/// page. #[utoipa::path( get, path = "/", @@ -490,7 +532,7 @@ async fn create_question( params(BankQuestionFilter, PageParams), responses( (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit, offset, or visibility", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, subject, owner, or visibility", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), ), @@ -502,11 +544,7 @@ async fn list_questions( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let subject = filter.subject.as_deref().map(SubjectId::from_key); - let owner = filter.owner.as_deref().map(|owner| match owner { - "me" => *user.get_id(), - id => UserId::from_key(id), - }); + let (subject, owner) = filter.resolve(user.get_id())?; // Same newtype the PATCH validates against, so an unknown shelf is the same // 400 ("visibility must be private or school") on both routes. let visibility = filter @@ -1018,4 +1056,77 @@ mod tests { assert!(!can_see(&question, &student)); assert!(can_see(&question, &admin)); } + + /// The field a filter's validation error names, or a panic. + fn invalid_field(result: Result<(Option, Option), AppError>) -> &'static str { + match result { + Err(AppError::Validation(ValidationError::Invalid { field, .. })) => field, + other => panic!("expected a field validation error, got {other:?}"), + } + } + + /// A malformed or empty `subject`/`owner` key is a 400 naming the field — + /// never the nil id silently matching nothing. `owner=me` is the caller, + /// and a well-formed key passes through unchanged. + #[tokio::test] + async fn subject_and_owner_keys_are_validated() { + let (db, _leases) = init_test_db().await; + let caller = user("ogretmen", Role::Teacher, &db).await; + + let filter = |subject: Option<&str>, owner: Option<&str>| BankQuestionFilter { + subject: subject.map(str::to_string), + owner: owner.map(str::to_string), + q: None, + visibility: None, + }; + + assert_eq!( + invalid_field(filter(Some("not-a-uuid"), None).resolve(caller.get_id())), + "subject" + ); + assert_eq!( + invalid_field(filter(Some(""), None).resolve(caller.get_id())), + "subject" + ); + assert_eq!( + invalid_field(filter(None, Some("not-a-uuid")).resolve(caller.get_id())), + "owner" + ); + assert_eq!( + invalid_field(filter(None, Some(" ")).resolve(caller.get_id())), + "owner" + ); + + // `me` resolves to the caller; a well-formed key passes through. + let (_, owner) = filter(None, Some("me")).resolve(caller.get_id()).unwrap(); + assert_eq!(owner, Some(*caller.get_id())); + let well_formed = "019732e3-7b00-7000-8000-00000000dead"; + let (subject, owner) = filter(Some(well_formed), Some(well_formed)) + .resolve(caller.get_id()) + .unwrap(); + assert_eq!(subject.map(|s| s.uuid()), Some(UserId::from_key(well_formed).uuid())); + assert_eq!(owner.map(|o| o.uuid()), Some(UserId::from_key(well_formed).uuid())); + } + + /// A well-formed id that names nothing is a 200 with an empty page and + /// `total` 0 — only a malformed key is a 400. + #[tokio::test] + async fn a_well_formed_but_unmatched_owner_is_an_empty_page() { + let (db, _leases) = init_test_db().await; + let stranger = UserId::from_key("019732e3-7b00-7000-8000-00000000dead"); + let (items, total) = bank_question::list( + &db, + None, + Some(&stranger), + None, + None, + None, + None, + 0, + ) + .await + .unwrap(); + assert!(items.is_empty()); + assert_eq!(total, 0); + } } diff --git a/src/web/boards.rs b/src/web/boards.rs index 636df9f..8837245 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -212,6 +212,11 @@ struct ListFilter { /// for both. A closed board is never deleted, so this is how a heavy /// creator trims a list of retired boards. open: Option, + /// Free-text search over the title: a case- and diacritic-insensitive + /// substring (`geometri` finds `Geometri`). Literal text — `%` and `_` + /// carry no special meaning. Blank means no search. + #[param(example = "geometri")] + q: Option, } /// Every board the caller may open — the ones they created and the ones they @@ -223,6 +228,10 @@ struct ListFilter { /// that has spent its lifetime stroke budget but was never drawn on again, are /// both still open — the closing stamp is only ever written by `/close` or by /// the append that the lifetime cap refuses. +/// +/// `?q=` narrows further by title: a case- and diacritic-insensitive +/// substring, composed with `open`; `total` counts the matches. Blank means +/// no search. #[utoipa::path( get, path = "/", @@ -243,8 +252,15 @@ async fn list_boards( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (boards, total) = - board::list_for_user(&st.db, user.get_id(), filter.open, limit, offset).await?; + let (boards, total) = board::list_for_user( + &st.db, + user.get_id(), + filter.open, + filter.q.as_deref(), + limit, + offset, + ) + .await?; let items = boards.iter().map(BoardResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index f9e331d..37b4111 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -27,7 +27,7 @@ use crate::domain::course_note_file::{ CourseNoteFile, CourseNoteFileId, FileContentType, FileName, }; use crate::domain::rag_output::{RagOutput, RagOutputId}; -use crate::error::{AppError, ErrorResponse}; +use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::module::Module; use crate::service; use crate::service::course::{can_manage_course, can_view_course}; @@ -160,9 +160,40 @@ struct CourseFilter { course: String, } +impl CourseFilter { + /// Validate: `course` is required, so an empty key is a 400 ("must not + /// be empty") and a non-uuid is a 400 naming the field — never the nil + /// id silently 404ing as a missing course. A well-formed id that names + /// no course stays a 404: the course read below must succeed for the + /// auth check. + fn resolve(&self) -> Result { + let key = self.course.trim(); + if key.is_empty() { + return Err(ValidationError::Invalid { + field: "course", + reason: "must not be empty", + } + .into()); + } + let id = CourseId::from_key(key); + if id.uuid().is_nil() { + return Err(ValidationError::Invalid { + field: "course", + reason: "must be a hyphenated uuid", + } + .into()); + } + Ok(id) + } +} + /// List a course's notes, newest first. Visible to whoever can view the /// course (its creator, a manager/admin, or anyone the course reaches). /// Paged via `?limit=&offset=`. +/// +/// `course` must be a hyphenated uuid: empty or malformed is a 400 naming +/// the field; a well-formed id that names no course stays a 404, since the +/// course must be read for the auth check. #[utoipa::path( get, path = "/", @@ -171,7 +202,7 @@ struct CourseFilter { params(CourseFilter, PageParams), responses( (status = 200, description = "A page of the course's notes (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or course key", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -183,7 +214,8 @@ async fn list( Query(filter): Query, Query(page): Query, ) -> Result>, AppError> { - let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course)) + let course_id = filter.resolve()?; + let course = crate::service::course::read(&st.db, &course_id) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -720,3 +752,54 @@ async fn reindex_rag( spawn_index(&st, &tenant, note); Ok(StatusCode::ACCEPTED.into_response()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `course` is required and must be a real key: empty is "must not be + /// empty", a non-uuid is "must be a hyphenated uuid" — never the nil id + /// silently 404ing as a missing course. A well-formed id passes through, + /// and one that names no course stays on the 404 path (the course read + /// the handler runs next must miss for the auth check). + #[tokio::test] + async fn course_key_is_validated_before_the_course_read() { + let (db, _leases) = crate::database::init_test_db().await; + let filter = |course: &str| CourseFilter { + course: course.to_string(), + }; + + match filter("").resolve() { + Err(AppError::Validation(ValidationError::Invalid { field, reason })) => { + assert_eq!(field, "course"); + assert_eq!(reason, "must not be empty"); + } + other => panic!("expected an empty-course error, got {other:?}"), + } + match filter(" ").resolve() { + Err(AppError::Validation(ValidationError::Invalid { field, reason })) => { + assert_eq!(field, "course"); + assert_eq!(reason, "must not be empty"); + } + other => panic!("expected a blank-course error, got {other:?}"), + } + match filter("not-a-uuid").resolve() { + Err(AppError::Validation(ValidationError::Invalid { field, reason })) => { + assert_eq!(field, "course"); + assert_eq!(reason, "must be a hyphenated uuid"); + } + other => panic!("expected a malformed-course error, got {other:?}"), + } + + // A well-formed id passes through; if it names no course, the read + // the handler does next misses and the route answers 404. + let id = filter("019732e3-7b00-7000-8000-00000000dead") + .resolve() + .unwrap(); + assert_eq!( + id.uuid(), + uuid::Uuid::parse_str("019732e3-7b00-7000-8000-00000000dead").unwrap() + ); + assert!(service::course::read(&db, &id).await.unwrap().is_none()); + } +} diff --git a/src/web/courses.rs b/src/web/courses.rs index 23d1fc1..db67018 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -3,7 +3,7 @@ use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -17,6 +17,7 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou use crate::domain::course_offering::CourseOfferingId; use crate::domain::role::Role; use crate::domain::subject::{SubjectDescription, SubjectName}; +use crate::domain::text_fold::search_fold; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; use crate::service; @@ -133,8 +134,24 @@ fn owns_course(course: &Course, user: &User) -> bool { /// homework. Below `teacher` a course is visible only the way it is to any /// other student: by enrollment. pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, AppError> { + visible_courses_filtered(user, db, None, None, None).await +} + +/// [`visible_courses`] narrowed by the `GET /courses` filters. The filters +/// ride *after* the visibility union and *before* any paging, so a filter can +/// only ever narrow what the caller already reaches and `total` is the +/// filtered length. For a manager the filters go into the catalog query +/// itself ([`crate::service::course::list_filtered`]); below manager the +/// union is Rust, so the same text fold filters the merged list in memory. +pub(crate) async fn visible_courses_filtered( + user: &User, + db: &Database, + kind: Option, + q: Option<&str>, + taught: Option, +) -> Result, AppError> { if user.get_role().at_least(Role::Manager) { - return service::course::list_all(db).await; + return service::course::list_filtered(db, kind, q, taught).await; } let mut courses = if user.get_role().at_least(Role::Teacher) { service::course::list_for_teacher(db, user.get_id()).await? @@ -154,6 +171,17 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result 0) == taught) + && needle.as_deref().is_none_or(|needle| { + search_fold(course.get_title().as_str()).contains(needle) + || search_fold(course.get_description().as_str()).contains(needle) + }) + }); Ok(courses) } @@ -391,29 +419,75 @@ async fn create_course( )) } +/// The `GET /courses` filters, both optional and combinable. They narrow the +/// caller's visible set — they never widen it: a student filtering by `kind` +/// still sees only the courses they reach. +#[derive(Debug, Deserialize, IntoParams)] +struct CourseListFilter { + /// Narrow to one kind: `course` (a regular class), `study` (a supervised + /// study session), or `club`. Omit for every kind. + #[param(example = "course")] + kind: Option, + /// Case- and diacritic-insensitive fragment of the title or description. + /// Omit — or leave blank — to filter nothing; `%` and `_` are literal. + #[param(example = "matematik")] + q: Option, + /// Keep only courses taught somewhere (`true`, `class_course_count > 0`) + /// or nowhere yet (`false`, `= 0`). Omit for both. + #[param(example = true)] + 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> { + let kind = match self.kind { + Some(kind) => Some(CourseKind::try_new(&kind)?), + None => None, + }; + Ok((kind, self.q, self.taught)) + } +} + /// List the catalog courses visible to the caller: every course for manager+, /// otherwise the courses they teach somewhere plus the ones they're enrolled /// in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a /// `{items, total, limit, offset}` envelope. +/// +/// `kind` narrows to one flavor, `q` filters by a case- and +/// diacritic-insensitive fragment of the title or description (blank = +/// unfiltered), and `taught` keeps only the courses a class section teaches +/// (`true`) or none yet (`false`). All apply to the caller's visible set +/// only — after the visibility gate and before the window is cut — so +/// `total` is the filtered length. #[utoipa::path( get, path = "/", tag = "courses", security(("session_cookie" = [])), - params(PageParams), + params(CourseListFilter, PageParams), responses( (status = 200, description = "A page of the caller's visible courses (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Unknown or empty kind, a `taught` that is not true/false, or invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_courses( State(st): State, CurrentUser(user): CurrentUser, + Query(filter): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let courses = visible_courses(&user, &st.db).await?; + let (kind, q, taught) = 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 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); @@ -883,6 +957,254 @@ mod tests { .unwrap() } + /// A catalog course with caller-chosen fields, minted through the real + /// create path. + async fn shaped_course( + creator: &User, + db: &Database, + title: &str, + description: &str, + kind: &str, + ) -> Course { + service::course::create( + db, + creator.get_id(), + CourseTitle::try_new(title).unwrap(), + CourseDescription::try_new(description).unwrap(), + CourseKind::try_new(kind).unwrap(), + ) + .await + .unwrap() + } + + fn titles(courses: &[Course]) -> Vec<&str> { + courses + .iter() + .map(|course| course.get_title().as_str()) + .collect() + } + + fn a_kind(kind: &str) -> CourseKind { + CourseKind::try_new(kind).unwrap() + } + + /// An unknown or empty `kind` is the write path's own 400, naming the + /// field; `q` passes through verbatim (each arm folds it). + #[tokio::test] + async fn the_kind_filter_parses_through_the_write_path() { + for kind in ["nope", ""] { + let err = CourseListFilter { + kind: Some(kind.to_string()), + q: None, + taught: None, + } + .resolve() + .unwrap_err(); + assert!( + matches!( + &err, + AppError::Validation(crate::error::ValidationError::Invalid { field, .. }) + if *field == "kind" + ), + "{kind:?}: {err:?}" + ); + } + let (kind, q, taught) = 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); + } + + /// Manager arm: kind and q narrow the catalog, total is the filtered + /// length, a miss is an empty list, and `%`/`_` are literal. + #[tokio::test] + async fn kind_and_q_narrow_the_manager_catalog() { + let (db, _leases) = init_test_db().await; + let boss = user("boss", Role::Manager, &db).await; + shaped_course(&boss, &db, "Matematik", "Cebir ve Geometri", "course").await; + shaped_course(&boss, &db, "Satranç Kulübü", "", "club").await; + shaped_course(&boss, &db, "Biyoloji Etüdü", "canlı yayın", "study").await; + // "Matematik" is taught by a real class section; the other two are + // attached nowhere, so the taught axis has both values in play. + let class = crate::db::class_group::create( + &db, + boss.get_id(), + crate::domain::class_group::ClassName::try_new("9-A").unwrap(), + crate::domain::grade::GradeLevel::new(9).unwrap(), + None, + None, + ) + .await + .unwrap(); + let matematik = visible_courses_filtered(&boss, &db, None, None, None) + .await + .unwrap() + .into_iter() + .find(|course| course.get_title().as_str() == "Matematik") + .unwrap(); + service::class_course::attach(&db, class.get_id(), matematik.get_id(), boss.get_id()) + .await + .unwrap(); + + // No filters: the whole catalog, newest first — today's response, + // taught and untaught alike. + let all = visible_courses_filtered(&boss, &db, None, None, None) + .await + .unwrap(); + assert_eq!( + titles(&all), + vec!["Biyoloji Etüdü", "Satranç Kulübü", "Matematik"] + ); + + // kind: exact flavor only. + let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, None) + .await + .unwrap(); + assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]); + + // q: title fragment, case- and diacritic-insensitive. + let q = visible_courses_filtered(&boss, &db, None, Some("SATRANÇ"), None) + .await + .unwrap(); + assert_eq!(titles(&q), vec!["Satranç Kulübü"]); + // q: description fragment too. + let q = visible_courses_filtered(&boss, &db, None, Some("canlı"), None) + .await + .unwrap(); + assert_eq!(titles(&q), vec!["Biyoloji Etüdü"]); + // q: `position`, not `LIKE` — no wildcard surprises. + for wildcard in ["%", "_"] { + let q = visible_courses_filtered(&boss, &db, None, Some(wildcard), None) + .await + .unwrap(); + assert!(q.is_empty(), "{wildcard:?} acted as a wildcard"); + } + + // Combined filters AND; a miss is 200 empty, not an error. + let miss = + visible_courses_filtered(&boss, &db, Some(a_kind("course")), Some("satranç"), None) + .await + .unwrap(); + assert!(miss.is_empty()); + let hit = visible_courses_filtered(&boss, &db, Some(a_kind("study")), Some("CANLI"), None) + .await + .unwrap(); + assert_eq!(titles(&hit), vec!["Biyoloji Etüdü"]); + + // Blank q is no filter — the unfiltered catalog again. + let blank = visible_courses_filtered(&boss, &db, None, Some(" "), None) + .await + .unwrap(); + assert_eq!(titles(&blank), titles(&all)); + + // taught: true keeps the attached one, false the unattached two, and + // it composes with kind. + let taught = visible_courses_filtered(&boss, &db, None, None, Some(true)) + .await + .unwrap(); + assert_eq!(titles(&taught), vec!["Matematik"]); + let untaught = visible_courses_filtered(&boss, &db, None, None, Some(false)) + .await + .unwrap(); + assert_eq!(titles(&untaught), vec!["Biyoloji Etüdü", "Satranç Kulübü"]); + let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(false)) + .await + .unwrap(); + assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]); + let miss = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(true)) + .await + .unwrap(); + assert!(miss.is_empty()); + + // The window is cut after the filter: one course per page while the + // total stays the filtered length (the handler's `total` is + // `courses.len()` taken *before* `paginate`). + let dersler = visible_courses_filtered(&boss, &db, Some(a_kind("course")), None, None) + .await + .unwrap(); + assert_eq!(dersler.len(), 1); + assert_eq!(paginate(&dersler, Some(1), 0).len(), 1); + } + + /// Below manager the filters ride the Rust union: they can narrow what a + /// student reaches but never widen it. + #[tokio::test] + async fn filters_narrow_but_never_widen_a_students_visible_set() { + let (db, _leases) = init_test_db().await; + let boss = user("boss2", Role::Manager, &db).await; + let student = user("ogrenci", Role::Student, &db).await; + let (instance, _ders) = crate::db::course::a_test_instance(&db).await; + shaped_course(&boss, &db, "Satranç Kulübü", "zeka oyunu", "club").await; + service::enrollment::enroll(&db, &instance, student.get_id(), boss.get_id()) + .await + .unwrap(); + + // Unfiltered: only the enrolled ders — the club is real but not theirs. + let mine = visible_courses_filtered(&student, &db, None, None, None) + .await + .unwrap(); + assert_eq!(titles(&mine), vec!["test course"]); + + // kind=club: the club exists in the catalog, the student still sees none. + let clubs = visible_courses_filtered(&student, &db, Some(a_kind("club")), None, None) + .await + .unwrap(); + assert!(clubs.is_empty()); + // q over the club's own title finds nothing they cannot reach either. + let q = visible_courses_filtered(&student, &db, None, Some("satranç"), None) + .await + .unwrap(); + assert!(q.is_empty()); + + // taught: their ders is taught (the attached instance), the club is + // not — the axis narrows both ways without widening anything. + let taught = visible_courses_filtered(&student, &db, None, None, Some(true)) + .await + .unwrap(); + assert_eq!(titles(&taught), vec!["test course"]); + let untaught = visible_courses_filtered(&student, &db, None, None, Some(false)) + .await + .unwrap(); + assert!(untaught.is_empty()); + + // Their own ders survives both filters. + let dersler = visible_courses_filtered(&student, &db, Some(a_kind("course")), None, None) + .await + .unwrap(); + assert_eq!(titles(&dersler), vec!["test course"]); + let q = visible_courses_filtered(&student, &db, None, Some("TEST"), None) + .await + .unwrap(); + assert_eq!(titles(&q), vec!["test course"]); + } + + /// `?taught=` present but empty is refused by the query extractor itself — + /// a 400 naming the field; only `true`/`false` parse. + #[test] + fn an_empty_taught_is_rejected_naming_the_field() { + let uri = axum::http::Uri::from_static("/courses?taught="); + let err = Query::::try_from_uri(&uri).unwrap_err(); + assert!(err.to_string().contains("taught"), "{err}"); + for ok in [ + "/courses?taught=true", + "/courses?taught=false", + "/courses?q=x", + "/courses", + ] { + let uri = axum::http::Uri::from_static(ok); + assert!( + Query::::try_from_uri(&uri).is_ok(), + "{ok:?} refused" + ); + } + } + /// The leak: `creator` is a historical column that demotion never sweeps, /// so the grant itself has to re-read the live role on every call. #[tokio::test] diff --git a/src/web/events.rs b/src/web/events.rs index 78c8cbb..d877f9d 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -24,24 +24,10 @@ use crate::service; use crate::state::AppState; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireTeacher, Scheduled, WindowParams, - check_not_past, check_time_range, paginate, person_map, set_or_clear, + CurrentUser, Page, PageParams, PersonRef, RequireTeacher, WindowParams, check_not_past, + check_time_range, paginate, person_map, set_or_clear, }; -impl Scheduled for Event { - fn starts_at_ms(&self) -> Option { - self.get_starts_at().map(|at| at.as_millis()) - } - - fn ends_at_ms(&self) -> Option { - self.get_ends_at().map(|at| at.as_millis()) - } - - fn order_key(&self) -> String { - self.get_id().key() - } -} - pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(create_event, list_events)) @@ -358,7 +344,10 @@ async fn create_event( /// milliseconds) narrows the list to upcoming/unfinished events and flips the /// order to ascending by schedule, so `?ends_after=&limit=20` returns the /// twenty *soonest* events rather than the twenty newest-created. Events with -/// no schedule are excluded by either parameter. +/// no schedule are excluded by either parameter. `?starts_before=` / +/// `?ends_before=` are the mirror bounds (strictly before); with any bound +/// set the page, the count, and the window share one SQL `WHERE`, so a +/// filtered page never decodes the events it skips. #[utoipa::path( get, path = "/", @@ -378,13 +367,20 @@ async fn list_events( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let events = window.apply(service::event::list_all(&st.db).await?)?; - let total = events.len() as i64; - // Paged in the web layer: `WindowParams` filters and re-orders in Rust. - let items = paginate(&events, limit, offset) - .iter() - .map(EventResponse::new) - .collect(); + window.validate()?; + // The window and the page are one SQL statement; `total` is a count over + // the same WHERE, so a filtered page never loads the rows it skips. + let (events, total) = service::event::list_windowed( + &st.db, + window.starts_after, + window.ends_after, + window.starts_before, + window.ends_before, + limit, + offset, + ) + .await?; + let items = events.iter().map(EventResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 8fee1fe..faf7422 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -36,7 +36,7 @@ use super::bank_questions::BankQuestionResponse; use super::instances::can_view_instance; use super::{ ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef, - RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate, + RequireTeacher, UploadFileForm, WindowParams, blob_path, check_not_past, paginate, person_map, read_image_upload, remove_blob, set_or_clear, store_blob, }; @@ -52,20 +52,6 @@ pub(crate) use images::*; pub(crate) use questions::*; pub(crate) use review::*; -impl Scheduled for Exam { - fn starts_at_ms(&self) -> Option { - self.get_starts_at().map(|at| at.as_millis()) - } - - fn ends_at_ms(&self) -> Option { - self.get_ends_at().map(|at| at.as_millis()) - } - - fn order_key(&self) -> String { - self.get_id().key() - } -} - pub fn routes() -> OpenApiRouter { OpenApiRouter::new() // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so @@ -245,6 +231,10 @@ struct ExamStatisticsResponse { /// schedule — so `?ends_after=&limit=20` returns the twenty *soonest* /// exams rather than the twenty newest-created. Exams without a window /// (no `mode`, or `open`) are excluded by either parameter. +/// `?starts_before=` / `?ends_before=` are the mirror bounds (strictly +/// before). Visibility, the draft rule, the window, the page, and the count +/// share one SQL `WHERE`, so a filtered page never decodes the exams it +/// skips. #[utoipa::path( get, path = "/", @@ -264,29 +254,47 @@ async fn list_exams( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let exams = if user.get_role().at_least(Role::Manager) { - service::exam::list_all(&st.db).await? + window.validate()?; + // 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? } else { let instances = visible_instances(&user, &st.db).await?; - let ids: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect(); + let visible: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect(); // Drafts show only where the caller manages the instance (as one of // its teachers — the manager+ path above already saw everything). - let managed: HashSet = instances + let managed: Vec<_> = instances .iter() .filter(|(_, manages)| *manages) - .map(|(instance, _)| instance.get_id().key()) + .map(|(instance, _)| instance.get_id().clone()) .collect(); - let mut exams = service::exam::list_for_class_course_courses(&st.db, &ids).await?; - exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_class_course().key())); - exams + 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? }; - let exams = window.apply(exams)?; - let total = exams.len() as i64; - // Paged in the web layer: the draft filter and the window are Rust. - let items = paginate(&exams, limit, offset) - .iter() - .map(ExamResponse::new) - .collect(); + let items = exams.iter().map(ExamResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/homework.rs b/src/web/homework.rs index 4f38038..43807f1 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -15,7 +15,7 @@ use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -138,21 +138,81 @@ async fn homework_with_instance( Ok((homework, instance)) } +/// The optional `?due_after=&due_before=&class_course=` scoping of the list. +/// `due_after` keeps homework due at or after an instant (the frontend's open +/// tab), `due_before` keeps what is due before one (the past tab) — the two +/// bounds share no instant and leave no gap — and `class_course` scopes the +/// list to one instance. Absent, each field filters nothing. +#[derive(Debug, Deserialize, IntoParams)] +struct HomeworkListFilter { + /// Keep homework due at or after this instant (Unix ms). + due_after: Option, + /// Keep homework due before this instant (Unix ms). + due_before: Option, + /// Keep only this class×course instance's homework (an instance id). + #[param(example = "019732e3-7b00-7000-8000-00000000face")] + class_course: Option, +} + +impl HomeworkListFilter { + /// Validate the raw query into the service-layer scope. A negative due + /// bound, an empty instance key, and a key that is not a hyphenated uuid + /// (the nil id included — [`ClassCourseId::from_key`] lands there) are + /// refused with the field named; a well-formed id that names no row + /// simply matches nothing. + fn resolve(self) -> Result { + let invalid = + |field: &'static str, reason: &'static str| AppError::Validation(ValidationError::Invalid { field, reason }); + let due_after = match self.due_after { + None => None, + Some(ms) if ms < 0 => return Err(invalid("due_after", "must not be negative")), + Some(ms) => Some(ms), + }; + let due_before = match self.due_before { + None => None, + Some(ms) if ms < 0 => return Err(invalid("due_before", "must not be negative")), + Some(ms) => Some(ms), + }; + let class_course = match self.class_course.as_deref().map(str::trim) { + None => None, + Some("") => return Err(invalid("class_course", "must not be empty")), + Some(key) => { + let instance = ClassCourseId::from_key(key); + if instance.uuid().is_nil() { + return Err(invalid("class_course", "must be a hyphenated uuid")); + } + Some(instance) + } + }; + Ok(service::homework::HomeworkListFilter { + due_after, + due_before, + class_course, + }) + } +} + /// List the homework across the caller's instances — their "my homework" view — /// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every /// instance's homework; a teacher sees the homework of instances they run; a /// student sees only the homework they are assigned (whole-roster ones plus any /// subset that names them, each with its `assigned` narrowed to themselves). /// Returns a `{items, total, limit, offset}` envelope. +/// +/// `due_after` and `due_before` (Unix ms) carry the frontend's open and past +/// tabs — due at or after an instant, due before one — and `class_course` +/// scopes the list to a single instance, all before anything leaves the +/// database. Omitted, the response is the caller's whole visible homework, +/// unchanged. #[utoipa::path( get, path = "/", tag = "homework", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, HomeworkListFilter), responses( (status = 200, description = "A page of the caller's visible homework (all of it when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -160,33 +220,40 @@ async fn list_homework( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, + Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; + let filter = filter.resolve()?; // The instances this caller manages — empty for a manager+, who manages all // of them, and who is told apart by this flag. let manages_all = user.get_role().at_least(Role::Manager); - let mut managed: Vec = Vec::new(); - let homework = if manages_all { - service::homework::list_all(&st.db).await? - } else { - let instances = visible_instances(&user, &st.db).await?; - let ids: Vec = instances - .iter() - .map(|(instance, _)| instance.get_id().clone()) - .collect(); - // A student sees only the homework they are assigned; a teacher who - // manages an instance sees all of its homework (the manager+ path above - // already saw everything). - managed = instances - .iter() - .filter(|(_, manages)| *manages) - .map(|(instance, _)| instance.get_id().clone()) - .collect(); - let mut homework = service::homework::list_for_class_courses(&st.db, &ids).await?; - homework - .retain(|hw| managed.contains(hw.get_class_course()) || hw.student_sees(user.get_id())); - homework - }; + if manages_all { + // The SQL WHERE is the whole filter on this path: a manager retains + // nothing in Rust, so the window and the count both run in the + // database and `total` comes back with the page. + let (homework, total) = + service::homework::list_all(&st.db, &filter, limit, offset).await?; + let items = homework.iter().map(HomeworkResponse::new).collect(); + return Ok(Json(Page::new(items, total, limit, offset))); + } + let instances = visible_instances(&user, &st.db).await?; + let ids: Vec = instances + .iter() + .map(|(instance, _)| instance.get_id().clone()) + .collect(); + // A student sees only the homework they are assigned; a teacher who + // manages an instance sees all of its homework (the manager+ path above + // already saw everything). + let managed: Vec = instances + .iter() + .filter(|(_, manages)| *manages) + .map(|(instance, _)| instance.get_id().clone()) + .collect(); + let mut homework = service::homework::list_for_class_courses(&st.db, &ids, &filter).await?; + // The audience retain stays after the SQL filter and before the window, + // so `total` is the post-retain length, never a page sliced before it. + homework + .retain(|hw| managed.contains(hw.get_class_course()) || hw.student_sees(user.get_id())); let total = homework.len() as i64; // Paged in the web layer: the audience filter above is per-row Rust. The // subset roster rides along only for the rows the caller manages — to a @@ -195,7 +262,7 @@ async fn list_homework( let items = paginate(&homework, limit, offset) .iter() .map(|hw| { - if manages_all || managed.contains(hw.get_class_course()) { + if managed.contains(hw.get_class_course()) { HomeworkResponse::new(hw) } else { HomeworkResponse::for_viewer(hw, user.get_id()) @@ -1277,3 +1344,408 @@ async fn homework_report( } Ok(Json(Page::new(items, total, limit, offset))) } + +#[cfg(test)] +mod tests { + use super::*; + use axum::Router; + use axum::body::Body; + use axum::http::{Request, StatusCode}; + use tower::ServiceExt; + + use crate::database::init_test_tenants; + use crate::db::session; + use crate::domain::homework::HomeworkTitle; + use crate::domain::role::Role; + use crate::domain::subject::{SubjectDescription, SubjectName}; + use crate::domain::user::Username; + use crate::tenant::{DEMO_SCHOOL_ID, SchoolId}; + + const DAY: i64 = 86_400_000; + + /// The app behind a live school cookie for `user`, plus the tenant + /// registry handle. The router is the real one, so the cookie, the + /// tenant resolution, and the published query params are all exercised. + async fn app_for(username: &str, role: Role) -> (Router, String, crate::database::Database) { + let tenants = init_test_tenants().await; + let school = tenants + .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap()) + .await + .expect("the demo school"); + let user = crate::service::user::create(&school, Username::try_new(username).unwrap(), None) + .await + .unwrap(); + let user = crate::service::user::set_role(&school, user.get_id(), role) + .await + .unwrap() + .0; + let token = session::create(&school, user.get_id()).await.unwrap(); + let cookie = format!("session={DEMO_SCHOOL_ID}.{}", token.token().as_str()); + let state = AppState { + db: tenants.control().clone(), + tenants, + files_path: std::env::temp_dir(), + cookie_secure: false, + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + rag_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + ai: None, + metrics: crate::telemetry::Metrics::noop(), + }; + (crate::build_router(state), cookie, school) + } + + /// One homework with a chosen due instant and audience on `instance`. + async fn seed_homework_on( + db: &crate::database::Database, + instance: &ClassCourseId, + course: &crate::domain::course::CourseId, + due_at: i64, + title: &str, + assigned: Option>, + ) -> Homework { + let subject = crate::db::subject::create( + db, + course, + SubjectName::try_new(title).unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + let teacher = crate::service::user::create(db, Username::try_new(title).unwrap(), None) + .await + .unwrap(); + crate::db::homework::create( + db, + instance, + subject.get_id(), + HomeworkTitle::try_new(title).unwrap(), + None, + Timestamp::from_millis(due_at), + assigned, + teacher.get_id(), + ) + .await + .unwrap() + } + + /// One homework with a chosen due instant and audience on a fresh + /// instance; returns the instance and the row. + async fn seed_homework( + db: &crate::database::Database, + due_at: i64, + title: &str, + assigned: Option>, + ) -> (ClassCourseId, Homework) { + let (instance, course) = crate::db::course::a_test_instance(db).await; + let homework = + seed_homework_on(db, &instance, &course, due_at, title, assigned).await; + (instance, homework) + } + + /// A student put on the live roster of the class `instance` belongs to — + /// the membership `visible_instances` reads for a student. + async fn join_class( + db: &crate::database::Database, + instance: &ClassCourseId, + student: &UserId, + ) { + let instance = crate::service::class_course::read(db, instance) + .await + .unwrap() + .unwrap(); + sqlx::query( + "INSERT INTO class_member (id, class, app_user, added_by, joined_at) \ + VALUES ($1, $2, $3, $3, 0)", + ) + .bind(crate::domain::class_group::ClassGroupId::generate().uuid()) + .bind(instance.get_class().uuid()) + .bind(student.uuid()) + .execute(db) + .await + .unwrap(); + } + + async fn get(app: &Router, uri: &str, cookie: &str) -> (StatusCode, serde_json::Value) { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(uri) + .header("cookie", cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let body = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .unwrap(); + let json = if body.is_empty() { + serde_json::Value::Null + } else { + serde_json::from_slice(&body).unwrap() + }; + (status, json) + } + + /// The manager path: the due window and the instance scope narrow in SQL, + /// the page window applies after the filter, and `total` stays the + /// filtered length. Absent params are exactly the old response. + #[tokio::test] + async fn manager_filters_open_past_and_instance_in_sql() { + let now = Timestamp::now().as_millis(); + let (app, cookie, school) = app_for("mudur-filter", Role::Manager).await; + let (_, past) = seed_homework(&school, now - DAY, "past-here", None).await; + let (_, open) = seed_homework(&school, now + DAY, "open-here", None).await; + let (there, open_there) = seed_homework(&school, now + 2 * DAY, "open-there", None).await; + + // Absent params: every row, newest first — the old response. + let (status, body) = get(&app, "/homework", &cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 3); + let ids: Vec = body["items"] + .as_array() + .unwrap() + .iter() + .map(|row| row["id"].as_str().unwrap().to_string()) + .collect(); + assert_eq!( + ids, + vec![ + open_there.get_id().key(), + open.get_id().key(), + past.get_id().key() + ] + ); + + // The open tab: due at or after the bound. + let (status, body) = get(&app, &format!("/homework?due_after={now}"), &cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 2); + assert!( + body["items"] + .as_array() + .unwrap() + .iter() + .all(|row| row["due_at"].as_i64().unwrap() >= now) + ); + + // The past tab: due strictly before the bound — no overlap, no gap. + let (status, body) = get(&app, &format!("/homework?due_before={now}"), &cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 1); + assert_eq!(body["items"][0]["id"], past.get_id().key().to_string()); + + // The instance scope: only `there`'s rows. + let (status, body) = get( + &app, + &format!("/homework?class_course={}", there.key()), + &cookie, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 1); + assert_eq!(body["items"][0]["id"], open_there.get_id().key().to_string()); + + // A well-formed id that names no row: an empty page, not a 404. + let stranger = ClassCourseId::generate(); + let (status, body) = get( + &app, + &format!("/homework?class_course={}", stranger.key()), + &cookie, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 0); + assert!(body["items"].as_array().unwrap().is_empty()); + + // The window applies after the filter; total is the filtered count. + let (status, body) = + get(&app, &format!("/homework?due_after={now}&limit=1"), &cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 2); + assert_eq!(body["items"].as_array().unwrap().len(), 1); + let (status, body) = + get(&app, &format!("/homework?due_after={now}&offset=1"), &cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 2); + assert_eq!(body["items"][0]["id"], open.get_id().key().to_string()); + } + + /// A bad filter is a 400 naming the field: negative due bounds, and an + /// instance key that is empty, not a uuid, or the nil uuid. + #[tokio::test] + async fn bad_filters_are_400_naming_the_field() { + let (app, cookie, _school) = app_for("mudur-hata", Role::Manager).await; + for (uri, field) in [ + ("/homework?due_after=-1", "due_after"), + ("/homework?due_before=-5", "due_before"), + ("/homework?class_course=", "class_course"), + ("/homework?class_course=%20", "class_course"), + ("/homework?class_course=not-a-uuid", "class_course"), + ( + "/homework?class_course=00000000-0000-0000-0000-000000000000", + "class_course", + ), + ] { + let (status, body) = get(&app, uri, &cookie).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{uri} must be a 400"); + assert!( + body["error"] + .as_str() + .unwrap_or_default() + .contains(field), + "{uri} must name {field}: {body}" + ); + } + } + + /// The audience wall survives the filter: a student still sees only the + /// homework they are assigned, a teacher still sees their instances' + /// homework, and the manager sees every instance — all narrowed by the + /// same params. + #[tokio::test] + async fn audience_walls_survive_the_filter() { + let now = Timestamp::now().as_millis(); + let (app, _, school) = app_for("ogretmen-seyirci", Role::Student).await; + // The same registry also holds the actors; mint them directly. + let ali = crate::service::user::create(&school, Username::try_new("ali-filter").unwrap(), None) + .await + .unwrap(); + let veli = crate::service::user::create(&school, Username::try_new("veli-filter").unwrap(), None) + .await + .unwrap(); + let teacher = crate::service::user::create( + &school, + Username::try_new("hocasi-filter").unwrap(), + None, + ) + .await + .unwrap(); + let teacher = crate::service::user::set_role(&school, teacher.get_id(), Role::Teacher) + .await + .unwrap() + .0; + let manager = crate::service::user::create( + &school, + Username::try_new("mudur-seyirci").unwrap(), + None, + ) + .await + .unwrap(); + let manager = crate::service::user::set_role(&school, manager.get_id(), Role::Manager) + .await + .unwrap() + .0; + + let (instance, course) = crate::db::course::a_test_instance(&school).await; + let whole_open = seed_homework_on(&school, &instance, &course, now + DAY, "acik-genel", None).await; + let subset_open = seed_homework_on( + &school, + &instance, + &course, + now + DAY, + "acik-secili", + Some(vec![*ali.get_id()]), + ) + .await; + let past = seed_homework_on(&school, &instance, &course, now - DAY, "gecmis-genel", None).await; + join_class(&school, &instance, ali.get_id()).await; + join_class(&school, &instance, veli.get_id()).await; + crate::db::class_course_teacher::assign(&school, &instance, teacher.get_id()) + .await + .unwrap(); + + let ali_cookie = format!( + "session={DEMO_SCHOOL_ID}.{}", + session::create(&school, ali.get_id()) + .await + .unwrap() + .token() + .as_str() + ); + let veli_cookie = format!( + "session={DEMO_SCHOOL_ID}.{}", + session::create(&school, veli.get_id()) + .await + .unwrap() + .token() + .as_str() + ); + let teacher_cookie = format!( + "session={DEMO_SCHOOL_ID}.{}", + session::create(&school, teacher.get_id()) + .await + .unwrap() + .token() + .as_str() + ); + let manager_cookie = format!( + "session={DEMO_SCHOOL_ID}.{}", + session::create(&school, manager.get_id()) + .await + .unwrap() + .token() + .as_str() + ); + + // Ali: open tab only, and the subset names him — narrowed to him. + let (status, body) = get(&app, &format!("/homework?due_after={now}"), &ali_cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 2); + let ids: Vec = body["items"] + .as_array() + .unwrap() + .iter() + .map(|row| row["id"].as_str().unwrap().to_string()) + .collect(); + assert_eq!( + ids, + vec![ + subset_open.get_id().key(), + whole_open.get_id().key() + ] + ); + let subset = body["items"] + .as_array() + .unwrap() + .iter() + .find(|row| row["id"] == subset_open.get_id().key()) + .unwrap(); + assert_eq!( + subset["assigned"], + serde_json::json!([ali.get_id().key().to_string()]), + "a student's subset roster is narrowed to themselves" + ); + + // Veli shares the class but not the subset: the open tab hides it. + let (status, body) = get(&app, &format!("/homework?due_after={now}"), &veli_cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 1); + assert_eq!(body["items"][0]["id"], whole_open.get_id().key().to_string()); + + // The teacher manages the instance: every open row of it, roster and + // all — the past row stays behind the filter, not the audience. + let (status, body) = + get(&app, &format!("/homework?due_after={now}"), &teacher_cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 2); + assert!(body["items"].as_array().unwrap().iter().any(|row| row["id"] + == subset_open.get_id().key() + && row["assigned"] + .as_array() + .unwrap() + .len() + == 1)); + + // The manager sees every instance's homework, narrowed by the params. + let (status, body) = get(&app, &format!("/homework?due_before={now}"), &manager_cookie).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["total"], 1); + assert_eq!(body["items"][0]["id"], past.get_id().key().to_string()); + } +} diff --git a/src/web/instances.rs b/src/web/instances.rs index acfadc3..43b4b4a 100644 --- a/src/web/instances.rs +++ b/src/web/instances.rs @@ -22,7 +22,7 @@ use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -1080,19 +1080,59 @@ async fn create_session_in_instance( )) } +/// The optional `?starts_after=&starts_before=` window on the session list: +/// half-open on `starts_at`, both bounds unix milliseconds. A negative value +/// is a `400` naming the field. +#[derive(Debug, Deserialize, IntoParams)] +struct SessionWindow { + /// Keep sessions starting at or after this unix-millisecond instant + /// (inclusive). + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + #[serde(default)] + starts_after: Option, + /// Keep sessions starting strictly before this unix-millisecond instant, + /// so `[month_start, next_month_start)` names a month exactly. + #[param(minimum = 0, example = 1_760_259_599_999_i64)] + #[serde(default)] + starts_before: Option, +} + +impl SessionWindow { + fn validate(&self) -> Result<(), AppError> { + for (field, value) in [ + ("starts_after", self.starts_after), + ("starts_before", self.starts_before), + ] { + if value.is_some_and(|value| value < 0) { + return Err(AppError::Validation(ValidationError::Invalid { + field, + reason: "must not be negative", + })); + } + } + Ok(()) + } +} + /// List one instance's lesson sessions, most recent first, paged via /// `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's /// enrolled students, its teachers, and managers/admins. Returns a /// `{items, total, limit, offset}` envelope. +/// +/// The optional `?starts_after=&starts_before=` window (unix milliseconds) +/// narrows the list to the half-open `[starts_after, starts_before)` on +/// `starts_at` — a calendar month is `[month_start, next_month_start)`. The +/// window rides the same SQL `WHERE` as the page and the count; the order is +/// unchanged. Absent, the response is the unfiltered list. #[utoipa::path( get, path = "/{id}/sessions", tag = "instances", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Instance id"), PageParams), + params(("id" = String, Path, description = "Instance id"), SessionWindow, PageParams), responses( (status = 200, description = "A page of the instance's sessions (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Instance not found", body = ErrorResponse), @@ -1102,9 +1142,11 @@ async fn list_instance_sessions( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, + Query(window): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; + window.validate()?; // The instance must exist — a missing one is a 404, not an empty list. let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; if !can_view_instance(&st.db, instance.get_id(), &user).await? { @@ -1112,9 +1154,15 @@ async fn list_instance_sessions( "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its sessions", )); } - let (rows, total) = - service::course_session::list_for_class_course(&st.db, instance.get_id(), limit, offset) - .await?; + let (rows, total) = service::course_session::list_windowed( + &st.db, + instance.get_id(), + window.starts_after, + window.starts_before, + limit, + offset, + ) + .await?; // Join teachers onto the page alone — the lookup shrinks with the window. let people = person_map(rows.iter().map(|s| *s.get_teacher()), &st.db).await?; let items = rows @@ -1129,6 +1177,44 @@ mod tests { use super::*; use crate::domain::class_group::ClassGroupId; + /// A negative window bound is a `400` naming the field, whichever bound + /// it is; both absent validates clean. + #[test] + fn a_negative_session_window_bound_is_refused_naming_the_field() { + let clean = SessionWindow { + starts_after: None, + starts_before: None, + }; + assert!(clean.validate().is_ok()); + + for (field, window) in [ + ( + "starts_after", + SessionWindow { + starts_after: Some(-1), + starts_before: None, + }, + ), + ( + "starts_before", + SessionWindow { + starts_after: None, + starts_before: Some(-1), + }, + ), + ] { + let AppError::Validation(ValidationError::Invalid { + field: named, + reason, + }) = window.validate().unwrap_err() + else { + panic!("expected a validation error for {field}"); + }; + assert_eq!(named, field); + assert_eq!(reason, "must not be negative"); + } + } + /// The read path behind `GET /instances/me` is `class_member` → the sections /// → their instances. A student enrolled by a section sees exactly that /// section's instances, and a second section teaching the same course is a diff --git a/src/web/meals.rs b/src/web/meals.rs index eb40db4..6865327 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -93,6 +93,40 @@ struct MenuRange { to: Option, } +/// Optional slot filter on `GET /meals/menus`. Its own extractor, so +/// `GET /meals/attendance/{user}` — which shares [`MenuRange`] for its date +/// bounds — gains no dead `slot` param. +#[derive(Debug, Deserialize, IntoParams)] +struct MenuSlotFilter { + /// Keep only menus published for this meal slot, named exactly as the + /// menu snapshotted it. + #[param(example = "lunch")] + slot: Option, +} + +impl MenuSlotFilter { + /// The slot text to bind, trimmed. Deliberately *not* checked against + /// the school's current `meal_slots`: a menu snapshots its slot's name + /// at publish, so a slot retired since must still find the menus + /// published under it — an unknown name simply matches nothing (an + /// empty page, not a `400`). An empty value, though, filters nothing + /// and says nothing: refused, naming the field. + fn resolve(self) -> Result, AppError> { + let Some(raw) = self.slot else { + return Ok(None); + }; + let slot = raw.trim(); + if slot.is_empty() { + return Err(ValidationError::Invalid { + field: "slot", + reason: "must name a meal slot and may not be empty", + } + .into()); + } + Ok(Some(slot.to_string())) + } +} + #[derive(Deserialize, ToSchema)] struct CreateDish { #[schema(example = "Mercimek çorbası", max_length = 100)] @@ -283,15 +317,22 @@ async fn create_menu( /// `YYYY-MM-DD`, each bound held to the same real-calendar-day rule a menu's /// own date is). Paged via `?limit=&offset=` (omit `limit` for the full list); /// returns a `{items, total, limit, offset}` envelope. +/// +/// Narrow to one meal slot with `?slot=` — matched exactly against the slot +/// text each menu snapshotted at publish, not against the school's current +/// `meal_slots`, so a slot retired since still finds its menus and an +/// unknown name is an empty page rather than an error. `?slot=` (empty) is a +/// `400`. The filter runs in SQL: `total` counts the filtered rows, and +/// `limit`/`offset` window inside them. #[utoipa::path( get, path = "/menus", tag = "meals", security(("session_cookie" = [])), - params(MenuRange, PageParams), + params(MenuRange, MenuSlotFilter, PageParams), responses( (status = 200, description = "A page of menus (the full list when unpaged)", body = Page), - (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, or a malformed limit or offset", body = ErrorResponse), + (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, an empty slot, or a malformed limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -299,13 +340,22 @@ async fn list_menus( State(st): State, CurrentUser(user): CurrentUser, Query(range): Query, + Query(filter): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; - let (menus, total) = - service::menu::list(&st.db, from.as_ref(), to.as_ref(), limit, offset).await?; + let slot = filter.resolve()?; + let (menus, total) = service::menu::list( + &st.db, + from.as_ref(), + to.as_ref(), + slot.as_deref(), + limit, + offset, + ) + .await?; // The dish/people join runs over the page alone, so it shrinks with it. let items = menu_responses(&menus, user.get_id(), &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) diff --git a/src/web/messages.rs b/src/web/messages.rs index 78e568c..e1efa02 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -62,6 +62,11 @@ struct ListFilter { /// `?folder=inbox&read=false&limit=1` makes `total` the unread badge), /// `true` = read only. Omit for both. read: Option, + /// Free-text search over each message's subject and body: a case- and + /// diacritic-insensitive substring (`etut` finds `Etüt`). Literal text — + /// `%` and `_` carry no special meaning. Blank means no search. + #[param(example = "etüt")] + q: Option, } /// A message as one party sees it. `folder` is the *caller's* copy's folder; @@ -222,6 +227,10 @@ async fn send_message( /// flag; `total` counts the filtered folder, so /// `?folder=inbox&read=false&limit=1` is a cheap unread badge. Paged via /// `?limit=&offset=`. +/// +/// `?q=` narrows further by free text: a case- and diacritic-insensitive +/// substring of each message's subject or body, composed with `folder` and +/// `read`; `total` counts the matches. Blank means no search. #[utoipa::path( get, path = "/", @@ -246,8 +255,16 @@ async fn list( None => Folder::Inbox, }; - let (messages, total) = - message::list_folder(&st.db, user.get_id(), folder, filter.read, limit, offset).await?; + let (messages, total) = message::list_folder( + &st.db, + user.get_id(), + folder, + filter.read, + filter.q.as_deref(), + limit, + offset, + ) + .await?; let people = load_people(&messages, &st.db).await?; let items = messages .iter() diff --git a/src/web/page.rs b/src/web/page.rs index f79d404..0098d08 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -64,33 +64,47 @@ pub trait Scheduled { fn order_key(&self) -> String; } -/// The optional `?starts_after=&ends_after=` schedule window on a list of -/// scheduled rows. Both are unix milliseconds and independent (AND-ed when -/// both are given). Omit both and the list is untouched — same order, same -/// total as an unfiltered call. +/// The optional `?starts_after=&ends_after=&starts_before=&ends_before=` +/// schedule window on a list of scheduled rows. All four are unix milliseconds +/// and independent (AND-ed when several are given). Omit all four and the list +/// is untouched — same order, same total as an unfiltered call. #[derive(Debug, Deserialize, IntoParams)] pub struct WindowParams { /// Keep only rows starting strictly after this unix-millisecond instant. /// Rows without a `starts_at` are dropped. #[param(minimum = 0, example = 1_760_000_000_000_i64)] + #[serde(default)] pub starts_after: Option, /// Keep only rows whose window has not finished by this unix-millisecond /// instant: `ends_at > value`, falling back to `starts_at > value` when /// `ends_at` is null. Rows with no schedule at all are dropped. #[param(minimum = 0, example = 1_760_000_000_000_i64)] + #[serde(default)] pub ends_after: Option, + /// Keep only rows starting strictly before this unix-millisecond instant. + /// Rows without a `starts_at` are dropped. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + #[serde(default)] + pub starts_before: Option, + /// Keep only rows whose window has already finished by this + /// unix-millisecond instant: `ends_at < value`, falling back to + /// `starts_at < value` when `ends_at` is null. Rows with no schedule at + /// all are dropped. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + #[serde(default)] + pub ends_before: Option, } impl WindowParams { - /// Apply the window to an already-visibility-filtered list. With neither - /// parameter the list is returned untouched; with either, schedule-less - /// rows are dropped and the survivors are sorted ascending by `starts_at` - /// (falling back to `ends_at`), ties broken by id. A negative value is a - /// `400` naming the field. - pub fn apply(&self, mut items: Vec) -> Result, AppError> { + /// The `400` half of the window: a negative bound is refused naming its + /// field. Endpoints that push the window into SQL call this before the + /// read; [`Self::apply`] calls it before filtering. + pub fn validate(&self) -> Result<(), AppError> { for (field, value) in [ ("starts_after", self.starts_after), ("ends_after", self.ends_after), + ("starts_before", self.starts_before), + ("ends_before", self.ends_before), ] { if value.is_some_and(|value| value < 0) { return Err(AppError::Validation(ValidationError::Invalid { @@ -99,16 +113,40 @@ impl WindowParams { })); } } - if self.starts_after.is_none() && self.ends_after.is_none() { + Ok(()) + } + + /// Apply the window to an already-visibility-filtered list. With no + /// parameter the list is returned untouched; with any, schedule-less + /// rows are dropped and the survivors are sorted ascending by `starts_at` + /// (falling back to `ends_at`), ties broken by id. A negative value is a + /// `400` naming the field. + pub fn apply(&self, mut items: Vec) -> Result, AppError> { + self.validate()?; + if self.starts_after.is_none() + && self.ends_after.is_none() + && self.starts_before.is_none() + && self.ends_before.is_none() + { return Ok(items); } items.retain(|item| { let starts = item.starts_at_ms(); let ends = item.ends_at_ms(); + // The `*_after` bounds drop a `None` on their own (`None > Some` + // is false), but `None < Some(_)` is *true* — `Option` orders + // `None` first — so the `*_before` bounds must refuse a missing + // end explicitly, the way SQL's `NULL < x` does. self.starts_after.is_none_or(|after| starts > Some(after)) + && self + .starts_before + .is_none_or(|before| starts.is_some_and(|start| start < before)) && self .ends_after .is_none_or(|after| ends.or(starts) > Some(after)) + && self + .ends_before + .is_none_or(|before| ends.or(starts).is_some_and(|end| end < before)) }); // Every survivor has at least one end, so the fallback never yields // `None` — but sort defensively rather than unwrapping. @@ -222,17 +260,24 @@ mod tests { .collect() } - fn window(starts_after: Option, ends_after: Option) -> WindowParams { + fn window( + starts_after: Option, + ends_after: Option, + starts_before: Option, + ends_before: Option, + ) -> WindowParams { WindowParams { starts_after, ends_after, + starts_before, + ends_before, } } #[test] fn window_absent_leaves_the_list_untouched() { assert_eq!( - keys(window(None, None)), + keys(window(None, None, None, None)), ["none", "running", "later", "ending", "tie"] ); } @@ -243,26 +288,60 @@ mod tests { // starts_at fallback), `none` has neither and always drops. Ascending // by starts_at ?? ends_at, ties broken by key. assert_eq!( - keys(window(None, Some(15))), + keys(window(None, Some(15), None, None)), ["running", "ending", "later", "tie"] ); // At 25, `ending` (ends 20) is over; `running` (ends 40) is not. - assert_eq!(keys(window(None, Some(25))), ["running", "later", "tie"]); + assert_eq!( + keys(window(None, Some(25), None, None)), + ["running", "later", "tie"] + ); } #[test] fn starts_after_excludes_started_and_start_less_rows() { - assert_eq!(keys(window(Some(25), None)), ["later", "tie"]); + assert_eq!(keys(window(Some(25), None, None, None)), ["later", "tie"]); // AND-ed with ends_after: `tie` ends at 50, while `later` has no end // and its starts_at fallback (30) is already behind 45. - assert_eq!(keys(window(Some(25), Some(45))), ["tie"]); - assert!(keys(window(Some(60), None)).is_empty()); + assert_eq!( + keys(window(Some(25), Some(45), None, None)), + ["tie"] + ); + assert!(keys(window(Some(60), None, None, None)).is_empty()); + } + + #[test] + fn starts_before_excludes_not_yet_started_and_start_less_rows() { + // Strictly before: a row starting exactly at the instant is out. + assert_eq!(keys(window(None, None, Some(30), None)), ["running"]); + // AND-ed with ends_after: `running` (ends 40) survives 35; `tie` + // starts exactly at 30 and a `starts_before` is strict. + assert_eq!(keys(window(None, Some(35), Some(30), None)), ["running"]); + } + + #[test] + fn ends_before_keeps_only_finished_rows_dropping_the_unscheduled() { + // At 45: `ending` (ends 20) is over, `later` on its starts_at + // fallback (30) is over, `running` (ends 40) is over; `tie` (ends 50) + // is not; `none` has no schedule and always drops. + assert_eq!(keys(window(None, None, None, Some(45))), ["running", "ending", "later"]); + // Exactly at the end is not before it. + assert_eq!(keys(window(None, None, None, Some(40))), ["ending", "later"]); } #[test] fn window_rejects_negative_values() { - assert!(window(Some(-1), None).apply(rows()).is_err()); - assert!(window(None, Some(-1)).apply(rows()).is_err()); + assert!(window(Some(-1), None, None, None).apply(rows()).is_err()); + assert!(window(None, Some(-1), None, None).apply(rows()).is_err()); + assert!(window(None, None, Some(-1), None).apply(rows()).is_err()); + assert!(window(None, None, None, Some(-1)).apply(rows()).is_err()); + // The shared validate reports the field it refuses. + let Err(AppError::Validation(ValidationError::Invalid { field, .. })) = + window(None, None, Some(-1), None).apply(rows()) + else { + panic!("expected a validation error"); + }; + assert_eq!(field, "starts_before"); } #[test] diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index be46112..47866ab 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -3,7 +3,7 @@ use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -11,13 +11,13 @@ use crate::constant::MAX_POMODORO_LABEL_LEN; use crate::domain::pomodoro::PomodoroSession; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; -use crate::error::{AppError, ErrorResponse}; +use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service::parent_link::ensure_can_observe; use crate::service::pomodoro; use crate::state::AppState; use crate::validate::validate_optional; -use super::{CurrentUser, PageParams, paginate}; +use super::{CurrentUser, PageParams}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -84,7 +84,8 @@ impl PomodoroResponse { #[derive(Serialize, ToSchema)] struct PomodoroLog { items: Vec, - /// Total sessions in the full log, before `limit`/`offset` are applied. + /// Total sessions in the log the filter selects, before `limit`/`offset` + /// are applied. #[schema(example = 256)] total: i64, /// Echo of the applied `limit`; `null` when the response is unbounded. @@ -93,33 +94,20 @@ struct PomodoroLog { /// Echo of the applied `offset`. #[schema(example = 0)] offset: i64, - /// Sum of `duration_ms` over every *finished* session — the whole log, - /// not just this page. A running session counts nothing until finished. + /// Sum of `duration_ms` over every *finished* session the filter selects — + /// the whole log, not just this page. A running session counts nothing + /// until finished. total_focus_ms: i64, } impl PomodoroLog { - fn new(sessions: &[PomodoroSession], limit: Option, offset: i64) -> Self { - let total_focus_ms = sessions - .iter() - .filter_map(|session| { - session.get_finished_at().map(|done| { - done.as_millis() - .saturating_sub(session.get_started_at().as_millis()) - }) - }) - .sum(); + fn new(page: pomodoro::PomodoroLogPage, limit: Option, offset: i64) -> Self { Self { - // Paged in the web layer: `total_focus_ms` folds the whole log, so the - // rows the page comes from are already all in hand. - items: paginate(sessions, limit, offset) - .iter() - .map(PomodoroResponse::new) - .collect(), - total: sessions.len() as i64, + items: page.items.iter().map(PomodoroResponse::new).collect(), + total: page.total, limit, offset, - total_focus_ms, + total_focus_ms: page.total_focus_ms, } } } @@ -209,19 +197,57 @@ async fn finish( Ok(Json(PomodoroResponse::new(&session))) } +/// The optional `?from=&to=` window over the log. Both bounds are UTC unix +/// milliseconds and half-open — `from` inclusive, `to` exclusive, so +/// adjacent windows tile without overlap — and independent: each present +/// bound narrows from its own end. Absent, the log is untouched. +#[derive(Debug, Deserialize, IntoParams)] +struct HistoryFilter { + /// Keep sessions that started at or after this instant. + #[param(example = 1_760_000_000_000i64)] + from: Option, + /// Keep sessions that started before this instant. + #[param(example = 1_760_008_640_000i64)] + to: Option, +} + +impl HistoryFilter { + /// The validated bounds, or `(None, None)` for the whole log. A negative + /// bound is a `400` naming the field: the server stamps every instant + /// itself, so nothing predates the epoch and a negative value is a + /// malformed request, not an era to page through. + fn resolve(&self) -> Result<(Option, Option), AppError> { + let bound = |value: Option, field: &'static str| match value { + Some(ms) if ms < 0 => Err(AppError::Validation(ValidationError::Invalid { + field, + reason: "must not be negative", + })), + other => Ok(other), + }; + Ok((bound(self.from, "from")?, bound(self.to, "to")?)) + } +} + /// The caller's own pomodoro log, newest first — the running session (if any) /// included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of /// finished-session durations. Paged via `?limit=&offset=` (omit `limit` for /// the whole log). +/// +/// `from`/`to` (unix milliseconds) narrow the log to sessions that started in +/// the half-open window `[from, to)` — both optional, AND-ed when both are +/// given, negative values a `400`. The window bounds the page, `total` and +/// `total_focus_ms` alike: the focus total is the sum over the same filtered +/// set the page reads, and with neither bound the response is the +/// whole-history log, unchanged. #[utoipa::path( get, path = "/me", tag = "pomodoro", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, HistoryFilter), responses( (status = 200, description = "A page of the caller's pomodoro log with the unpaged focus total", body = PomodoroLog), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -229,24 +255,31 @@ async fn my_pomodoro( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, + Query(filter): Query, ) -> Result, AppError> { let (limit, offset) = page.resolve()?; - let sessions = pomodoro::list_for_user(&st.db, user.get_id()).await?; - Ok(Json(PomodoroLog::new(&sessions, limit, offset))) + let (from, to) = filter.resolve()?; + let log = pomodoro::page_for_user(&st.db, user.get_id(), from, to, limit, offset).await?; + Ok(Json(PomodoroLog::new(log, limit, offset))) } /// A student's pomodoro log, newest first, with `total_focus_ms` — the same /// shape as `/me`. Requires teacher+ (study oversight), or a parent tied to /// the target student. Paged via `?limit=&offset=`. +/// +/// Like `/me`, the optional `from`/`to` window (unix milliseconds, the +/// half-open `[from, to)`) narrows the log — page, `total` and +/// `total_focus_ms` together — and leaves the observation rules untouched: a +/// caller who may not read the log cannot read a window of it either. #[utoipa::path( get, path = "/{user}", tag = "pomodoro", security(("session_cookie" = [])), - params(("user" = String, Path, description = "User id"), PageParams), + params(("user" = String, Path, description = "User id"), PageParams, HistoryFilter), responses( (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), @@ -257,14 +290,75 @@ async fn user_pomodoro( CurrentUser(caller): CurrentUser, Path(user): Path, Query(page): Query, + Query(filter): Query, ) -> Result, AppError> { let (limit, offset) = page.resolve()?; + let (from, to) = filter.resolve()?; let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty log. crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; - let sessions = pomodoro::list_for_user(&st.db, &target).await?; - Ok(Json(PomodoroLog::new(&sessions, limit, offset))) + let log = pomodoro::page_for_user(&st.db, &target, from, to, limit, offset).await?; + Ok(Json(PomodoroLog::new(log, limit, offset))) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::Uri; + + #[test] + fn an_absent_window_leaves_the_log_untouched() { + let filter = HistoryFilter { + from: None, + to: None, + }; + assert_eq!(filter.resolve().unwrap(), (None, None)); + } + + #[test] + fn a_negative_bound_is_a_400_naming_the_field() { + let filter = HistoryFilter { + from: Some(-1), + to: None, + }; + let AppError::Validation(ValidationError::Invalid { field, .. }) = + filter.resolve().unwrap_err() + else { + panic!("a negative `from` must be a validation error"); + }; + assert_eq!(field, "from"); + + let filter = HistoryFilter { + from: None, + to: Some(-1), + }; + let AppError::Validation(ValidationError::Invalid { field, .. }) = + filter.resolve().unwrap_err() + else { + panic!("a negative `to` must be a validation error"); + }; + assert_eq!(field, "to"); + } + + #[test] + fn zero_is_a_legal_bound() { + let filter = HistoryFilter { + from: Some(0), + to: Some(0), + }; + assert_eq!(filter.resolve().unwrap(), (Some(0), Some(0))); + } + + #[test] + fn a_present_but_empty_bound_is_a_400_naming_the_field() { + // `?from=` carries no i64: the query extractor itself refuses, the + // same 400 `?limit=` has always given for an empty value. + let err = Query::::try_from_uri(&Uri::from_static("/?from=&to=5")) + .unwrap_err(); + assert_eq!(err.status(), StatusCode::BAD_REQUEST); + assert!(err.body_text().contains("from"), "{}", err.body_text()); + } } diff --git a/src/web/questions.rs b/src/web/questions.rs index b95e7b0..a2a27e2 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -38,7 +38,7 @@ use crate::web::tenant_state::State; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, - paginate, person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob, + person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob, }; pub fn routes() -> OpenApiRouter { @@ -296,6 +296,11 @@ async fn ask_question( /// `approved` question; `pending` ones appear only to their asker and to /// teacher+ — so for a teacher, `?status=pending` is the approval queue. /// Paged via `?limit=&offset=`. +/// +/// The visibility gate and the `status` filter share one SQL `WHERE`, so +/// `total` counts the filtered set — `?status=pending` never loads the whole +/// pool into a `Vec` first. A `status` other than `pending` or `approved` +/// is a 400. #[utoipa::path( get, path = "/", @@ -316,8 +321,9 @@ async fn list_questions( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - if let Some(ref status) = filter.status - && !POOL_QUESTION_STATUSES.contains(&status.as_str()) + let status = filter.status.as_deref().map(str::trim); + if let Some(status) = status + && !POOL_QUESTION_STATUSES.contains(&status) { return Err(AppError::Validation(ValidationError::Invalid { field: "status", @@ -325,18 +331,15 @@ async fn list_questions( })); } - let mut questions = if user.get_role().at_least(Role::Teacher) { - pool_question::list_all(&st.db).await? - } else { - pool_question::list_visible_to(&st.db, user.get_id()).await? - }; - if let Some(ref status) = filter.status { - questions.retain(|question| question.get_status() == status); - } + // Visibility stays exactly what the two reads encoded: teacher+ see the + // approval queue and the pool, everyone else the pool plus their own + // pending questions. Gate and status filter ride one SQL WHERE — `total` + // is the filtered count, and the window is the database's. + let viewer = (!user.get_role().at_least(Role::Teacher)).then_some(user.get_id()); + let (questions, total) = + pool_question::list(&st.db, viewer, status, limit, offset).await?; - let total = questions.len() as i64; - // Paged in the web layer: the status filter above is per-row Rust. - let items = question_responses(paginate(&questions, limit, offset), &st).await?; + let items = question_responses(&questions, &st).await?; Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/users.rs b/src/web/users.rs index 06b3590..602bccd 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -365,19 +365,67 @@ async fn search_users( Ok(Json(Page::new(items, total, limit, offset))) } +/// The admin directory's optional `roles` narrowing: a comma-separated list +/// of role names, e.g. `roles=manager,admin` for the two staff tabs in one +/// read. Absent (`None`) is every user — today's response, unchanged. +#[derive(Debug, Deserialize, IntoParams)] +struct ListUsersFilter { + /// Keep only users whose role is in this comma-separated set: `student`, + /// `parent`, `teacher`, `manager`, or `admin` (an OR, not an AND). Omit + /// to list every role. + roles: Option, +} + +impl ListUsersFilter { + /// Resolve `roles` into the filter set. Each token is trimmed, then + /// parsed with [`Role::try_from_str`] — the same vocabulary + /// `GET /users/search` parses `role` with. An empty value (`?roles=`), a + /// blank token (`roles=manager,`), or an unknown name is a `400` naming + /// `roles` — the same refusal shape every other closed set answers with, + /// never a silently empty page. + fn resolve(&self) -> Result>, ValidationError> { + let Some(raw) = self.roles.as_deref() else { + return Ok(None); + }; + raw.split(',') + .map(|token| { + Role::try_from_str(token.trim()).map_err(|err| match err { + // The parser names its field `role`; this param is the + // plural `roles`, so the refusal must name what the + // request actually carried. + ValidationError::Invalid { reason, .. } => ValidationError::Invalid { + field: "roles", + reason, + }, + err => err, + }) + }) + .collect::, _>>() + .map(Some) + } +} + /// List every user with their role, newest first. Admin only. Paged: pass /// `?limit=&offset=` to take a window (omit `limit` for the whole list); the /// response is a `{items, total, limit, offset}` envelope where `total` counts /// every user. +/// +/// The optional `roles` parameter narrows the directory to a set of roles — +/// a comma-separated list (`roles=manager,admin` is the two staff tabs in +/// one read, an OR). Omitted, the response is the whole roster. The window +/// and `total` are taken after the narrowing, so `total` counts the filtered +/// set and paging stays inside it. Each name is the vocabulary +/// `GET /users/search` parses; an unknown name, a blank value, or a blank +/// token is a `400` naming `roles`. #[utoipa::path( get, path = "/", tag = "users", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, ListUsersFilter), responses( (status = 200, description = "A page of users (the full list when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit or offset, or an unknown `roles` entry", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires admin role", body = ErrorResponse), ), @@ -386,9 +434,12 @@ async fn list_users( State(st): State, _admin: RequireAdmin, Query(page): Query, + Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?; + let roles = filter.resolve()?; + let (users, total) = + crate::service::user::list_all(&st.db, roles.as_deref(), limit, offset).await?; let items = users.iter().map(UserResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -1591,3 +1642,50 @@ async fn drop_avatar(st: &AppState, user: &UserId) -> Result) -> ListUsersFilter { + ListUsersFilter { + roles: roles.map(str::to_owned), + } + } + + #[test] + fn absent_roles_is_every_user() { + assert_eq!(filter(None).resolve().unwrap(), None); + } + + #[test] + fn roles_parse_into_the_role_set() { + // The manager tab is one OR set, not an intersection. + assert_eq!( + filter(Some("manager,admin")).resolve().unwrap(), + Some(vec![Role::Manager, Role::Admin]) + ); + assert_eq!( + filter(Some("student")).resolve().unwrap(), + Some(vec![Role::Student]) + ); + // A stray space rides the trim, like every other query value. + assert_eq!( + filter(Some(" teacher ")).resolve().unwrap(), + Some(vec![Role::Teacher]) + ); + } + + #[test] + fn a_bad_roles_value_is_refused_naming_roles() { + // Empty value, unknown name, blank token, whitespace-only token, and + // the non-assignable service principal — all the same field naming. + for bad in ["", "nope", "manager,", "manager, ,admin", "ai"] { + let err = filter(Some(bad)).resolve().unwrap_err(); + let ValidationError::Invalid { field, .. } = err else { + panic!("expected Invalid for {bad:?}, got {err}"); + }; + assert_eq!(field, "roles", "{bad:?} must name the roles field"); + } + } +} diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs index 3414751..2026fa4 100644 --- a/tests/regress_meals.rs +++ b/tests/regress_meals.rs @@ -23,12 +23,17 @@ use serde_json::json; /// Publish a menu for `date`, uncapped unless told otherwise. async fn publish(app: &axum::Router, mgr: &str, date: &str) -> String { + publish_slot(app, mgr, date, "lunch").await +} + +/// Publish a menu for `date` under an explicit slot name. +async fn publish_slot(app: &axum::Router, mgr: &str, date: &str, slot: &str) -> String { let res = send( app, "POST", "/meals/menus", Some(mgr), - Some(json!({ "date": date, "slot": "lunch" })), + Some(json!({ "date": date, "slot": slot })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -1412,3 +1417,154 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); } + +/// `?slot=` on `GET /meals/menus` filters in SQL — the page *and* the count +/// off one WHERE — so `total` is the filtered count and `limit`/`offset` +/// window inside the filtered set, not the unfiltered one. The match is the +/// slot text each menu snapshotted at publish: no menu carries it, the page +/// is empty at `200`; an empty value is a `400` naming the field. +#[tokio::test] +async fn the_menu_list_slot_filter_narrows_rows_and_total_together() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "mslot_admin", "admin").await; + let mgr = login_as(&app, &db, "mslot_mgr", "manager").await; + // Two slots, so a filter has something to exclude. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{ "name": "lunch" }, { "name": "dinner" }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + for (date, slot) in [ + ("2099-03-01", "lunch"), + ("2099-03-02", "dinner"), + ("2099-03-03", "lunch"), + ("2099-03-04", "dinner"), + ] { + publish_slot(&app, &mgr, date, slot).await; + } + + // Absent: every menu, exactly as before the filter existed. + let res = send(&app, "GET", "/meals/menus", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(4), "{}", res.body); + + // Matched: only that slot's menus, and `total` is the filtered count — + // neither the page size nor the unfiltered total. + let res = send(&app, "GET", "/meals/menus?slot=dinner", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let items = res.body["items"].as_array().unwrap(); + assert_eq!(items.len(), 2, "{}", res.body); + assert!(items.iter().all(|m| m["slot"] == "dinner"), "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body); + + // The window applies *after* the filter: one dinner per page, two pages, + // and `total` stays the filtered count on both. + let res = send( + &app, + "GET", + "/meals/menus?slot=dinner&limit=1&offset=1", + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let items = res.body["items"].as_array().unwrap(); + assert_eq!(items.len(), 1, "{}", res.body); + // Newest day first within the filtered set. + assert_eq!(items[0]["date"], "2099-03-02", "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body); + + // Composes with the date range: the lunch menus inside it only. + let res = send( + &app, + "GET", + "/meals/menus?slot=lunch&from=2099-03-02&to=2099-03-04", + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(1), "{}", res.body); + assert_eq!(res.body["items"][0]["date"], "2099-03-03", "{}", res.body); + + // The value is trimmed before matching. + let res = send(&app, "GET", "/meals/menus?slot=%20dinner%20", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body); + + // A well-formed name no menu carries: an empty page at `200`, not a 404. + let res = send(&app, "GET", "/meals/menus?slot=brunch", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + res.body["items"].as_array().unwrap().len(), + 0, + "{}", + res.body + ); + assert_eq!(res.body["total"].as_i64(), Some(0), "{}", res.body); + + // Empty: refused, naming the field. + let res = send(&app, "GET", "/meals/menus?slot=", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + assert!( + res.body["error"].as_str().unwrap().contains("slot"), + "the refusal must name the field: {}", + res.body + ); +} + +/// The slot filter must *not* validate against the school's current +/// `meal_slots`: a menu snapshots its slot's name at publish, so a slot +/// retired since still has to find the menus published under it. The write +/// path itself refuses to drop a slot that has menus (`409`), so a retired +/// slot with menus exists only where a settings row written before that rule +/// left one behind — the state this test writes by hand, like its +/// `a_slot_whose_name_would_break_the_menu_url` sibling does. +#[tokio::test] +async fn a_retired_slot_still_finds_the_menus_published_under_it() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "ret_adm", "admin").await; + let mgr = login_as(&app, &db, "ret_mgr", "manager").await; + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{ "name": "brunch" }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + publish_slot(&app, &mgr, "2099-04-01", "brunch").await; + + // The live route refuses the retirement — that guard is what makes the + // retired-but-published state reachable only through older rows. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{ "name": "lunch" }] })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // …so the retirement lands the way history actually left one: a settings + // row written before the guard existed. + sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'") + .bind(sqlx::types::Json(json!([ + { "name": "lunch", "serving_minute": null } + ]))) + .execute(&db) + .await + .unwrap(); + + let res = send(&app, "GET", "/meals/menus?slot=brunch", Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"].as_i64(), Some(1), "{}", res.body); + assert_eq!(res.body["items"][0]["slot"], "brunch", "{}", res.body); +}