forge
Explore
Log in

Don't you dare go Hollow

Server-side filters on the list doors

Browse files at this commit

d8dad926f1eaa0a040d734a6379e8813064bf907Ahmet Kaan GümüşParent: 51e5c7b
  • feat
    • server-side filters on the list doors
Show full message
✨ feat(api): server-side filters on the list doors

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.

45 changed files +4698 -490

src/db/appointment.rsmodified+117 -61
@@ -132,86 +132,142 @@ where
132132 Ok(appointment)
133133 }
134134
135+/// The caller's own bookings, newest first. The optional filters narrow the
136+/// read: `status` matches the stored state, `starts_after`/`starts_before`
137+/// bound the meeting's effective start — a standing proposal, the slot's
138+/// window otherwise — from below (inclusive) and above (exclusive, so a
139+/// month is `[start, next_start)`), and `teacher` is the booked slot's
140+/// teacher — which needs the slot row, so the read runs over a derived table
141+/// the window and its count share. A booking whose slot is gone has no
142+/// meeting time and no teacher, so any of those three filters drops it; with
143+/// no filter the read stays the plain single-table one, so today's rows
144+/// (dangling bookings included) are untouched.
135145 pub async fn list_for_requester(
136146 db: &Database,
137147 requester: &UserId,
148+ status: Option<AppointmentStatus>,
149+ starts_after: Option<Timestamp>,
150+ starts_before: Option<Timestamp>,
151+ teacher: Option<&UserId>,
138152 limit: Option<i64>,
139153 offset: i64,
140154 ) -> Result<(Vec<Appointment>, i64), AppError> {
141- PagedList::new("appointment WHERE requester = $1", "ORDER BY id DESC")
142- .bind(requester.uuid())
143- .run(limit, offset, db)
144- .await
155+ // Spell the appointment columns against the join alias, so the derived
156+ // table's row keeps the exact names [`Appointment`] decodes and the
157+ // slot's duplicate column names never leak in. The plain shape aliases
158+ // the table too, so the one clause builder speaks both shapes.
159+ const JOINED: &str = "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \
160+ a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \
161+ a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \
162+ FROM appointment a LEFT JOIN appointment_slot s ON a.slot = s.id \
163+ WHERE a.requester = $1";
164+ let joined = teacher.is_some() || starts_after.is_some() || starts_before.is_some();
165+ let mut from_where = if joined {
166+ JOINED.to_string()
167+ } else {
168+ "appointment a WHERE a.requester = $1".to_string()
169+ };
170+ // The meeting's start: a standing proposal overrides the slot's window
171+ // (the same rule [`Appointment::window`] applies), so the predicate
172+ // coalesces them — and these clauses only ever ride the joined shape,
173+ // where the slot row is in hand.
174+ let mut next = 2;
175+ if status.is_some() {
176+ from_where.push_str(&format!(" AND a.status = ${next}"));
177+ next += 1;
178+ }
179+ if starts_after.is_some() {
180+ from_where.push_str(&format!(
181+ " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}"
182+ ));
183+ next += 1;
184+ }
185+ if starts_before.is_some() {
186+ from_where.push_str(&format!(
187+ " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}"
188+ ));
189+ next += 1;
190+ }
191+ if teacher.is_some() {
192+ from_where.push_str(&format!(" AND s.teacher = ${next}"));
193+ }
194+ // Close the derived table when the read is the joined shape; the plain
195+ // single-table shape opened none.
196+ if joined {
197+ from_where.push(')');
198+ }
199+ let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(requester.uuid());
200+ if let Some(status) = status {
201+ list = list.bind(status.as_str().to_string());
202+ }
203+ if let Some(after) = starts_after {
204+ list = list.bind(after.as_millis());
205+ }
206+ if let Some(before) = starts_before {
207+ list = list.bind(before.as_millis());
208+ }
209+ if let Some(teacher) = teacher {
210+ list = list.bind(teacher.uuid());
211+ }
212+ list.run(limit, offset, db).await
145213 }
146214
147215 /// Every booking aimed at `teacher`, across all their slots — the
148216 /// teacher's request inbox. The teacher lives on the slot row now, so
149217 /// this is a join; the page and its count share the one predicate, and
150218 /// the columns are spelled out so the join's duplicate slot-column names
151-/// can never leak into the row decode.
219+/// can never leak into the row decode. `status` narrows to one booking
220+/// state and `starts_after`/`starts_before` to meetings whose effective
221+/// start (a standing proposal, the slot's window otherwise) sits in
222+/// `[after, before)` — both bounds optional, both in the SQL, so the
223+/// count always describes exactly the rows the window pages over.
152224 pub async fn list_for_teacher(
153225 db: &Database,
154226 teacher: &UserId,
227+ status: Option<AppointmentStatus>,
228+ starts_after: Option<Timestamp>,
229+ starts_before: Option<Timestamp>,
155230 limit: Option<i64>,
156231 offset: i64,
157232 ) -> Result<(Vec<Appointment>, i64), AppError> {
158- match limit {
159- None => {
160- let rows = query_as!(
161- Appointment,
162- "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \
163- a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \
164- a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
165- a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
166- a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \
167- a.cancelled_by AS \"cancelled_by: UserId\", \
168- a.cancel_reason AS \"cancel_reason: AppointmentReason\", \
169- a.reject_reason AS \"reject_reason: AppointmentReason\", \
170- a.created_at AS \"created_at: Timestamp\" \
171- FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
172- WHERE s.teacher = $1 \
173- ORDER BY a.id DESC",
174- teacher.uuid()
175- )
176- .fetch_all(db)
177- .await?;
178- let total = rows.len() as i64;
179- Ok((rows, total))
180- }
181- Some(limit) => {
182- let rows = query_as!(
183- Appointment,
184- "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \
185- a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \
186- a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
187- a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
188- a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \
189- a.cancelled_by AS \"cancelled_by: UserId\", \
190- a.cancel_reason AS \"cancel_reason: AppointmentReason\", \
191- a.reject_reason AS \"reject_reason: AppointmentReason\", \
192- a.created_at AS \"created_at: Timestamp\" \
193- FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
194- WHERE s.teacher = $1 \
195- ORDER BY a.id DESC LIMIT $2 OFFSET $3",
196- teacher.uuid(),
197- limit,
198- offset
199- )
200- .fetch_all(db)
201- .await?;
202- let total = query!(
203- "SELECT count(*) AS total \
204- FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
205- WHERE s.teacher = $1",
206- teacher.uuid()
207- )
208- .fetch_one(db)
209- .await?
210- .total
211- .unwrap_or(0);
212- Ok((rows, total))
213- }
233+ // The join wrapped as one derived table, so [`PagedList`]'s `SELECT *`
234+ // still sees exactly the appointment columns.
235+ let mut from_where = String::from(
236+ "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \
237+ a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \
238+ a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \
239+ FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
240+ WHERE s.teacher = $1",
241+ );
242+ let mut next = 2;
243+ if status.is_some() {
244+ from_where.push_str(&format!(" AND a.status = ${next}"));
245+ next += 1;
246+ }
247+ if starts_after.is_some() {
248+ from_where.push_str(&format!(
249+ " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}"
250+ ));
251+ next += 1;
252+ }
253+ if starts_before.is_some() {
254+ from_where.push_str(&format!(
255+ " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}"
256+ ));
257+ }
258+ // Close the derived table the clauses were appended into.
259+ from_where.push(')');
260+ let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(teacher.uuid());
261+ if let Some(status) = status {
262+ list = list.bind(status.as_str().to_string());
263+ }
264+ if let Some(after) = starts_after {
265+ list = list.bind(after.as_millis());
266+ }
267+ if let Some(before) = starts_before {
268+ list = list.bind(before.as_millis());
214269 }
270+ list.run(limit, offset, db).await
215271 }
216272
217273 pub async fn list_for_slot(
src/db/appointment_slot.rsmodified+45 -25
@@ -11,6 +11,7 @@
1111 //! texts; the constraint is the authority a racing publish answers to.
1212
1313 use crate::database::{Database, exclusion_violation, tx_with_retry, unique_violation};
14+use crate::db::page::PagedList;
1415 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
1516 use crate::domain::role::Role;
1617 use crate::domain::timestamp::Timestamp;
@@ -184,23 +185,28 @@ pub async fn read(
184185 Ok(slot)
185186 }
186187
187-/// A teacher's own calendar, earliest first.
188+/// A teacher's own calendar, earliest first. `starts_after` cuts the read in
189+/// the SQL, so asking for the upcoming window never loads the whole past to
190+/// slice it in the caller — a calendar of years of weekly publishes stays a
191+/// bounded scan. The predicate is the same either way, so the filtered and
192+/// unfiltered reads answer in one shared shape.
188193 pub async fn list_for_teacher(
189194 db: &Database,
190195 teacher: &UserId,
196+ starts_after: Option<Timestamp>,
191197 ) -> Result<Vec<AppointmentSlot>, AppError> {
192- let slots = query_as!(
193- AppointmentSlot,
194- "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
195- ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
196- series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
197- FROM appointment_slot WHERE teacher = $1 \
198- ORDER BY starts_at ASC, id ASC",
199- teacher.uuid()
200- )
201- .fetch_all(db)
202- .await?;
203- Ok(slots)
198+ let mut from_where = String::from("appointment_slot WHERE teacher = $1");
199+ if starts_after.is_some() {
200+ from_where.push_str(" AND starts_at >= $2");
201+ }
202+ let mut list =
203+ PagedList::new(from_where, "ORDER BY starts_at ASC, id ASC").bind(teacher.uuid());
204+ if let Some(after) = starts_after {
205+ list = list.bind(after.as_millis());
206+ }
207+ // Unpaged on purpose: the callers slice the window in the web layer.
208+ let (rows, _) = list.run(None, 0, db).await?;
209+ Ok(rows)
204210 }
205211
206212 /// Every slot whose window has not opened yet, earliest first — the bookable
@@ -216,19 +222,33 @@ pub async fn list_for_teacher(
216222 pub async fn list_upcoming(
217223 db: &Database,
218224 from: Timestamp,
225+ teacher: Option<&UserId>,
226+ starts_after: Option<Timestamp>,
219227 ) -> Result<Vec<AppointmentSlot>, AppError> {
220- let slots = query_as!(
221- AppointmentSlot,
222- "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
223- ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
224- series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
225- FROM appointment_slot WHERE starts_at > $1 \
226- ORDER BY starts_at ASC, id ASC",
227- from.as_millis()
228- )
229- .fetch_all(db)
230- .await?;
231- Ok(slots)
228+ // The strict `starts_at > from` bound is the bookable calendar itself and
229+ // never moves; the optional filters only narrow inside it, each taking
230+ // the placeholder number its bind position gives it.
231+ let mut from_where = String::from("appointment_slot WHERE starts_at > $1");
232+ let mut next = 2;
233+ if starts_after.is_some() {
234+ from_where.push_str(&format!(" AND starts_at >= ${next}"));
235+ next += 1;
236+ }
237+ if teacher.is_some() {
238+ from_where.push_str(&format!(" AND teacher = ${next}"));
239+ }
240+ let mut list =
241+ PagedList::new(from_where, "ORDER BY starts_at ASC, id ASC").bind(from.as_millis());
242+ if let Some(after) = starts_after {
243+ list = list.bind(after.as_millis());
244+ }
245+ if let Some(teacher) = teacher {
246+ list = list.bind(teacher.uuid());
247+ }
248+ // Unpaged on purpose: the web layer retains the live teachers' rows and
249+ // slices the page after that filter, so the window cannot move into SQL.
250+ let (rows, _) = list.run(None, 0, db).await?;
251+ Ok(rows)
232252 }
233253
234254 pub async fn list_for_series(
src/db/board.rsmodified+121 -6
@@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry, unique_violation};
77 use crate::db::page::PagedList;
88 use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants};
99 use crate::domain::timestamp::Timestamp;
10+use crate::domain::text_fold::{search_fold, search_fold_sql};
1011 use crate::domain::user::UserId;
1112 use crate::error::AppError;
1213
@@ -130,24 +131,38 @@ pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError
130131 /// that is locked, or full at its lifetime cap but never drawn on again, is
131132 /// never stamped and so reads as **open** — because it is. Only a creator's
132133 /// `/close` and the lifetime cap's own refusal ever stamp one.
134+///
135+/// `q` is an optional free-text needle over the title, folded case- and
136+/// diacritic-insensitively on both sides ([`search_fold`] /
137+/// [`search_fold_sql`]); a blank needle searches nothing.
133138 pub async fn list_for_user(
134139 db: &Database,
135140 user: &UserId,
136141 open: Option<bool>,
142+ q: Option<&str>,
137143 limit: Option<i64>,
138144 offset: i64,
139145 ) -> Result<(Vec<Board>, i64), AppError> {
146+ // A blank needle searches nothing, exactly like an absent one.
147+ let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
140148 let open_clause = match open {
141149 Some(true) => " AND b.closed_at IS NULL",
142150 Some(false) => " AND b.closed_at IS NOT NULL",
143151 None => "",
144152 };
153+ // The needle rides the same fold on both sides (`position`, not `LIKE`,
154+ // keeps `%` and `_` literal); `$1` and `$2` are always spent on the
155+ // membership predicate, so the needle is `$3`.
156+ let q_clause = match needle {
157+ Some(_) => format!(" AND position($3 in {}) > 0", search_fold_sql("b.title")),
158+ None => String::new(),
159+ };
145160 // `PagedList` wraps `from_where` in `SELECT * FROM (…)`, so the window
146161 // is a whole derived table: the row columns plus the roster
147162 // re-assembled from `board_participant`, and the membership half of the
148163 // predicate as an `EXISTS` over it (the participant-side index covers
149164 // it, as the GIN index once did).
150- PagedList::new(
165+ let mut builder = PagedList::new(
151166 format!(
152167 "(SELECT b.id, b.creator, b.title,
153168 ARRAY(SELECT p.participant FROM board_participant p
@@ -156,14 +171,16 @@ pub async fn list_for_user(
156171 FROM board b
157172 WHERE (b.creator = $1
158173 OR EXISTS (SELECT 1 FROM board_participant bp
159- WHERE bp.board = b.id AND bp.participant = $2)){open_clause})"
174+ WHERE bp.board = b.id AND bp.participant = $2)){open_clause}{q_clause})"
160175 ),
161176 "ORDER BY id DESC",
162177 )
163178 .bind(user.uuid())
164- .bind(user.uuid())
165- .run::<Board>(limit, offset, db)
166- .await
179+ .bind(user.uuid());
180+ if let Some(needle) = needle {
181+ builder = builder.bind(needle);
182+ }
183+ builder.run::<Board>(limit, offset, db).await
167184 }
168185
169186 /// Re-invite: the creator-driven roster replace. The write is the
@@ -461,7 +478,7 @@ mod tests {
461478 .await;
462479 assert!(matches!(over, Err(AppError::Conflict(_))));
463480
464- let last = list_for_user(&db, &creator, None, None, 0)
481+ let last = list_for_user(&db, &creator, None, None, None, 0)
465482 .await
466483 .unwrap()
467484 .0
@@ -479,4 +496,102 @@ mod tests {
479496 .await;
480497 assert!(again.is_ok());
481498 }
499+
500+ /// `q` narrows by title through the search fold (`geometri` finds
501+ /// `Geometri`), composes with `open`, and pages after the filter
502+ /// (`total` counts matches, not rows) — while the membership predicate
503+ /// still scopes every row: a non-participant searching a real title
504+ /// sees nothing.
505+ #[tokio::test]
506+ async fn q_searches_titles_and_composes_with_open() {
507+ let (db, _leases) = crate::database::init_test_db().await;
508+ let creator = crate::db::class_member::tests::fixture_user(&db, "q-board-kurucu").await;
509+ let outsider = crate::db::class_member::tests::fixture_user(&db, "q-board-disari").await;
510+
511+ let open_hit = create(
512+ &db,
513+ &creator,
514+ BoardTitle::try_new("Geometri Kampı").unwrap(),
515+ Vec::new(),
516+ )
517+ .await
518+ .unwrap();
519+ create(
520+ &db,
521+ &creator,
522+ BoardTitle::try_new("Cebir").unwrap(),
523+ Vec::new(),
524+ )
525+ .await
526+ .unwrap();
527+ let closed_hit = create(
528+ &db,
529+ &creator,
530+ BoardTitle::try_new("Geometri Kapanış").unwrap(),
531+ Vec::new(),
532+ )
533+ .await
534+ .unwrap();
535+ close(&db, &closed_hit).await.unwrap();
536+
537+ // Absent and blank needles both see every board.
538+ let (_, total) = list_for_user(&db, &creator, None, None, None, 0)
539+ .await
540+ .unwrap();
541+ assert_eq!(total, 3);
542+ let (_, total) = list_for_user(&db, &creator, None, Some(" "), None, 0)
543+ .await
544+ .unwrap();
545+ assert_eq!(total, 3);
546+
547+ // Title hits through the fold, in both directions.
548+ for needle in ["geometri", "GEOMETRİ"] {
549+ let (hits, total) =
550+ list_for_user(&db, &creator, None, Some(needle), None, 0)
551+ .await
552+ .unwrap();
553+ assert_eq!(total, 2);
554+ let keys: Vec<String> = hits
555+ .iter()
556+ .map(|board| board.get_id().key().to_string())
557+ .collect();
558+ assert!(keys.contains(&open_hit.get_id().key().to_string()));
559+ assert!(keys.contains(&closed_hit.get_id().key().to_string()));
560+ }
561+
562+ // Composes with `open`.
563+ let (hits, total) =
564+ list_for_user(&db, &creator, Some(true), Some("geometri"), None, 0)
565+ .await
566+ .unwrap();
567+ assert_eq!(total, 1);
568+ assert_eq!(hits[0].get_id().key().to_string(), open_hit.get_id().key().to_string());
569+ let (_, total) = list_for_user(&db, &creator, Some(false), Some("geometri"), None, 0)
570+ .await
571+ .unwrap();
572+ assert_eq!(total, 1);
573+
574+ // The window runs after the filter: `total` counts matches.
575+ let (hits, total) = list_for_user(&db, &creator, None, Some("geometri"), Some(1), 0)
576+ .await
577+ .unwrap();
578+ assert_eq!(total, 2);
579+ assert_eq!(hits.len(), 1);
580+
581+ // A needle matching nothing: an empty page, not an error.
582+ let (hits, total) = list_for_user(&db, &creator, None, Some("yok boyle bir tahta"), None, 0)
583+ .await
584+ .unwrap();
585+ assert_eq!(total, 0);
586+ assert!(hits.is_empty());
587+
588+ // The membership predicate still scopes the search: a non-participant
589+ // searching a title that exists finds nothing.
590+ let (hits, total) =
591+ list_for_user(&db, &outsider, None, Some("geometri"), None, 0)
592+ .await
593+ .unwrap();
594+ assert_eq!(total, 0);
595+ assert!(hits.is_empty());
596+ }
482597 }
src/db/course.rsmodified+59 -1
@@ -10,8 +10,9 @@
1010
1111 use crate::constant::COURSE_TABLE;
1212 use crate::database::{Database, tx_with_retry, unique_violation};
13-use crate::db::page::PagedList;
13+use crate::db::page::{PagedList, Param};
1414 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
15+use crate::domain::text_fold::{search_fold, search_fold_sql};
1516 use crate::domain::user::UserId;
1617 use crate::error::AppError;
1718 use sqlx::PgConnection;
@@ -118,6 +119,63 @@ pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
118119 Ok(rows.into_iter().map(CourseRow::into_course).collect())
119120 }
120121
122+/// The catalog the visible list's manager arm serves — the whole table,
123+/// newest first — with the `GET /courses` optional filters pushed into the
124+/// SQL `WHERE`, so listing one kind (or searching, or the taught/untaught
125+/// axis) is not a full-catalog pull the caller then throws most of away.
126+/// `kind` is the exact flavor; `q` is a case- and diacritic-insensitive
127+/// fragment of the title or the description (blank = no text filter): needle
128+/// and columns both go through [`crate::domain::text_fold`], so `satranc`
129+/// finds `Satranç` and back. `position` rather than `LIKE` keeps the needle
130+/// a *literal* substring — no `%`/`_` wildcard surprises. `taught` keys on
131+/// the row's own attachment counter: `true` keeps the courses a class
132+/// section teaches (`class_course_count > 0`), `false` the ones nothing
133+/// attaches yet. Every filter is part of the one `WHERE` the window and any
134+/// count share ([`PagedList`]), so a filtered total can never disagree with
135+/// the rows it counts.
136+pub async fn list_filtered(
137+ db: &Database,
138+ kind: Option<CourseKind>,
139+ q: Option<&str>,
140+ taught: Option<bool>,
141+) -> Result<Vec<Course>, AppError> {
142+ let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
143+ let mut clauses: Vec<String> = Vec::new();
144+ let mut binds: Vec<Param> = Vec::new();
145+ if let Some(kind) = &kind {
146+ binds.push(Param::Text(kind.as_str().to_string()));
147+ clauses.push(format!("kind = ${}", binds.len()));
148+ }
149+ if let Some(taught) = taught {
150+ binds.push(Param::I64(0));
151+ clauses.push(format!(
152+ "class_course_count {} ${}",
153+ if taught { ">" } else { "=" },
154+ binds.len()
155+ ));
156+ }
157+ if let Some(needle) = &needle {
158+ binds.push(Param::Text(needle.clone()));
159+ let at = binds.len();
160+ clauses.push(format!(
161+ "(position(${at} in {}) > 0 OR position(${at} in {}) > 0)",
162+ search_fold_sql("title"),
163+ search_fold_sql("description"),
164+ ));
165+ }
166+ let from_where = if clauses.is_empty() {
167+ "course WHERE true".to_string()
168+ } else {
169+ format!("course WHERE {}", clauses.join(" AND "))
170+ };
171+ let mut page = PagedList::new(from_where, "ORDER BY id DESC");
172+ for bind in binds {
173+ page = page.bind(bind);
174+ }
175+ let (rows, _) = page.run::<CourseRow>(None, 0, db).await?;
176+ Ok(rows.into_iter().map(CourseRow::into_course).collect())
177+}
178+
121179 /// The courses `user` is enrolled in — read through the *instances* their
122180 /// enrollments name, since an enrollment keys on the class×course instance.
123181 /// The spine of `/courses/me` and the marks report.
src/db/course_session.rsmodified+120 -7
@@ -173,19 +173,36 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSe
173173 /// An instance's sessions, most recent lesson first. Ordered by `starts_at`
174174 /// (not id): a timetable is read by when the lesson happens, not by when
175175 /// the row was created.
176+///
177+/// `starts_after`/`starts_before` narrow the list to a half-open
178+/// `[starts_after, starts_before)` on `starts_at` — a calendar month is
179+/// `[month_start, next_month_start)` — with the page and the count sharing
180+/// the one `WHERE`. Absent bounds leave today's unfiltered read.
176181 pub async fn list_for_class_course(
177182 db: &Database,
178183 class_course: &ClassCourseId,
184+ starts_after: Option<i64>,
185+ starts_before: Option<i64>,
179186 limit: Option<i64>,
180187 offset: i64,
181188 ) -> Result<(Vec<CourseSession>, i64), AppError> {
182- PagedList::new(
183- "course_session WHERE class_course = $1",
184- "ORDER BY starts_at DESC, id DESC",
185- )
186- .bind(class_course.uuid())
187- .run::<CourseSession>(limit, offset, db)
188- .await
189+ let from_where = match (starts_after, starts_before) {
190+ (Some(_), Some(_)) => {
191+ "course_session WHERE class_course = $1 AND starts_at >= $2 AND starts_at < $3"
192+ }
193+ (Some(_), None) => "course_session WHERE class_course = $1 AND starts_at >= $2",
194+ (None, Some(_)) => "course_session WHERE class_course = $1 AND starts_at < $2",
195+ (None, None) => "course_session WHERE class_course = $1",
196+ };
197+ let mut list = PagedList::new(from_where, "ORDER BY starts_at DESC, id DESC")
198+ .bind(class_course.uuid());
199+ if let Some(after) = starts_after {
200+ list = list.bind(after);
201+ }
202+ if let Some(before) = starts_before {
203+ list = list.bind(before);
204+ }
205+ list.run::<CourseSession>(limit, offset, db).await
189206 }
190207
191208 /// Request-scoped: the handler holds nothing across its read and this
@@ -339,4 +356,100 @@ mod tests {
339356 )
340357 .await;
341358 }
359+
360+ /// One section, three lessons an hour apart across `now`. Starts differ
361+ /// per row: the section's `UNIQUE (class_course, starts_at)` refuses a
362+ /// shared instant, and the window bounds below hang off that middle
363+ /// lesson's exact start.
364+ async fn three_sessions(db: &Database) -> (ClassCourseId, i64) {
365+ let (instance, _) = crate::db::course::a_test_instance(db).await;
366+ let teacher = UserId::generate();
367+ sqlx::query(
368+ "INSERT INTO app_user (id, username, created_at, role) \
369+ VALUES ($1, $2, 0, 'teacher')",
370+ )
371+ .bind(teacher.uuid())
372+ .bind(format!("session-window-{}", &teacher.key()[30..]))
373+ .execute(db)
374+ .await
375+ .unwrap();
376+ let now = Timestamp::now().as_millis();
377+ for starts_at in [now - 3_600_000, now, now + 3_600_000] {
378+ create(
379+ db,
380+ &instance,
381+ &teacher,
382+ SessionTopic::try_new("limits").unwrap(),
383+ Timestamp::from_millis(starts_at),
384+ None,
385+ )
386+ .await
387+ .unwrap();
388+ }
389+ (instance, now)
390+ }
391+
392+ #[tokio::test]
393+ async fn the_session_window_is_half_open_on_starts_at() {
394+ let (db, _leases) = crate::database::init_test_db().await;
395+ let (instance, now) = three_sessions(&db).await;
396+
397+ // Absent bounds: every session, most recent lesson first.
398+ let (rows, total) = list_for_class_course(&db, &instance, None, None, None, 0)
399+ .await
400+ .unwrap();
401+ assert_eq!(total, 3);
402+ let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect();
403+ assert_eq!(starts, vec![now + 3_600_000, now, now - 3_600_000]);
404+
405+ // starts_after is inclusive: the middle lesson (exactly `now`) stays,
406+ // and the order does not flip.
407+ let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, None, 0)
408+ .await
409+ .unwrap();
410+ assert_eq!(total, 2);
411+ let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect();
412+ assert_eq!(starts, vec![now + 3_600_000, now]);
413+
414+ // starts_before is strict: the middle lesson is out.
415+ let (rows, total) = list_for_class_course(&db, &instance, None, Some(now), None, 0)
416+ .await
417+ .unwrap();
418+ assert_eq!(total, 1);
419+ assert_eq!(rows[0].get_starts_at().as_millis(), now - 3_600_000);
420+
421+ // The half-open pair pins exactly the middle lesson.
422+ let (rows, total) = list_for_class_course(
423+ &db,
424+ &instance,
425+ Some(now),
426+ Some(now + 3_600_000),
427+ None,
428+ 0,
429+ )
430+ .await
431+ .unwrap();
432+ assert_eq!((rows.len(), total), (1, 1));
433+ assert_eq!(rows[0].get_starts_at().as_millis(), now);
434+
435+ // The limit pages the filtered set; total is the filtered count.
436+ let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, Some(1), 0)
437+ .await
438+ .unwrap();
439+ assert_eq!((rows.len(), total), (1, 2));
440+ assert_eq!(rows[0].get_starts_at().as_millis(), now + 3_600_000);
441+
442+ // An instant naming no lesson is an empty page, not an error.
443+ let (rows, total) = list_for_class_course(
444+ &db,
445+ &instance,
446+ Some(now + 30 * 86_400_000),
447+ None,
448+ None,
449+ 0,
450+ )
451+ .await
452+ .unwrap();
453+ assert!(rows.is_empty() && total == 0);
454+ }
342455 }
src/db/event.rsmodified+167 -17
@@ -4,7 +4,7 @@
44
55 use crate::database::{Database, tx_with_retry};
66 use crate::db::field_update::FieldUpdate;
7-use crate::db::page::Param;
7+use crate::db::page::{PagedList, Param};
88 use crate::domain::class_group::ClassGroupId;
99 use crate::domain::course::CourseId;
1010 use crate::domain::event::{
@@ -68,7 +68,7 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool,
6868 pub async fn members(db: &Database, event: &Event) -> Result<Vec<UserId>, AppError> {
6969 match event.get_audience_kind() {
7070 crate::domain::event::EventAudienceKind::School => {
71- Ok(crate::db::user::list_all(db, None, 0)
71+ Ok(crate::db::user::list_all(db, None, None, 0)
7272 .await?
7373 .0
7474 .iter()
@@ -164,21 +164,55 @@ pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError
164164 Ok(event)
165165 }
166166
167-pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
168- let events = query_as!(
169- Event,
170- "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
171- audience_kind AS \"audience_kind: EventAudienceKind\", \
172- audience_role AS \"audience_role: Role\", \
173- audience_course AS \"audience_course: CourseId\", \
174- audience_class AS \"audience_class: ClassGroupId\", \
175- audience_capacity, starts_at AS \"starts_at: Timestamp\", \
176- ends_at AS \"ends_at: Timestamp\" \
177- FROM event ORDER BY id DESC",
178- )
179- .fetch_all(db)
180- .await?;
181- Ok(events)
167+/// The event list behind `GET /events`, paged by the database — the window is
168+/// `LIMIT/OFFSET` in SQL, and `total` a `count(*)` over the same `WHERE`, so
169+/// a schedule query never decodes the whole table to slice ten rows off it.
170+///
171+/// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule
172+/// window, validated upstream. All four absent is the unfiltered read,
173+/// `ORDER BY id DESC` (newest first). Any bound set drops schedule-less rows
174+/// (every predicate is `NULL`-rejecting) and flips the order to ascending by
175+/// schedule — `starts_at`, falling back to `ends_at`, ties by id — the same
176+/// order `WindowParams::apply` used to produce in Rust.
177+pub async fn list_windowed(
178+ db: &Database,
179+ starts_after: Option<i64>,
180+ ends_after: Option<i64>,
181+ starts_before: Option<i64>,
182+ ends_before: Option<i64>,
183+ limit: Option<i64>,
184+ offset: i64,
185+) -> Result<(Vec<Event>, i64), AppError> {
186+ // Conditions and binds move together: each bound appends its predicate
187+ // with the placeholder number its bind position lands on.
188+ let mut conds: Vec<String> = Vec::new();
189+ let mut bounds: Vec<i64> = Vec::new();
190+ let mut bound = |column: &str, op: &str, value: Option<i64>| {
191+ if let Some(value) = value {
192+ conds.push(format!("{column} {op} ${}", bounds.len() + 1));
193+ bounds.push(value);
194+ }
195+ };
196+ bound("starts_at", ">", starts_after);
197+ bound("starts_at", "<", starts_before);
198+ bound("COALESCE(ends_at, starts_at)", ">", ends_after);
199+ bound("COALESCE(ends_at, starts_at)", "<", ends_before);
200+ let windowed = !conds.is_empty();
201+ let from_where = if windowed {
202+ format!("event WHERE {}", conds.join(" AND "))
203+ } else {
204+ "event".to_owned()
205+ };
206+ let order = if windowed {
207+ "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC"
208+ } else {
209+ "ORDER BY id DESC"
210+ };
211+ let mut list = PagedList::new(from_where, order);
212+ for value in bounds {
213+ list = list.bind(value);
214+ }
215+ list.run::<Event>(limit, offset, db).await
182216 }
183217
184218 /// Request-scoped: the handler reads the event, then awaits the clock and a
@@ -418,4 +452,120 @@ mod tests {
418452 );
419453 }
420454 }
455+
456+ /// Four schedule shapes; creation order is id order (uuidv7), so the
457+ /// unfiltered read is exactly the reverse of the creation order.
458+ async fn four_events(db: &Database) -> (UserId, [EventId; 4]) {
459+ let creator = a_person(db, "event-window").await;
460+ let school = EventAudience {
461+ kind: EventAudienceKind::School,
462+ role: None,
463+ course: None,
464+ class: None,
465+ capacity: None,
466+ };
467+ let now = Timestamp::now().as_millis();
468+ let past = Timestamp::from_millis(now - 60_000);
469+ let soon = Timestamp::from_millis(now + 30 * 60_000);
470+ let future = Timestamp::from_millis(now + 3_600_000);
471+ let later = Timestamp::from_millis(now + 2 * 3_600_000);
472+ let mut ids = Vec::new();
473+ for (starts_at, ends_at) in [
474+ (None, None), // timeless — never survives a window
475+ (Some(past), None), // already started
476+ (Some(soon), None), // ends-only deadline... starts soon
477+ (Some(future), Some(later)), // fully scheduled ahead
478+ ] {
479+ ids.push(
480+ create(
481+ db,
482+ &creator,
483+ EventTitle::try_new("window").unwrap(),
484+ EventDescription::try_new("").unwrap(),
485+ school.clone(),
486+ starts_at,
487+ ends_at,
488+ )
489+ .await
490+ .unwrap()
491+ .get_id()
492+ .clone(),
493+ );
494+ }
495+ (creator, ids.try_into().unwrap())
496+ }
497+
498+ #[tokio::test]
499+ async fn absent_window_is_the_unfiltered_newest_first_read() {
500+ let (db, _leases) = crate::database::init_test_db().await;
501+ let (_, ids) = four_events(&db).await;
502+ let (events, total) = list_windowed(&db, None, None, None, None, None, 0)
503+ .await
504+ .unwrap();
505+ assert_eq!(total, 4);
506+ let listed: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
507+ let expected: Vec<_> = ids.iter().rev().cloned().collect();
508+ assert_eq!(listed, expected);
509+ }
510+
511+ #[tokio::test]
512+ async fn the_window_filters_and_orders_in_sql_with_a_filtered_total() {
513+ let (db, _leases) = crate::database::init_test_db().await;
514+ let (_, ids) = four_events(&db).await;
515+ let [_, started, soon, ahead] = &ids;
516+ let now = Timestamp::now().as_millis();
517+
518+ // ends_after: the timeless and the already-started drop; the ends-only
519+ // event survives on its `ends_at` COALESCE fallback.
520+ let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 0)
521+ .await
522+ .unwrap();
523+ assert_eq!(total, 2);
524+ let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
525+ assert_eq!(keys, vec![soon.clone(), ahead.clone()]);
526+
527+ // A limit applies after the filter: one row out, total still two.
528+ let (events, total) = list_windowed(&db, None, Some(now), None, None, Some(1), 0)
529+ .await
530+ .unwrap();
531+ assert_eq!((events.len(), total), (1, 2));
532+ assert_eq!(events[0].get_id(), soon);
533+ // Offset runs inside the filtered set, not past it.
534+ let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 1)
535+ .await
536+ .unwrap();
537+ assert_eq!((events.len(), total), (1, 2));
538+ assert_eq!(events[0].get_id(), ahead);
539+
540+ // starts_before drops the start-less rows and everything starting at
541+ // or after the cut (strict): the cut sits between `soon` (+30 min)
542+ // and `ahead` (+1 h), so `started` and `soon` survive, schedule
543+ // ascending.
544+ let (events, total) = list_windowed(
545+ &db,
546+ None,
547+ None,
548+ Some(now + 45 * 60_000),
549+ None,
550+ None,
551+ 0,
552+ )
553+ .await
554+ .unwrap();
555+ assert_eq!(total, 2);
556+ let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
557+ assert_eq!(keys, vec![started.clone(), soon.clone()]);
558+
559+ // ends_before: only the already-started, on its starts_at fallback.
560+ let (_, total) = list_windowed(&db, None, None, None, Some(now - 30_000), None, 0)
561+ .await
562+ .unwrap();
563+ assert_eq!(total, 1);
564+
565+ // A well-formed instant naming no row is an empty page, not an error.
566+ let (events, total) = list_windowed(&db, Some(now + 30 * 86_400_000), None, None, None, None, 0)
567+ .await
568+ .unwrap();
569+ assert!((events.is_empty()) && total == 0);
570+ }
421571 }
src/db/exam.rsmodified+93 -19
@@ -5,6 +5,7 @@
55 use sqlx::PgConnection;
66
77 use crate::database::{Database, foreign_key_violation, tx_with_retry};
8+use crate::db::page::{PagedList, Param};
89 use crate::domain::class_course::ClassCourseId;
910 use crate::domain::course::CourseId;
1011 use crate::domain::exam::{
@@ -205,24 +206,96 @@ pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError>
205206 .await?)
206207 }
207208
208-/// The exams, newest first — `ORDER BY id` on a UUIDv7 column is creation
209-/// order, the sort the old record ids gave for free.
210-pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
211- Ok(sqlx::query_as!(
212- Exam,
213- r#"SELECT id AS "id: ExamId", creator AS "creator: UserId",
214- class_course AS "class_course: ClassCourseId", term AS "term: TermId",
215- title AS "title: ExamTitle", description AS "description: ExamDescription",
216- kind AS "kind: ExamKind", mode AS "mode: ExamMode",
217- starts_at AS "starts_at: Timestamp",
218- ends_at AS "ends_at: Timestamp",
219- duration_ms AS "duration_ms: ExamDuration",
220- max_attempts AS "max_attempts: ExamAttemptLimit",
221- allow_rejoin, allow_review, draft
222- FROM exam ORDER BY id DESC"#,
223- )
224- .fetch_all(db)
225- .await?)
209+/// The exams list behind `GET /exams`, paged by the database — visibility,
210+/// the draft rule, the schedule window, the `LIMIT/OFFSET` and the `total`
211+/// count all share one `WHERE` per branch, so a filtered page never decodes
212+/// the exams it skips.
213+///
214+/// `visible`/`managed` are the non-manager read: the exams addressed to any
215+/// of `visible` (through `exam_audience`, deduplicated — a shared exam is one
216+/// exam), with `NOT draft OR owner ∈ managed`, today's rule unchanged — a
217+/// draft shows only to someone who manages its owner instance. Both `None` is
218+/// the manager+ whole-table read.
219+///
220+/// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule
221+/// window, validated upstream. All four absent keeps `id DESC` (newest
222+/// first); any bound set drops window-less exams (no `mode` → both schedule
223+/// columns null, so every predicate is `NULL`-rejecting) and flips the order
224+/// to ascending by schedule — `starts_at`, falling back to `ends_at`, ties by
225+/// id — the order `WindowParams::apply` used to produce in Rust.
226+pub async fn list_windowed(
227+ db: &Database,
228+ visible: Option<&[ClassCourseId]>,
229+ managed: Option<&[ClassCourseId]>,
230+ starts_after: Option<i64>,
231+ ends_after: Option<i64>,
232+ starts_before: Option<i64>,
233+ ends_before: Option<i64>,
234+ limit: Option<i64>,
235+ offset: i64,
236+) -> Result<(Vec<Exam>, i64), AppError> {
237+ // Window predicates and binds move together: each bound appends its
238+ // predicate with the placeholder number its bind position lands on. The
239+ // two visibility binds of the non-manager branch claim $1 and $2, so the
240+ // window numbering continues after them.
241+ let base = usize::from(visible.is_some()) * 2;
242+ let mut conds: Vec<String> = Vec::new();
243+ let mut bounds: Vec<i64> = Vec::new();
244+ let mut bound = |column: &str, op: &str, value: Option<i64>| {
245+ if let Some(value) = value {
246+ conds.push(format!("{column} {op} ${}", base + bounds.len() + 1));
247+ bounds.push(value);
248+ }
249+ };
250+ bound("starts_at", ">", starts_after);
251+ bound("starts_at", "<", starts_before);
252+ bound("COALESCE(ends_at, starts_at)", ">", ends_after);
253+ bound("COALESCE(ends_at, starts_at)", "<", ends_before);
254+ let window = if conds.is_empty() {
255+ String::new()
256+ } else {
257+ format!(" AND {}", conds.join(" AND "))
258+ };
259+ let (from_where, mut binds): (String, Vec<Param>) = match visible {
260+ None => (
261+ if conds.is_empty() {
262+ "exam".to_owned()
263+ } else {
264+ format!("exam WHERE {}", conds.join(" AND "))
265+ },
266+ Vec::new(),
267+ ),
268+ Some(visible) => {
269+ let managed = managed.expect("visible and managed travel together");
270+ (
271+ format!(
272+ "(SELECT DISTINCT ON (e.id) e.* \
273+ FROM exam e \
274+ JOIN exam_audience a ON a.exam = e.id \
275+ WHERE a.class_course = ANY($1::uuid[]) \
276+ AND (NOT e.draft OR e.class_course = ANY($2::uuid[])){window} \
277+ ORDER BY e.id)"
278+ ),
279+ vec![
280+ Param::Texts(visible.iter().map(ClassCourseId::key).collect()),
281+ Param::Texts(managed.iter().map(ClassCourseId::key).collect()),
282+ ],
283+ )
284+ }
285+ };
286+ let order = if conds.is_empty() {
287+ "ORDER BY id DESC"
288+ } else {
289+ "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC"
290+ };
291+ let mut list = PagedList::new(from_where, order);
292+ for bind in binds.drain(..) {
293+ list = list.bind(bind);
294+ }
295+ for value in bounds {
296+ list = list.bind(value);
297+ }
298+ list.run::<Exam>(limit, offset, db).await
226299 }
227300
228301 /// The exams of one instance, newest first.
@@ -737,7 +810,8 @@ mod tests {
737810 /// route funnels through `class_course_of`, which answers
738811 /// `Internal("exam references a missing course")`, so an orphan **500s
739812 /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
740- /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`.
813+ /// [`crate::db::exam::list_windowed`] still hands it to every manager+ on
814+ /// `GET /exams`.
741815 ///
742816 /// [`create`] therefore *writes* the course row rather than reading
743817 /// it ([`cap::touch_and_create`]); the harness and the window it races in
src/db/homework.rsmodified+254 -39
@@ -13,6 +13,8 @@ use crate::domain::user::UserId;
1313 use crate::error::{AppError, ValidationError};
1414 use sqlx::PgConnection;
1515
16+use crate::db::page::{PagedList, Param};
17+
1618 /// The answer a link to a subject that is not there gets, on create and on
1719 /// re-tag alike — the conditional claim on the subject row matches nothing,
1820 /// 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(
199201 .await?)
200202 }
201203
204+/// The homework table as `SELECT *` cannot read it: the assigned-student
205+/// roster is not a column but the `homework_assignment` junction, aggregated
206+/// per row. Every runtime ([`PagedList`]) read of homework selects through
207+/// this derived table, so its rows decode exactly like the `query_as!` reads
208+/// beside them; the alias names the row set the outer WHERE filters.
209+const HOMEWORK_WITH_ASSIGNED: &str = "(SELECT h.*, \
210+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a \
211+ WHERE a.homework = h.id) AS assigned \
212+ FROM homework h) AS homework";
213+
202214 /// Every homework in the system, newest first — the manager+ view of the
203-/// cross-course "my homework" list.
204-pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
205- Ok(sqlx::query_as!(
206- Homework,
207- r#"SELECT id AS "id: HomeworkId",
208- class_course AS "class_course: ClassCourseId",
209- subject AS "subject: SubjectId",
210- title AS "title: HomeworkTitle",
211- description AS "description: HomeworkDescription",
212- due_at AS "due_at: Timestamp",
213- (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
214- WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
215- created_by AS "created_by: UserId",
216- created_at AS "created_at: Timestamp"
217- FROM homework ORDER BY id DESC"#,
218- )
219- .fetch_all(db)
220- .await?)
215+/// cross-course "my homework" list, narrowed by the optional due window and
216+/// instance scope before anything leaves the database, so a manager asking
217+/// for open homework never loads the school's whole history. Paged in SQL:
218+/// a manager retains nothing in Rust, so the window and the count are the
219+/// database's to do.
220+pub async fn list_all(
221+ db: &Database,
222+ due_after: Option<i64>,
223+ due_before: Option<i64>,
224+ class_course: Option<&ClassCourseId>,
225+ limit: Option<i64>,
226+ offset: i64,
227+) -> Result<(Vec<Homework>, i64), AppError> {
228+ let mut from_where = HOMEWORK_WITH_ASSIGNED.to_string();
229+ let mut next = 1;
230+ let mut conds: Vec<String> = Vec::new();
231+ if due_after.is_some() {
232+ conds.push(format!("due_at >= ${next}"));
233+ next += 1;
234+ }
235+ if due_before.is_some() {
236+ conds.push(format!("due_at < ${next}"));
237+ next += 1;
238+ }
239+ if class_course.is_some() {
240+ conds.push(format!("class_course = ${next}"));
241+ }
242+ if !conds.is_empty() {
243+ from_where.push_str(" WHERE ");
244+ from_where.push_str(&conds.join(" AND "));
245+ }
246+ let mut list = PagedList::new(from_where, "ORDER BY id DESC");
247+ if let Some(after) = due_after {
248+ list = list.bind(after);
249+ }
250+ if let Some(before) = due_before {
251+ list = list.bind(before);
252+ }
253+ if let Some(course) = class_course {
254+ list = list.bind(course.uuid());
255+ }
256+ list.run::<Homework>(limit, offset, db).await
221257 }
222258
223259 /// Every homework of every instance in `instances`, newest first (one
224-/// query) — the cross-instance list over a caller's visible courses. The web
225-/// layer still trims each instance's rows to what the caller may see (a
226-/// student to the ones they `student_sees`).
260+/// query) — the cross-instance list over a caller's visible courses, with
261+/// the same optional due-window and instance narrowing as the manager view.
262+/// Unbounded by design: the web layer still trims each instance's rows to
263+/// what the caller may see (a student to the ones they `student_sees`), and
264+/// a window here could only hide rows that trim was about to keep.
227265 pub async fn list_for_class_courses(
228266 db: &Database,
229267 instances: &[ClassCourseId],
268+ due_after: Option<i64>,
269+ due_before: Option<i64>,
270+ class_course: Option<&ClassCourseId>,
230271 ) -> Result<Vec<Homework>, AppError> {
231272 if instances.is_empty() {
232273 return Ok(Vec::new());
233274 }
234- let ids: Vec<uuid::Uuid> = instances.iter().map(ClassCourseId::uuid).collect();
235- Ok(sqlx::query_as!(
236- Homework,
237- r#"SELECT id AS "id: HomeworkId",
238- class_course AS "class_course: ClassCourseId",
239- subject AS "subject: SubjectId",
240- title AS "title: HomeworkTitle",
241- description AS "description: HomeworkDescription",
242- due_at AS "due_at: Timestamp",
243- (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
244- WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
245- created_by AS "created_by: UserId",
246- created_at AS "created_at: Timestamp"
247- FROM homework WHERE class_course = ANY($1) ORDER BY id DESC"#,
248- &ids
249- )
250- .fetch_all(db)
251- .await?)
275+ // The instance set rides as TEXT: `Param` (the closed bind enum of
276+ // db::page) has no uuid-array arm, and `uuid::text` is the canonical
277+ // lowercase spelling both sides of the comparison agree on.
278+ let scope: Vec<String> = instances.iter().map(|id| id.uuid().to_string()).collect();
279+ let mut conds: Vec<String> = vec![String::from("class_course::text = ANY($1)")];
280+ let mut next = 2;
281+ if due_after.is_some() {
282+ conds.push(format!("due_at >= ${next}"));
283+ next += 1;
284+ }
285+ if due_before.is_some() {
286+ conds.push(format!("due_at < ${next}"));
287+ next += 1;
288+ }
289+ if class_course.is_some() {
290+ conds.push(format!("class_course = ${next}"));
291+ }
292+ let from_where = format!(
293+ "{} WHERE {}",
294+ HOMEWORK_WITH_ASSIGNED,
295+ conds.join(" AND ")
296+ );
297+ let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(Param::Texts(scope));
298+ if let Some(after) = due_after {
299+ list = list.bind(after);
300+ }
301+ if let Some(before) = due_before {
302+ list = list.bind(before);
303+ }
304+ if let Some(course) = class_course {
305+ list = list.bind(course.uuid());
306+ }
307+ // No window: the rows in hand are the whole filtered read, which the
308+ // caller retains and pages in the web layer.
309+ let (rows, _) = list.run::<Homework>(None, 0, db).await?;
310+ Ok(rows)
252311 }
253312
254313 /// The homework of one instance that `user` is meant to see — whole-class
@@ -932,4 +991,160 @@ mod tests {
932991 "whole-instance reaches the never-named student"
933992 );
934993 }
994+
995+ /// A real teacher row — `created_by` is a foreign key.
996+ async fn a_teacher(db: &Database) -> UserId {
997+ let teacher = UserId::generate();
998+ sqlx::query(
999+ "INSERT INTO app_user (id, username, created_at, role) \
1000+ VALUES ($1, $2, 0, 'teacher')",
1001+ )
1002+ .bind(teacher.uuid())
1003+ .bind(format!("homework-filter-{}", &teacher.key()[30..]))
1004+ .execute(db)
1005+ .await
1006+ .unwrap();
1007+ teacher
1008+ }
1009+
1010+ /// One homework with a chosen due instant on `instance`.
1011+ async fn homework_due(
1012+ db: &Database,
1013+ instance: &ClassCourseId,
1014+ subject: &SubjectId,
1015+ due_at: i64,
1016+ title: &str,
1017+ ) -> Homework {
1018+ create(
1019+ db,
1020+ instance,
1021+ subject,
1022+ HomeworkTitle::try_new(title).unwrap(),
1023+ None,
1024+ Timestamp::from_millis(due_at),
1025+ None,
1026+ &a_teacher(db).await,
1027+ )
1028+ .await
1029+ .unwrap()
1030+ }
1031+
1032+ /// The SQL predicates the cross-instance lists gained: the due window and
1033+ /// the instance scope both run in the WHERE, and (for the manager path)
1034+ /// the page window sits after them, with the count over the same clause.
1035+ #[tokio::test]
1036+ async fn list_all_filters_by_due_window_and_instance_in_sql() {
1037+ let (db, _leases) = crate::database::init_test_db().await;
1038+ let (here, _) = crate::db::course::a_test_instance(&db).await;
1039+ let (there, course2) = crate::db::course::a_test_instance(&db).await;
1040+ let subject = a_subject("matematik", &db).await;
1041+ let subject2 = crate::db::subject::create(
1042+ &db,
1043+ &course2,
1044+ SubjectName::try_new("fizik").unwrap(),
1045+ SubjectDescription::try_new("").unwrap(),
1046+ )
1047+ .await
1048+ .unwrap();
1049+ let now = Timestamp::now().as_millis();
1050+ let day = 86_400_000_i64;
1051+ let past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await;
1052+ let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await;
1053+ let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await;
1054+
1055+ // The open tab: due at or after the bound.
1056+ let (rows, total) = list_all(&db, Some(now), None, None, None, 0)
1057+ .await
1058+ .unwrap();
1059+ assert_eq!(total, 2);
1060+ assert_eq!(
1061+ rows.iter().map(Homework::get_id).collect::<Vec<_>>(),
1062+ vec![other.get_id(), open.get_id()],
1063+ "newest first, past rows left out"
1064+ );
1065+ // The past tab: due strictly before the bound — the bounds share no
1066+ // instant and leave no gap.
1067+ let (rows, total) = list_all(&db, None, Some(now), None, None, 0)
1068+ .await
1069+ .unwrap();
1070+ assert_eq!(total, 1);
1071+ assert_eq!(rows[0].get_id(), past.get_id());
1072+ // The instance scope: the other instance's rows stay behind.
1073+ let (rows, total) = list_all(&db, None, None, Some(&there), None, 0)
1074+ .await
1075+ .unwrap();
1076+ assert_eq!(total, 1);
1077+ assert_eq!(rows[0].get_id(), other.get_id());
1078+ // A well-formed id that names no row is an empty page, not an error.
1079+ let (rows, total) = list_all(&db, None, None, Some(&ClassCourseId::generate()), None, 0)
1080+ .await
1081+ .unwrap();
1082+ assert_eq!((rows.len(), total), (0, 0));
1083+ // The page window applies after the filter, and the count stays the
1084+ // filtered length, not the page size.
1085+ let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 0)
1086+ .await
1087+ .unwrap();
1088+ assert_eq!((rows.len(), total), (1, 2));
1089+ let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 1)
1090+ .await
1091+ .unwrap();
1092+ assert_eq!((rows.len(), total), (1, 2));
1093+ assert_eq!(rows[0].get_id(), open.get_id());
1094+ // Absent params: every row, unchanged.
1095+ let (_, total) = list_all(&db, None, None, None, None, 0).await.unwrap();
1096+ assert_eq!(total, 3);
1097+ }
1098+
1099+ /// The per-instance path: the caller's instances scope the read in SQL,
1100+ /// and the due window and single-instance filter apply on top of it.
1101+ #[tokio::test]
1102+ async fn list_for_class_courses_applies_the_same_predicates() {
1103+ let (db, _leases) = crate::database::init_test_db().await;
1104+ let (here, _) = crate::db::course::a_test_instance(&db).await;
1105+ let (there, course2) = crate::db::course::a_test_instance(&db).await;
1106+ let subject = a_subject("matematik", &db).await;
1107+ let subject2 = crate::db::subject::create(
1108+ &db,
1109+ &course2,
1110+ SubjectName::try_new("fizik").unwrap(),
1111+ SubjectDescription::try_new("").unwrap(),
1112+ )
1113+ .await
1114+ .unwrap();
1115+ let now = Timestamp::now().as_millis();
1116+ let day = 86_400_000_i64;
1117+ let _past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await;
1118+ let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await;
1119+ let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await;
1120+ let both = vec![here.clone(), there.clone()];
1121+
1122+ let rows = list_for_class_courses(&db, &both, Some(now), None, None)
1123+ .await
1124+ .unwrap();
1125+ assert_eq!(
1126+ rows.iter().map(Homework::get_id).collect::<Vec<_>>(),
1127+ vec![other.get_id(), open.get_id()]
1128+ );
1129+ let rows = list_for_class_courses(&db, &both, None, Some(now), None)
1130+ .await
1131+ .unwrap();
1132+ assert_eq!(rows.len(), 1, "the past tab keeps only the past row");
1133+ // A filter naming an instance outside the caller's visible set matches
1134+ // nothing — the scopes intersect, they do not override each other.
1135+ let rows = list_for_class_courses(&db, &both, None, None, Some(&here))
1136+ .await
1137+ .unwrap();
1138+ assert_eq!(rows.len(), 2, "both here rows, past and open");
1139+ let stranger = ClassCourseId::generate();
1140+ let rows = list_for_class_courses(&db, &both, None, None, Some(&stranger))
1141+ .await
1142+ .unwrap();
1143+ assert!(rows.is_empty(), "an unknown instance names no row");
1144+ // Absent filters: the whole visible read, unchanged.
1145+ let rows = list_for_class_courses(&db, &both, None, None, None)
1146+ .await
1147+ .unwrap();
1148+ assert_eq!(rows.len(), 3);
1149+ }
9351150 }
src/db/menu.rsmodified+11 -2
@@ -135,21 +135,30 @@ pub async fn find(
135135
136136 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
137137 /// either may be omitted (`NULL` bound). The comparison is lexical, which
138-/// is chronological for this format.
138+/// is chronological for this format. `slot`, when given, keeps only menus
139+/// published under that exact snapshotted slot text — deliberately not
140+/// checked against the school's current `meal_slots`, so a retired slot
141+/// still finds its menus and an unknown name matches nothing.
139142 pub async fn list(
140143 db: &Database,
141144 from: Option<&MenuDate>,
142145 to: Option<&MenuDate>,
146+ slot: Option<&str>,
143147 limit: Option<i64>,
144148 offset: i64,
145149 ) -> Result<(Vec<Menu>, i64), AppError> {
150+ // One WHERE for the page and the count alike: a slot filter moves
151+ // `total` with the items, so page numbers count the rows actually
152+ // returned.
146153 PagedList::new(
147154 "menu WHERE ($1::text IS NULL OR date >= $1::text) \
148- AND ($2::text IS NULL OR date <= $2::text)",
155+ AND ($2::text IS NULL OR date <= $2::text) \
156+ AND ($3::text IS NULL OR slot = $3::text)",
149157 "ORDER BY date DESC, slot ASC, id DESC",
150158 )
151159 .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
152160 .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
161+ .bind(Param::OptText(slot.map(|slot| slot.to_string())))
153162 .run(limit, offset, db)
154163 .await
155164 }
src/db/message.rsmodified+187 -4
@@ -8,6 +8,7 @@ use crate::db::page::{PagedList, Param};
88 use crate::domain::message::{
99 Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
1010 };
11+use crate::domain::text_fold::{search_fold, search_fold_sql};
1112 use crate::domain::timestamp::Timestamp;
1213 use crate::domain::user::UserId;
1314 use crate::error::AppError;
@@ -55,14 +56,21 @@ pub async fn send(
5556 /// dynamic string assembled, minus the interpolation. They ride the
5657 /// [`PagedList`] builder (the paged-list exemption), so the page and its
5758 /// count always see the same predicate.
59+///
60+/// `q` is an optional free-text needle over subject and body, folded
61+/// case- and diacritic-insensitively on both sides ([`search_fold`] /
62+/// [`search_fold_sql`]); a blank needle searches nothing.
5863 pub async fn list_folder(
5964 db: &Database,
6065 user: &UserId,
6166 folder: Folder,
6267 read: Option<bool>,
68+ q: Option<&str>,
6369 limit: Option<i64>,
6470 offset: i64,
6571 ) -> Result<(Vec<Message>, i64), AppError> {
72+ // A blank needle searches nothing, exactly like an absent one.
73+ let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
6674 let home_arm = folder == Folder::Inbox;
6775 let mut from = match folder {
6876 Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(),
@@ -76,8 +84,20 @@ pub async fn list_folder(
7684 };
7785 // The `read` filter binds after whichever placeholders the folder shape
7886 // spent (`$1` is always the user; the home-folder arm spends `$2`).
87+ let mut next = if home_arm { 3 } else { 2 };
7988 if read.is_some() {
80- from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 }));
89+ from.push_str(&format!(" AND read = ${next}"));
90+ next += 1;
91+ }
92+ // The needle rides the same fold on both sides (`position`, not `LIKE`,
93+ // keeps `%` and `_` literal). Subject or body — this query joins no
94+ // counterparty, so names are not searched.
95+ if needle.is_some() {
96+ from.push_str(&format!(
97+ " AND (position(${next} in {}) > 0 OR position(${next} in {}) > 0)",
98+ search_fold_sql("subject"),
99+ search_fold_sql("body"),
100+ ));
81101 }
82102 let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user.uuid());
83103 if home_arm {
@@ -86,6 +106,9 @@ pub async fn list_folder(
86106 if let Some(read) = read {
87107 builder = builder.bind(Param::Bool(read));
88108 }
109+ if let Some(needle) = needle {
110+ builder = builder.bind(needle);
111+ }
89112 builder.run(limit, offset, db).await
90113 }
91114
@@ -280,9 +303,10 @@ mod tests {
280303 sent.push(message.get_id().key().to_string());
281304 }
282305
283- let (listed, total) = list_folder(&db, &recipient, Folder::Inbox, None, None, 0)
284- .await
285- .unwrap();
306+ let (listed, total) =
307+ list_folder(&db, &recipient, Folder::Inbox, None, None, None, 0)
308+ .await
309+ .unwrap();
286310 assert_eq!(total, 25);
287311 sent.reverse();
288312 let read_back: Vec<String> = listed
@@ -291,4 +315,163 @@ mod tests {
291315 .collect();
292316 assert_eq!(read_back, sent);
293317 }
318+
319+ /// `q` folds case and Turkish diacritics on both sides, matches subject
320+ /// or body, composes with `read`, and pages after the filter (`total`
321+ /// counts matches, not rows). The folder predicate still scopes the
322+ /// search: a stranger's folders stay empty no matter what the needle
323+ /// matches in someone else's mail.
324+ #[tokio::test]
325+ async fn q_searches_subject_and_body_and_composes_with_read() {
326+ let (db, _leases) = crate::database::init_test_db().await;
327+ let sender = crate::db::class_member::tests::fixture_user(&db, "q-gonderen").await;
328+ let recipient = crate::db::class_member::tests::fixture_user(&db, "q-alici").await;
329+ let stranger = crate::db::class_member::tests::fixture_user(&db, "q-yabanci").await;
330+
331+ let subject_hit = send(
332+ &db,
333+ &sender,
334+ &recipient,
335+ MessageSubject::try_new("Matematik Etüt").unwrap(),
336+ MessageBody::try_new("saat üçte").unwrap(),
337+ None,
338+ )
339+ .await
340+ .unwrap();
341+ let body_hit = send(
342+ &db,
343+ &sender,
344+ &recipient,
345+ MessageSubject::try_new("duyuru").unwrap(),
346+ MessageBody::try_new("İSTANBUL gezisi etüt sonrası").unwrap(),
347+ None,
348+ )
349+ .await
350+ .unwrap();
351+ send(
352+ &db,
353+ &sender,
354+ &recipient,
355+ MessageSubject::try_new("toplantı").unwrap(),
356+ MessageBody::try_new("alakasız").unwrap(),
357+ None,
358+ )
359+ .await
360+ .unwrap();
361+ let subject_key = subject_hit.get_id().key().to_string();
362+ let body_key = body_hit.get_id().key().to_string();
363+
364+ // Absent and blank needles both see the whole folder.
365+ let (_, total) =
366+ list_folder(&db, &recipient, Folder::Inbox, None, None, None, 0)
367+ .await
368+ .unwrap();
369+ assert_eq!(total, 3);
370+ let (_, total) =
371+ list_folder(&db, &recipient, Folder::Inbox, None, Some(" "), None, 0)
372+ .await
373+ .unwrap();
374+ assert_eq!(total, 3);
375+
376+ // Subject hit through the fold: `etut` finds `Etüt`.
377+ let (hits, total) =
378+ list_folder(&db, &recipient, Folder::Inbox, None, Some("etut"), None, 0)
379+ .await
380+ .unwrap();
381+ assert_eq!(total, 2);
382+ let keys: Vec<String> = hits
383+ .iter()
384+ .map(|message| message.get_id().key().to_string())
385+ .collect();
386+ assert!(keys.contains(&subject_key));
387+ assert!(keys.contains(&body_key));
388+
389+ // Body hit, case-insensitive in both directions.
390+ let (hits, total) = list_folder(
391+ &db,
392+ &recipient,
393+ Folder::Inbox,
394+ None,
395+ Some("İsTaNbUl"),
396+ None,
397+ 0,
398+ )
399+ .await
400+ .unwrap();
401+ assert_eq!(total, 1);
402+ assert_eq!(hits[0].get_id().key().to_string(), body_key);
403+
404+ // A needle matching nothing: an empty page, not an error.
405+ let (hits, total) = list_folder(
406+ &db,
407+ &recipient,
408+ Folder::Inbox,
409+ None,
410+ Some("yok boyle bir sey"),
411+ None,
412+ 0,
413+ )
414+ .await
415+ .unwrap();
416+ assert_eq!(total, 0);
417+ assert!(hits.is_empty());
418+
419+ // The window runs after the filter: `total` counts matches.
420+ let (hits, total) = list_folder(
421+ &db,
422+ &recipient,
423+ Folder::Inbox,
424+ None,
425+ Some("etut"),
426+ Some(1),
427+ 0,
428+ )
429+ .await
430+ .unwrap();
431+ assert_eq!(total, 2);
432+ assert_eq!(hits.len(), 1);
433+
434+ // Composes with `read`: one match read, the other not.
435+ set_read(&db, subject_hit, true).await.unwrap();
436+ let (_, total) = list_folder(
437+ &db,
438+ &recipient,
439+ Folder::Inbox,
440+ Some(true),
441+ Some("etut"),
442+ None,
443+ 0,
444+ )
445+ .await
446+ .unwrap();
447+ assert_eq!(total, 1);
448+ let (hits, total) = list_folder(
449+ &db,
450+ &recipient,
451+ Folder::Inbox,
452+ Some(false),
453+ Some("etut"),
454+ None,
455+ 0,
456+ )
457+ .await
458+ .unwrap();
459+ assert_eq!(total, 1);
460+ assert_eq!(hits[0].get_id().key().to_string(), body_key);
461+
462+ // The folder predicate still scopes the search: the stranger's own
463+ // folders are empty even though the needle matches other users' mail.
464+ let (hits, total) =
465+ list_folder(&db, &stranger, Folder::Inbox, None, Some("etut"), None, 0)
466+ .await
467+ .unwrap();
468+ assert_eq!(total, 0);
469+ assert!(hits.is_empty());
470+ let (hits, total) =
471+ list_folder(&db, &stranger, Folder::Sent, None, Some("etut"), None, 0)
472+ .await
473+ .unwrap();
474+ assert_eq!(total, 0);
475+ assert!(hits.is_empty());
476+ }
294477 }
src/db/pomodoro.rsmodified+219 -24
@@ -5,11 +5,14 @@
55
66 use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS};
77 use crate::database::{Database, tx_with_retry};
8+use crate::db::page::{Param, PagedList};
89 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
910 use crate::domain::timestamp::Timestamp;
1011 use crate::domain::user::UserId;
1112 use crate::error::AppError;
13+use sqlx::postgres::PgArguments;
1214 use sqlx::query_as;
15+use sqlx::AssertSqlSafe;
1316
1417 /// Start a session for `user`, stamped with the server clock. The open slot
1518 /// 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<PomodoroSession, App
215218 Ok(saved)
216219 }
217220
218-/// Every session of `user`, newest first — the running one (if any)
219-/// included. Ordered by `started_at`, never by id alone: the log is a
220-/// chronology, and the id tie-break only ever separates two *finished*
221-/// stints sharing a `started_at` — there is one running row per user, so it
222-/// can never tie with itself.
223-pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {
224- let sessions = query_as!(
225- PomodoroSession,
226- "SELECT id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
227- started_at AS \"started_at: Timestamp\", \
228- finished_at AS \"finished_at: Timestamp\", counted, label \
229- FROM pomodoro_session WHERE app_user = $1 \
230- ORDER BY started_at DESC, id DESC",
231- user.uuid()
232- )
233- .fetch_all(db)
234- .await?;
235- Ok(sessions)
221+/// One read of the log: the page's rows, the filtered session count, and the
222+/// filtered focus total — three answers over one `WHERE`, so they can never
223+/// disagree.
224+pub(crate) struct PomodoroLogPage {
225+ pub(crate) items: Vec<PomodoroSession>,
226+ /// Sessions in the filtered set, before the page window is applied.
227+ pub(crate) total: i64,
228+ /// `SUM(finished_at - started_at)` over the filtered set, unpaged.
229+ pub(crate) total_focus_ms: i64,
230+}
231+
232+/// The `FROM … WHERE` the page, the count, and the focus sum share, assembled
233+/// once per read. Placeholders are positional: `$1` is the user, and the
234+/// bounds follow in `from`, `to` order, present exactly when the arm names
235+/// them.
236+fn log_from_where(from: bool, to: bool) -> &'static str {
237+ match (from, to) {
238+ (true, true) => {
239+ "pomodoro_session WHERE app_user = $1 AND started_at >= $2 AND started_at < $3"
240+ }
241+ (true, false) => "pomodoro_session WHERE app_user = $1 AND started_at >= $2",
242+ (false, true) => "pomodoro_session WHERE app_user = $1 AND started_at < $2",
243+ (false, false) => "pomodoro_session WHERE app_user = $1",
244+ }
245+}
246+
247+/// A page of `user`'s log, newest first — the running session (if any)
248+/// included — with the half-open window `[from, to)` applied *before* both
249+/// the page window and the sums. Ordered by `started_at`, never by id alone:
250+/// the log is a chronology, and the id tie-break only ever separates two
251+/// *finished* stints sharing a `started_at` — there is one running row per
252+/// user, so it can never tie with itself.
253+///
254+/// With no bounds this is the whole-history read the unpaged `list` used to give.
255+/// With bounds, answering the page never materializes the log beyond
256+/// the page itself — the count and the focus total are database scalars over
257+/// the same `WHERE`.
258+pub(crate) async fn page_for_user(
259+ db: &Database,
260+ user: &UserId,
261+ from: Option<i64>,
262+ to: Option<i64>,
263+ limit: Option<i64>,
264+ offset: i64,
265+) -> Result<PomodoroLogPage, AppError> {
266+ let from_where = log_from_where(from.is_some(), to.is_some());
267+ let mut list = PagedList::new(from_where, "ORDER BY started_at DESC, id DESC").bind(user.uuid());
268+ if let Some(ms) = from {
269+ list = list.bind(ms);
270+ }
271+ if let Some(ms) = to {
272+ list = list.bind(ms);
273+ }
274+ let (items, total) = list.run(limit, offset, db).await?;
275+ let total_focus_ms = focus_total_ms(db, from_where, user, from, to).await?;
276+ Ok(PomodoroLogPage {
277+ items,
278+ total,
279+ total_focus_ms,
280+ })
281+}
282+
283+/// `SUM(finished_at - started_at)` over the same filtered set the page reads —
284+/// one SQL scalar, so the focus total never folds the log in Rust. A running
285+/// stint contributes nothing (its `finished_at` is `NULL` and `SUM` skips
286+/// `NULL`), and an empty set `COALESCE`s to zero. `SUM(bigint)` answers
287+/// `numeric`, hence the `::BIGINT` cast.
288+async fn focus_total_ms(
289+ db: &Database,
290+ from_where: &str,
291+ user: &UserId,
292+ from: Option<i64>,
293+ to: Option<i64>,
294+) -> Result<i64, AppError> {
295+ let sql = format!(
296+ "SELECT COALESCE(SUM(finished_at - started_at), 0)::BIGINT FROM {from_where}"
297+ );
298+ let mut args = PgArguments::default();
299+ Param::Uuid(user.uuid()).add_to(&mut args);
300+ if let Some(ms) = from {
301+ Param::I64(ms).add_to(&mut args);
302+ }
303+ if let Some(ms) = to {
304+ Param::I64(ms).add_to(&mut args);
305+ }
306+ Ok(sqlx::query_scalar_with(AssertSqlSafe(sql), args)
307+ .fetch_one(db)
308+ .await?)
236309 }
237310 #[cfg(test)]
238311 mod tests {
@@ -347,6 +420,33 @@ mod tests {
347420 finish(db, user).await.unwrap();
348421 }
349422
423+ /// Insert one closed stint at explicit unix-ms stamps — a row the
424+ /// windowed-log tests below can aim bounds at, no clock involved.
425+ /// `counted = NULL` (a pre-rule row) is the honest verdict for a stint no
426+ /// transaction judged.
427+ async fn seeded_stint(user: &UserId, db: &Database, started_at: i64, finished_at: i64) {
428+ sqlx::query(
429+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
430+ VALUES ($1, $2, $3, $4, NULL, NULL)",
431+ )
432+ .bind(PomodoroSessionId::generate().uuid())
433+ .bind(user.uuid())
434+ .bind(started_at)
435+ .bind(finished_at)
436+ .execute(db)
437+ .await
438+ .unwrap();
439+ }
440+
441+ /// The whole unwindowed log — the read the old `list_for_user` gave —
442+ /// for tests that just want the sessions.
443+ async fn whole_log<'a>(user: &UserId, db: &Database) -> Vec<PomodoroSession> {
444+ page_for_user(db, user, None, None, None, 0)
445+ .await
446+ .unwrap()
447+ .items
448+ }
449+
350450 #[tokio::test]
351451 async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
352452 let (db, _leases) = crate::database::init_test_db().await;
@@ -569,7 +669,7 @@ mod tests {
569669 // Not a study day either — and no streak column was even opened.
570670 assert_eq!(streak(&user, &db).await, (0, 0, -1));
571671 // But it happened, and the log says so.
572- let log = list_for_user(&db, &user).await.unwrap();
672+ let log = whole_log(&user, &db).await;
573673 assert_eq!(log.len(), 1);
574674 assert_eq!(log[0].get_finished_at(), short.get_finished_at());
575675
@@ -590,7 +690,7 @@ mod tests {
590690 )
591691 );
592692 assert_eq!(streak(&user, &db).await.0, 1);
593- assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 2);
693+ assert_eq!(whole_log(&user, &db).await.len(), 2);
594694 }
595695
596696 /// The day quota: it stops the counter, it never stops the log, and it
@@ -617,7 +717,7 @@ mod tests {
617717 }
618718 assert_eq!(counters(&user, &db).await, (finished, focus_ms));
619719 assert_eq!(
620- list_for_user(&db, &user).await.unwrap().len() as i64,
720+ whole_log(&user, &db).await.len() as i64,
621721 MAX_COUNTED_POMODORO_PER_DAY + 3
622722 );
623723 // The quota is a day's, not a lifetime's.
@@ -645,7 +745,7 @@ mod tests {
645745 assert_eq!(counters(&user, &db).await, (0, 0));
646746 assert_eq!(streak(&user, &db).await, (0, 0, -1));
647747 // Every one of them is still the student's own history.
648- assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 200);
748+ assert_eq!(whole_log(&user, &db).await.len(), 200);
649749 assert!(
650750 crate::db::badge::list_for(&db, &user)
651751 .await
@@ -679,7 +779,7 @@ mod tests {
679779 // A restart replaces the dangling session: still one row, fresh clock.
680780 let second = start(&db, &user, None).await.unwrap();
681781 assert!(second.get_started_at() >= first.get_started_at());
682- let sessions = list_for_user(&db, &user).await.unwrap();
782+ let sessions = whole_log(&user, &db).await;
683783 assert_eq!(sessions.len(), 1);
684784
685785 let closed = finish(&db, &user).await.unwrap();
@@ -691,7 +791,7 @@ mod tests {
691791 Err(AppError::Conflict(_))
692792 ));
693793 start(&db, &user, None).await.unwrap();
694- let sessions = list_for_user(&db, &user).await.unwrap();
794+ let sessions = whole_log(&user, &db).await;
695795 assert_eq!(sessions.len(), 2);
696796 }
697797
@@ -722,4 +822,99 @@ mod tests {
722822 assert_eq!(stats.get_pomodoro_sessions(), 1);
723823 assert_eq!(stats.get_pomodoro_focus_ms(), 0);
724824 }
825+
826+ /// A timeline the windowed reads aim at: three finished stints
827+ /// (5000 + 500 + 6000 ms of focus) and one still running, which the sums
828+ /// must never mistake for focus.
829+ async fn a_seeded_timeline(db: &Database) -> UserId {
830+ let user = a_user(db).await;
831+ seeded_stint(&user, db, 1000, 6000).await;
832+ seeded_stint(&user, db, 2000, 2500).await;
833+ seeded_stint(&user, db, 3000, 9000).await;
834+ sqlx::query(
835+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
836+ VALUES ($1, $2, 4000, NULL, NULL, NULL)",
837+ )
838+ .bind(PomodoroSessionId::generate().uuid())
839+ .bind(user.uuid())
840+ .execute(db)
841+ .await
842+ .unwrap();
843+ user
844+ }
845+
846+ fn starts(page: &PomodoroLogPage) -> Vec<i64> {
847+ page.items
848+ .iter()
849+ .map(|session| session.get_started_at().as_millis())
850+ .collect()
851+ }
852+
853+ #[tokio::test]
854+ async fn the_window_bounds_the_page_the_count_and_the_focus_total_alike() {
855+ let (db, _leases) = crate::database::init_test_db().await;
856+ let user = a_seeded_timeline(&db).await;
857+
858+ // No bounds: today's whole-history read — every session, newest
859+ // first, and the focus total over all of it (running adds nothing).
860+ let page = page_for_user(&db, &user, None, None, None, 0).await.unwrap();
861+ assert_eq!(page.total, 4);
862+ assert_eq!(starts(&page), [4000, 3000, 2000, 1000]);
863+ assert_eq!(page.total_focus_ms, 11_500);
864+
865+ // `from` only: half-open at the start, so the stint opening at 2500
866+ // itself is out and the ones from 3000 on are in.
867+ let page = page_for_user(&db, &user, Some(2500), None, None, 0)
868+ .await
869+ .unwrap();
870+ assert_eq!(page.total, 2);
871+ assert_eq!(starts(&page), [4000, 3000]);
872+ assert_eq!(page.total_focus_ms, 6_000);
873+
874+ // `to` only: exclusive, so the stint starting exactly at 2000 is out.
875+ let page = page_for_user(&db, &user, None, Some(2000), None, 0)
876+ .await
877+ .unwrap();
878+ assert_eq!(page.total, 1);
879+ assert_eq!(starts(&page), [1000]);
880+ assert_eq!(page.total_focus_ms, 5_000);
881+
882+ // Both bounds AND together.
883+ let page = page_for_user(&db, &user, Some(1000), Some(3000), None, 0)
884+ .await
885+ .unwrap();
886+ assert_eq!(page.total, 2);
887+ assert_eq!(starts(&page), [2000, 1000]);
888+ assert_eq!(page.total_focus_ms, 5_500);
889+
890+ // A window over empty ground answers an empty page, not an error.
891+ let page = page_for_user(&db, &user, Some(10_000), None, None, 0)
892+ .await
893+ .unwrap();
894+ assert!(page.items.is_empty());
895+ assert_eq!(page.total, 0);
896+ assert_eq!(page.total_focus_ms, 0);
897+ }
898+
899+ #[tokio::test]
900+ async fn the_page_window_slices_after_the_time_window() {
901+ let (db, _leases) = crate::database::init_test_db().await;
902+ let user = a_seeded_timeline(&db).await;
903+
904+ // limit slices the filtered set; `total` stays the filtered count and
905+ // the focus total the filtered sum — not the one listed row's.
906+ let page = page_for_user(&db, &user, Some(2500), None, Some(1), 0)
907+ .await
908+ .unwrap();
909+ assert_eq!(starts(&page), [4000]);
910+ assert_eq!(page.total, 2);
911+ assert_eq!(page.total_focus_ms, 6_000);
912+
913+ // offset paging lands inside the filtered order, and the unpaged sums
914+ // span the whole filtered log — 11_500, not the two listed rows' 11_000.
915+ let page = page_for_user(&db, &user, None, None, Some(2), 1).await.unwrap();
916+ assert_eq!(starts(&page), [3000, 2000]);
917+ assert_eq!(page.total, 4);
918+ assert_eq!(page.total_focus_ms, 11_500);
919+ }
725920 }
src/db/pool_question.rsmodified+99 -38
@@ -6,6 +6,7 @@
66
77 use crate::constant::{STATUS_APPROVED, STATUS_PENDING};
88 use crate::database::{Database, tx_with_retry};
9+use crate::db::page::{PagedList, Param};
910 use crate::domain::note_file::FileContentType;
1011 use crate::domain::pool_question::{
1112 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,
@@ -51,40 +52,50 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuest
5152 Ok(row)
5253 }
5354
54-/// Every question, newest first — the teacher+ view (approval queue and
55-/// pool in one list).
56-pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {
57- let rows = sqlx::query_as!(
58- PoolQuestion,
59- r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId",
60- title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
61- status, asked_at AS "asked_at: Timestamp",
62- approved_by AS "approved_by: UserId"
63- FROM pool_question ORDER BY asked_at DESC, id DESC"#,
64- )
65- .fetch_all(db)
66- .await?;
67- Ok(rows)
68-}
69-
70-/// The pool as a non-staff user sees it, newest first: every approved
71-/// question, plus the caller's own pending ones.
72-pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {
73- let rows = sqlx::query_as!(
74- PoolQuestion,
75- r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId",
76- title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
77- status, asked_at AS "asked_at: Timestamp",
78- approved_by AS "approved_by: UserId"
79- FROM pool_question
80- WHERE status = $1 OR asker = $2
81- ORDER BY asked_at DESC, id DESC"#,
82- STATUS_APPROVED,
83- user.uuid()
84- )
85- .fetch_all(db)
86- .await?;
87- Ok(rows)
55+/// One page of the question list, newest first — plus the `total` count of
56+/// every row under the *same* filters, so a client can page past the window.
57+///
58+/// `viewer` is the security gate, and it is a WHERE clause, never a
59+/// post-filter: `None` (teacher+ only) sees every row — the approval queue
60+/// and the pool together; `Some(me)` sees every `approved` question plus
61+/// their own pending ones. `status` is the caller's filter, ANDed on top of
62+/// that gate so it can only ever narrow: `pending` for a student is exactly
63+/// their own unapproved questions, `approved` the pool, and for teacher+
64+/// `pending` is the approval queue. Gate and filter share one statement pair
65+/// ([`PagedList`]: the shape is runtime-conditional, that builder's named
66+/// exemption from the compile-time macros), so a `pending` request never
67+/// loads the approved pool into a `Vec` first and `total` can never disagree
68+/// with what paging through the list actually yields.
69+pub async fn list(
70+ db: &Database,
71+ viewer: Option<&UserId>,
72+ status: Option<&str>,
73+ limit: Option<i64>,
74+ offset: i64,
75+) -> Result<(Vec<PoolQuestion>, i64), AppError> {
76+ let mut clauses: Vec<String> = Vec::new();
77+ let mut binds: Vec<Param> = Vec::new();
78+ if let Some(viewer) = viewer {
79+ binds.push(Param::Text(STATUS_APPROVED.to_string()));
80+ let pool_arm = format!("status = ${}", binds.len());
81+ binds.push(Param::Uuid(viewer.uuid()));
82+ let own_arm = format!("asker = ${}", binds.len());
83+ clauses.push(format!("({pool_arm} OR {own_arm})"));
84+ }
85+ if let Some(status) = status {
86+ binds.push(Param::Text(status.to_string()));
87+ clauses.push(format!("status = ${}", binds.len()));
88+ }
89+ let from_where = if clauses.is_empty() {
90+ "pool_question WHERE true".to_string()
91+ } else {
92+ format!("pool_question WHERE {}", clauses.join(" AND "))
93+ };
94+ let mut page = PagedList::new(from_where, "ORDER BY asked_at DESC, id DESC");
95+ for bind in binds {
96+ page = page.bind(bind);
97+ }
98+ page.run(limit, offset, db).await
8899 }
89100
90101 /// Publish a pending question into the pool, stamping who approved it.
@@ -483,15 +494,65 @@ mod tests {
483494 .unwrap();
484495
485496 // The asker sees their own pending question plus the pool; a stranger
486- // sees only the pool; the teacher view (list_all) sees everything.
487- assert_eq!(list_visible_to(&db, &asker).await.unwrap().len(), 2);
488- let stranger_view = list_visible_to(&db, &other).await.unwrap();
497+ // sees only the pool; the teacher view (viewer = None) sees everything.
498+ let (asker_view, total) = list(&db, Some(&asker), None, None, 0).await.unwrap();
499+ assert_eq!(asker_view.len(), 2);
500+ assert_eq!(total, 2);
501+ let (stranger_view, total) = list(&db, Some(&other), None, None, 0).await.unwrap();
489502 assert_eq!(stranger_view.len(), 1);
503+ assert_eq!(total, 1);
490504 assert_eq!(stranger_view[0].get_id(), published.get_id());
491- assert_eq!(list_all(&db).await.unwrap().len(), 2);
505+ let (everything, total) = list(&db, None, None, None, 0).await.unwrap();
506+ assert_eq!(everything.len(), 2);
507+ assert_eq!(total, 2);
492508 assert!(read(&db, pending.get_id()).await.unwrap().is_some());
493509 }
494510
511+ /// The status filter rides the same WHERE as the visibility gate: a
512+ /// student's `pending` page is exactly their own unapproved questions —
513+ /// another student's pending one exists but is not in it — and `total`
514+ /// is the filtered count. Teacher+ `pending` is the whole approval
515+ /// queue, and the window applies after the filter.
516+ #[tokio::test]
517+ async fn status_filter_narrows_within_the_visibility_gate() {
518+ let (db, _leases) = database::init_test_db().await;
519+ let asker = a_user(&db).await;
520+ let other = a_user(&db).await;
521+ let teacher = a_user(&db).await;
522+
523+ let mine_pending = insert(&db, question(&asker)).await.unwrap();
524+ let theirs_pending = insert(&db, question(&other)).await.unwrap();
525+ let mine_pool = insert(&db, question(&asker)).await.unwrap();
526+ approve(&db, mine_pool.get_id(), &teacher).await.unwrap().unwrap();
527+ let theirs_pool = insert(&db, question(&other)).await.unwrap();
528+ approve(&db, theirs_pool.get_id(), &teacher).await.unwrap().unwrap();
529+
530+ // Student, pending: their own queue only.
531+ let (items, total) =
532+ list(&db, Some(&asker), Some(STATUS_PENDING), None, 0).await.unwrap();
533+ assert_eq!(items.len(), 1);
534+ assert_eq!(total, 1);
535+ assert_eq!(items[0].get_id(), mine_pending.get_id());
536+ assert_ne!(items[0].get_id(), theirs_pending.get_id());
537+
538+ // Student, approved: the pool (their gate already was pool + own).
539+ let (items, total) =
540+ list(&db, Some(&asker), Some(STATUS_APPROVED), None, 0).await.unwrap();
541+ assert_eq!(items.len(), 2);
542+ assert_eq!(total, 2);
543+
544+ // Teacher+, pending: the full approval queue, whoever asked.
545+ let (items, total) = list(&db, None, Some(STATUS_PENDING), None, 0).await.unwrap();
546+ assert_eq!(items.len(), 2);
547+ assert_eq!(total, 2);
548+
549+ // A paged pending request counts the filtered set, not the page.
550+ let (items, total) =
551+ list(&db, None, Some(STATUS_PENDING), Some(1), 0).await.unwrap();
552+ assert_eq!(items.len(), 1);
553+ assert_eq!(total, 2);
554+ }
555+
495556 #[tokio::test]
496557 async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() {
497558 let (db, _leases) = database::init_test_db().await;
src/db/user.rsmodified+85 -3
@@ -172,14 +172,29 @@ pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError>
172172 Ok(user)
173173 }
174174
175+/// Every account, newest first — the web layer's paging read — or, when
176+/// `roles` is `Some`, only the rows whose role is in the set (the admin
177+/// directory's tabs; `manager,admin` is one OR, not an AND). The narrowing
178+/// is the `WHERE` itself, so [`PagedList`] counts the filtered set and a
179+/// later page stays inside it: page and `total` share this one predicate.
175180 pub async fn list_all(
176181 db: &Database,
182+ roles: Option<&[Role]>,
177183 limit: Option<i64>,
178184 offset: i64,
179185 ) -> Result<(Vec<User>, i64), AppError> {
180- PagedList::new("app_user", "ORDER BY id DESC")
181- .run(limit, offset, db)
182- .await
186+ let list = match roles {
187+ None => PagedList::new("app_user", "ORDER BY id DESC"),
188+ Some(roles) => PagedList::new("app_user WHERE role = ANY($1)", "ORDER BY id DESC").bind(
189+ Param::Texts(
190+ roles
191+ .iter()
192+ .map(|role| role.as_str().to_string())
193+ .collect(),
194+ ),
195+ ),
196+ };
197+ list.run(limit, offset, db).await
183198 }
184199
185200 /// Fetch the users behind `ids` in one query. Ids with no row are simply
@@ -1248,4 +1263,71 @@ mod tests {
12481263 "a missing row is None, not an error"
12491264 );
12501265 }
1266+
1267+ /// The admin directory's role tabs: `roles` is the query's `WHERE`, so
1268+ /// the page and the `total` share one filtered predicate — a window
1269+ /// never leaks another role, and `total` counts the filtered set, not
1270+ /// the roster.
1271+ #[tokio::test]
1272+ async fn the_roles_filter_is_one_where_across_page_and_total() {
1273+ let (db, _leases) = init_test_db().await;
1274+ let admin = a_user("tabor-admin", &db).await;
1275+ crate::service::user::set_role(&db, admin.get_id(), Role::Admin)
1276+ .await
1277+ .unwrap();
1278+ let manager = a_user("tabor-mgr", &db).await;
1279+ crate::service::user::set_role(&db, manager.get_id(), Role::Manager)
1280+ .await
1281+ .unwrap();
1282+ let _student1 = a_user("tabor-s1", &db).await;
1283+ let _student2 = a_user("tabor-s2", &db).await;
1284+
1285+ // Matched: only the staff pair, `total` = the filtered count.
1286+ let (staff, total) =
1287+ list_all(&db, Some(&[Role::Manager, Role::Admin]), None, 0)
1288+ .await
1289+ .unwrap();
1290+ assert_eq!(total, 2, "total counts the filtered set, not the roster");
1291+ assert!(
1292+ staff
1293+ .iter()
1294+ .all(|user| matches!(user.get_role(), Role::Manager | Role::Admin)),
1295+ "no student may ride a staff tab"
1296+ );
1297+
1298+ // Unmatched: a well-formed set naming nobody is an empty page, not
1299+ // an error.
1300+ let (none, total) = list_all(&db, Some(&[Role::Parent]), None, 0)
1301+ .await
1302+ .unwrap();
1303+ assert!(none.is_empty());
1304+ assert_eq!(total, 0);
1305+
1306+ // Absent: the whole roster, exactly the unfiltered read.
1307+ let (all, total) = list_all(&db, None, None, 0).await.unwrap();
1308+ assert_eq!(total, 4);
1309+ assert_eq!(all.len(), 4);
1310+
1311+ // The window applies AFTER the filter: a page of 1 inside the staff
1312+ // set still counts 2, and walking the windows collects exactly the
1313+ // staff pair — never a student.
1314+ let (page1, total) =
1315+ list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 0)
1316+ .await
1317+ .unwrap();
1318+ assert_eq!(total, 2);
1319+ assert_eq!(page1.len(), 1);
1320+ let (page2, _) =
1321+ list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 1)
1322+ .await
1323+ .unwrap();
1324+ assert_eq!(page2.len(), 1);
1325+ let mut both: Vec<_> = page1
1326+ .iter()
1327+ .chain(page2.iter())
1328+ .map(|user| user.get_role())
1329+ .collect();
1330+ both.sort();
1331+ assert_eq!(both, vec![Role::Manager, Role::Admin]);
1332+ }
12511333 }
src/domain/event.rsmodified+1 -1
@@ -15,7 +15,7 @@ pub struct EventId(uuid::Uuid);
1515 impl EventId {
1616 /// Minted from the process-wide monotonic generator, not a plain random
1717 /// UUID: events list `id DESC` (newest first,
18- /// [`crate::db::event::list_all`]),
18+ /// [`crate::db::event::list_windowed`]),
1919 /// and a random low half scrambles rows minted in the same millisecond.
2020 pub fn generate() -> Self {
2121 Self(next_uuid())
src/domain/exam.rsmodified+1 -1
@@ -28,7 +28,7 @@ pub struct ExamId(uuid::Uuid);
2828 impl ExamId {
2929 /// Minted from the process-wide monotonic generator, not a plain random
3030 /// UUID: exams list `id DESC` (newest first,
31- /// [`crate::db::exam::list_all`]),
31+ /// [`crate::db::exam::list_windowed`]),
3232 /// and a random low half scrambles rows minted in the same millisecond.
3333 pub fn generate() -> Self {
3434 Self(next_uuid())
src/domain/pool_question.rsmodified+1 -1
@@ -33,7 +33,7 @@ pub struct PoolQuestionId(Uuid);
3333 impl PoolQuestionId {
3434 /// Minted from the process-wide monotonic generator, not a random v4:
3535 /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break
36- /// ([`crate::db::pool_question::list_all`]),
36+ /// ([`crate::db::pool_question::list`]),
3737 /// and a random low half scrambles rows minted in the same millisecond.
3838 pub fn generate() -> Self {
3939 Self(next_uuid())
src/service/appointment.rsmodified+275 -4
@@ -119,24 +119,48 @@ pub async fn read(db: &Database, id: &AppointmentId) -> Result<Option<Appointmen
119119 appointment::read(db, id).await
120120 }
121121
122-/// The requester's bookings, newest first — the web layer's paging read.
122+/// The requester's bookings, newest first — the web layer's paging read,
123+/// narrowed by the door's optional `status`, `starts_after`/`starts_before`
124+/// (the meeting's effective start, `[after, before)`) and `teacher` (the
125+/// booked slot's teacher) filters.
123126 pub async fn list_for_requester(
124127 db: &Database,
125128 requester: &UserId,
129+ status: Option<AppointmentStatus>,
130+ starts_after: Option<Timestamp>,
131+ starts_before: Option<Timestamp>,
132+ teacher: Option<&UserId>,
126133 limit: Option<i64>,
127134 offset: i64,
128135 ) -> Result<(Vec<Appointment>, i64), AppError> {
129- appointment::list_for_requester(db, requester, limit, offset).await
136+ appointment::list_for_requester(
137+ db,
138+ requester,
139+ status,
140+ starts_after,
141+ starts_before,
142+ teacher,
143+ limit,
144+ offset,
145+ )
146+ .await
130147 }
131148
132-/// Every booking aimed at `teacher`, newest first — the request inbox.
149+/// Every booking aimed at `teacher`, newest first — the request inbox,
150+/// narrowed by the door's optional `status` and `starts_after`/`starts_before`
151+/// filters. The inbox is the teacher's own universe already, so it takes no
152+/// teacher filter: narrowing is the web layer's call.
133153 pub async fn list_for_teacher(
134154 db: &Database,
135155 teacher: &UserId,
156+ status: Option<AppointmentStatus>,
157+ starts_after: Option<Timestamp>,
158+ starts_before: Option<Timestamp>,
136159 limit: Option<i64>,
137160 offset: i64,
138161 ) -> Result<(Vec<Appointment>, i64), AppError> {
139- appointment::list_for_teacher(db, teacher, limit, offset).await
162+ appointment::list_for_teacher(db, teacher, status, starts_after, starts_before, limit, offset)
163+ .await
140164 }
141165
142166 /// Confirm the meeting at the slot's own window. Re-runs the double-booking
@@ -841,4 +865,251 @@ mod tests {
841865 assert_eq!(second.get_status(), AppointmentStatus::Pending);
842866 assert_eq!(occupied(slot.get_id(), &db).await, 1);
843867 }
868+
869+ /// The listing filters narrow each side's own universe: `status` to one
870+ /// state, `starts_after` to meetings whose effective start (a standing
871+ /// proposal, the slot's window otherwise) is at or after the instant,
872+ /// `teacher` to the booked slot's teacher — and the paging window applies
873+ /// after all of it, with `total` counting the filtered set, not the page.
874+ /// Absent filters, the listings answer exactly as before, dangling rows
875+ /// included.
876+ #[tokio::test]
877+ async fn listings_filter_by_status_start_and_teacher() {
878+ let (db, _leases) = init_test_db().await;
879+ let ali = a_person(&db, "ali", "teacher").await;
880+ let ayse = a_person(&db, "ayse", "teacher").await;
881+ let veli = a_person(&db, "veli", "student").await;
882+ let reason = AppointmentReason::try_new("görüşme").unwrap();
883+ let now = Timestamp::now().as_millis();
884+ let at = |millis: i64| Timestamp::from_millis(millis);
885+
886+ let ali_slot =
887+ appointment_slot::create(&db, &ali, at(now + 60_000), at(now + 120_000), None)
888+ .await
889+ .unwrap();
890+ let ayse_slot =
891+ appointment_slot::create(&db, &ayse, at(now + 200_000), at(now + 260_000), None)
892+ .await
893+ .unwrap();
894+ let pending = book(&db, ali_slot.get_id(), &veli, reason.clone())
895+ .await
896+ .unwrap();
897+ let approved = book(&db, ayse_slot.get_id(), &veli, reason.clone())
898+ .await
899+ .unwrap();
900+ approve(&db, approved.get_id(), &ayse).await.unwrap();
901+ let settled_slot =
902+ appointment_slot::create(&db, &ali, at(now + 300_000), at(now + 360_000), None)
903+ .await
904+ .unwrap();
905+ let cancelled = book(&db, settled_slot.get_id(), &veli, reason.clone())
906+ .await
907+ .unwrap();
908+ cancel(&db, cancelled.get_id(), &veli, None).await.unwrap();
909+
910+ // Absent: all three, newest first — the shape today's callers see.
911+ let (rows, total) =
912+ list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap();
913+ assert_eq!((rows.len(), total), (3, 3));
914+
915+ // status: only the approved one, and total is the filtered count.
916+ let (rows, total) = list_for_requester(&db, &veli, Some(AppointmentStatus::Approved), None, None, None,
917+ None,
918+ 0,
919+ )
920+ .await
921+ .unwrap();
922+ assert_eq!((rows.len(), total), (1, 1));
923+ assert_eq!(rows[0].get_id(), approved.get_id());
924+
925+ // No state matches: an empty page, not an error.
926+ let (rows, total) = list_for_requester(&db, &veli, Some(AppointmentStatus::Rejected), None, None, None,
927+ None,
928+ 0,
929+ )
930+ .await
931+ .unwrap();
932+ assert_eq!((rows.len(), total), (0, 0));
933+
934+ // teacher joins through the slot: only the bookings on ali's slots.
935+ let (rows, total) =
936+ list_for_requester(&db, &veli, None, None, None, Some(&ali), None, 0).await.unwrap();
937+ assert_eq!((rows.len(), total), (2, 2));
938+ assert!(rows.iter().all(|row| row.get_id() != approved.get_id()));
939+
940+ // starts_after judges the effective start: the pending meeting (at
941+ // now + 60_000) is out; the approved and cancelled ones stay.
942+ let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now + 150_000)), None, None,
943+ None,
944+ 0,
945+ )
946+ .await
947+ .unwrap();
948+ assert_eq!((rows.len(), total), (2, 2));
949+ assert!(rows.iter().all(|row| row.get_id() != pending.get_id()));
950+
951+ // The window applies after the filter; total stays the filtered count.
952+ let (page1, total) =
953+ list_for_requester(&db, &veli, None, None, None, None, Some(1), 0).await.unwrap();
954+ assert_eq!((page1.len(), total), (1, 3));
955+ let (page2, total) =
956+ list_for_requester(&db, &veli, None, None, None, None, Some(1), 1).await.unwrap();
957+ assert_eq!((page2.len(), total), (1, 3));
958+ assert_ne!(page1[0].get_id(), page2[0].get_id());
959+
960+ // A standing proposal moves the meeting's start for the cut: the
961+ // pending booking proposes itself to now + 500_000, so it alone
962+ // clears a cut at now + 400_000.
963+ propose(&db, pending.get_id(), at(now + 500_000), at(now + 560_000), &ali)
964+ .await
965+ .unwrap();
966+ let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now + 400_000)), None, None,
967+ None,
968+ 0,
969+ )
970+ .await
971+ .unwrap();
972+ assert_eq!((rows.len(), total), (1, 1));
973+ assert_eq!(rows[0].get_id(), pending.get_id());
974+
975+ // The inbox: ali's two bookings and never ayse's — the join's
976+ // teacher predicate is the whole visibility universe here.
977+ let (rows, total) =
978+ list_for_teacher(&db, &ali, None, None, None, None, 0).await.unwrap();
979+ assert_eq!((rows.len(), total), (2, 2));
980+ let (rows, total) = list_for_teacher(&db, &ali, Some(AppointmentStatus::Cancelled), None, None, None,
981+ 0,
982+ )
983+ .await
984+ .unwrap();
985+ assert_eq!((rows.len(), total), (1, 1));
986+ assert_eq!(rows[0].get_id(), cancelled.get_id());
987+ let (_, total) =
988+ list_for_teacher(&db, &ali, None, Some(at(now + 400_000)), None, None, 0)
989+ .await
990+ .unwrap();
991+ assert_eq!(total, 1);
992+ let (rows, total) =
993+ list_for_teacher(&db, &ali, None, None, None, Some(1), 0).await.unwrap();
994+ assert_eq!((rows.len(), total), (1, 2));
995+
996+ // A settled booking whose slot is withdrawn still lists unfiltered —
997+ // today's shape — and the time and teacher filters drop it: it has
998+ // neither a meeting window nor a teacher any more. The guarded
999+ // delete sweeps its settled bookings along, so the dangling shape is
1000+ // forced here the way a demotion sweep leaves it: the slot row goes,
1001+ // and the slot's `ON DELETE SET NULL` strands the booking.
1002+ sqlx::query("DELETE FROM appointment_slot WHERE id = $1")
1003+ .bind(settled_slot.get_id().uuid())
1004+ .execute(&db)
1005+ .await
1006+ .unwrap();
1007+ let (rows, total) =
1008+ list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap();
1009+ assert_eq!((rows.len(), total), (3, 3), "the windowless row still lists");
1010+ let (rows, total) = list_for_requester(&db, &veli, None, Some(at(now)), None, None,
1011+ None,
1012+ 0,
1013+ )
1014+ .await
1015+ .unwrap();
1016+ assert_eq!((rows.len(), total), (2, 2), "the windowless row has no start to match");
1017+ assert!(rows.iter().all(|row| row.get_id() != cancelled.get_id()));
1018+ let (rows, total) =
1019+ list_for_requester(&db, &veli, None, None, None, Some(&ali), None, 0).await.unwrap();
1020+ assert_eq!((rows.len(), total), (1, 1), "a windowless row names no teacher");
1021+ assert_eq!(rows[0].get_id(), pending.get_id());
1022+ }
1023+
1024+ /// `starts_before` is the upper edge of a half-open month window: a row
1025+ /// starting before the bound is out, a row inside it stays, the bound
1026+ /// instant itself is excluded, and absent the set is unchanged.
1027+ #[tokio::test]
1028+ async fn starts_before_bounds_the_meeting_exclusively() {
1029+ let (db, _leases) = init_test_db().await;
1030+ let teacher = a_person(&db, "t1", "teacher").await;
1031+ let veli = a_person(&db, "veli", "student").await;
1032+ let reason = AppointmentReason::try_new("görüşme").unwrap();
1033+ let now = Timestamp::now().as_millis();
1034+ let at = |millis: i64| Timestamp::from_millis(millis);
1035+
1036+ // Two bookings: one before the bound, one after it.
1037+ let early_slot =
1038+ appointment_slot::create(&db, &teacher, at(now + 60_000), at(now + 120_000), None)
1039+ .await
1040+ .unwrap();
1041+ let late_slot =
1042+ appointment_slot::create(&db, &teacher, at(now + 200_000), at(now + 260_000), None)
1043+ .await
1044+ .unwrap();
1045+ let early = book(&db, early_slot.get_id(), &veli, reason.clone())
1046+ .await
1047+ .unwrap();
1048+ let late = book(&db, late_slot.get_id(), &veli, reason.clone())
1049+ .await
1050+ .unwrap();
1051+
1052+ // Absent: both — the set is unchanged without the bound.
1053+ let (rows, total) =
1054+ list_for_requester(&db, &veli, None, None, None, None, None, 0).await.unwrap();
1055+ assert_eq!((rows.len(), total), (2, 2));
1056+
1057+ // before: only the early booking survives.
1058+ let (rows, total) = list_for_requester(
1059+ &db,
1060+ &veli,
1061+ None,
1062+ None,
1063+ Some(at(now + 150_000)),
1064+ None,
1065+ None,
1066+ 0,
1067+ )
1068+ .await
1069+ .unwrap();
1070+ assert_eq!((rows.len(), total), (1, 1));
1071+ assert_eq!(rows[0].get_id(), early.get_id());
1072+
1073+ // Half-open: the bound instant itself is outside the window, so a
1074+ // cut exactly at the late meeting's start keeps only the early one —
1075+ // and the inbox answers the same way.
1076+ let (rows, total) = list_for_requester(
1077+ &db,
1078+ &veli,
1079+ None,
1080+ None,
1081+ Some(at(now + 200_000)),
1082+ None,
1083+ None,
1084+ 0,
1085+ )
1086+ .await
1087+ .unwrap();
1088+ assert_eq!((rows.len(), total), (1, 1));
1089+ assert_eq!(rows[0].get_id(), early.get_id());
1090+
1091+ let (rows, total) =
1092+ list_for_teacher(&db, &teacher, None, None, Some(at(now + 150_000)), None, 0)
1093+ .await
1094+ .unwrap();
1095+ assert_eq!((rows.len(), total), (1, 1));
1096+ assert_eq!(rows[0].get_id(), early.get_id());
1097+
1098+ // Composed with starts_after, the pair is the month window: only the
1099+ // late meeting sits in [now + 150_000, now + 260_000).
1100+ let (rows, total) = list_for_requester(
1101+ &db,
1102+ &veli,
1103+ None,
1104+ Some(at(now + 150_000)),
1105+ Some(at(now + 260_000)),
1106+ None,
1107+ None,
1108+ 0,
1109+ )
1110+ .await
1111+ .unwrap();
1112+ assert_eq!((rows.len(), total), (1, 1));
1113+ assert_eq!(rows[0].get_id(), late.get_id());
1114+ }
8441115 }
src/service/appointment_slot.rsmodified+110 -4
@@ -27,21 +27,37 @@ pub async fn read(
2727 appointment_slot::read(db, id).await
2828 }
2929
30-/// A teacher's own calendar, earliest first — the web layer's calendar read.
30+/// A teacher's own calendar, earliest first — the plain, unfiltered read.
3131 pub async fn list_for_teacher(
3232 db: &Database,
3333 teacher: &UserId,
3434 ) -> Result<Vec<AppointmentSlot>, AppError> {
35- appointment_slot::list_for_teacher(db, teacher).await
35+ appointment_slot::list_for_teacher(db, teacher, None).await
36+}
37+
38+/// The calendar read the slots door runs: `teacher`'s published rows,
39+/// earliest first, cut to windows starting at or after `starts_after` when
40+/// the caller asked. The cut is the SQL's, so a calendar with years of past
41+/// publishes answers from the asked-for window onward without loading its
42+/// whole history to slice it afterwards.
43+pub async fn list_calendar(
44+ db: &Database,
45+ teacher: &UserId,
46+ starts_after: Option<Timestamp>,
47+) -> Result<Vec<AppointmentSlot>, AppError> {
48+ appointment_slot::list_for_teacher(db, teacher, starts_after).await
3649 }
3750
3851 /// Every slot whose window has not opened yet, earliest first — the bookable
39-/// calendar a requester browses.
52+/// calendar a requester browses, narrowed by the door's optional `teacher`
53+/// and `starts_after` filters (which only cut inside the upcoming set).
4054 pub async fn list_upcoming(
4155 db: &Database,
4256 from: Timestamp,
57+ teacher: Option<&UserId>,
58+ starts_after: Option<Timestamp>,
4359 ) -> Result<Vec<AppointmentSlot>, AppError> {
44- appointment_slot::list_upcoming(db, from).await
60+ appointment_slot::list_upcoming(db, from, teacher, starts_after).await
4561 }
4662
4763 /// Every slot of one recurring publish, earliest first.
@@ -563,4 +579,94 @@ mod tests {
563579 ));
564580 assert!(list_for_teacher(&db, &teacher).await.unwrap().is_empty());
565581 }
582+
583+ /// The calendar read stays within the named teacher's rows after the
584+ /// rewrite to the runtime builder — the slots door's whole visibility
585+ /// universe hangs on that predicate.
586+ #[tokio::test]
587+ async fn the_calendar_read_names_only_its_own_teachers_rows() {
588+ let (db, _leases) = crate::database::init_test_db().await;
589+ let ali = a_person(&db, "ali", "teacher").await;
590+ let ayse = a_person(&db, "ayse", "teacher").await;
591+ create(&db, &ali, at(1_000), at(2_000), None).await.unwrap();
592+ create(&db, &ayse, at(3_000), at(4_000), None).await.unwrap();
593+
594+ let calendar = list_for_teacher(&db, &ali).await.unwrap();
595+ assert_eq!(calendar.len(), 1);
596+ assert_eq!(calendar[0].get_teacher(), &ali);
597+ }
598+
599+ /// The calendar cut is the SQL's: `starts_after` drops the past
600+ /// occurrences from the read instead of loading the whole history for the
601+ /// caller to slice, so the filtered length the web layer reports is the
602+ /// filtered count. The instant is inclusive.
603+ #[tokio::test]
604+ async fn the_calendar_start_cut_is_sql_side_and_inclusive() {
605+ let (db, _leases) = crate::database::init_test_db().await;
606+ let teacher = a_person(&db, "t1", "teacher").await;
607+ let now = Timestamp::now().as_millis();
608+ create(&db, &teacher, at(now - 10_000), at(now - 5_000), None)
609+ .await
610+ .unwrap();
611+ create(&db, &teacher, at(now + 10_000), at(now + 20_000), None)
612+ .await
613+ .unwrap();
614+
615+ // Absent: both, earliest first — the calendar as it has always read.
616+ let all = list_for_teacher(&db, &teacher).await.unwrap();
617+ assert_eq!(all.len(), 2);
618+ assert!(all[0].get_starts_at().as_millis() < all[1].get_starts_at().as_millis());
619+
620+ // Filtered: only the future one; the cut instant itself would match.
621+ let upcoming = list_calendar(&db, &teacher, Some(at(now))).await.unwrap();
622+ assert_eq!(upcoming.len(), 1);
623+ assert_eq!(upcoming[0].get_starts_at().as_millis(), now + 10_000);
624+ }
625+
626+ /// The bookable read narrows inside the upcoming set: the strict
627+ /// `starts_at > now` bound never moves, the teacher filter names one
628+ /// publisher, and the instant cut is inclusive. Absent, the read is the
629+ /// whole calendar exactly as before.
630+ #[tokio::test]
631+ async fn the_upcoming_read_narrows_without_moving_the_bound() {
632+ let (db, _leases) = crate::database::init_test_db().await;
633+ let ali = a_person(&db, "ali", "teacher").await;
634+ let ayse = a_person(&db, "ayse", "teacher").await;
635+ let now = Timestamp::now().as_millis();
636+ create(&db, &ali, at(now - 10_000), at(now - 5_000), None)
637+ .await
638+ .unwrap();
639+ create(&db, &ali, at(now + 5_000), at(now + 10_000), None)
640+ .await
641+ .unwrap();
642+ create(&db, &ali, at(now + 60_000), at(now + 90_000), None)
643+ .await
644+ .unwrap();
645+ create(&db, &ayse, at(now + 30_000), at(now + 40_000), None)
646+ .await
647+ .unwrap();
648+
649+ let from = at(now);
650+ // Absent: the strict bound holds — ali's past slot is out, three in.
651+ let all = list_upcoming(&db, from, None, None).await.unwrap();
652+ assert_eq!(all.len(), 3);
653+
654+ // teacher: only that teacher, past stays out.
655+ let ali_only = list_upcoming(&db, from, Some(&ali), None).await.unwrap();
656+ assert_eq!(ali_only.len(), 2);
657+ assert!(ali_only.iter().all(|slot| slot.get_teacher() == &ali));
658+
659+ // starts_after is inclusive: the two slots at or after the cut.
660+ let cut = list_upcoming(&db, from, None, Some(at(now + 30_000)))
661+ .await
662+ .unwrap();
663+ assert_eq!(cut.len(), 2);
664+
665+ // Both filters together.
666+ let both = list_upcoming(&db, from, Some(&ayse), Some(at(now + 30_000)))
667+ .await
668+ .unwrap();
669+ assert_eq!(both.len(), 1);
670+ assert_eq!(both[0].get_teacher(), &ayse);
671+ }
566672 }
src/service/board.rsmodified+2 -1
@@ -181,10 +181,11 @@ pub async fn list_for_user(
181181 db: &Database,
182182 user: &UserId,
183183 open: Option<bool>,
184+ q: Option<&str>,
184185 limit: Option<i64>,
185186 offset: i64,
186187 ) -> Result<(Vec<Board>, i64), AppError> {
187- board::list_for_user(db, user, open, limit, offset).await
188+ board::list_for_user(db, user, open, q, limit, offset).await
188189 }
189190
190191 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
src/service/course.rsmodified+10 -2
@@ -31,8 +31,16 @@ pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppErr
3131 course::read(db, id).await
3232 }
3333
34-pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
35- course::list_all(db).await
34+/// The catalog the visible list's manager arm serves, optionally narrowed by
35+/// the `GET /courses` filters (`kind`, folded `q`) — pushed into the SQL so
36+/// listing one kind is not a full-catalog pull.
37+pub async fn list_filtered(
38+ db: &Database,
39+ kind: Option<CourseKind>,
40+ q: Option<&str>,
41+ taught: Option<bool>,
42+) -> Result<Vec<Course>, AppError> {
43+ course::list_filtered(db, kind, q, taught).await
3644 }
3745
3846 pub async fn list_enrolled(
src/service/course_session.rsmodified+26 -2
@@ -73,14 +73,38 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSe
7373 course_session::read(db, id).await
7474 }
7575
76-/// An instance's sessions, most recent lesson first — the timetable read.
76+/// An instance's sessions, most recent lesson first — the timetable read,
77+/// unbounded by any schedule window.
7778 pub async fn list_for_class_course(
7879 db: &Database,
7980 class_course: &ClassCourseId,
8081 limit: Option<i64>,
8182 offset: i64,
8283 ) -> Result<(Vec<CourseSession>, i64), AppError> {
83- course_session::list_for_class_course(db, class_course, limit, offset).await
84+ list_windowed(db, class_course, None, None, limit, offset).await
85+}
86+
87+/// The same timetable read narrowed to a half-open `[starts_after,
88+/// starts_before)` on `starts_at` — a calendar month is
89+/// `[month_start, next_month_start)`. The page and the count share the one
90+/// SQL `WHERE`; the order does not flip.
91+pub async fn list_windowed(
92+ db: &Database,
93+ class_course: &ClassCourseId,
94+ starts_after: Option<i64>,
95+ starts_before: Option<i64>,
96+ limit: Option<i64>,
97+ offset: i64,
98+) -> Result<(Vec<CourseSession>, i64), AppError> {
99+ course_session::list_for_class_course(
100+ db,
101+ class_course,
102+ starts_after,
103+ starts_before,
104+ limit,
105+ offset,
106+ )
107+ .await
84108 }
85109
86110 /// Only what the request carried is written: an omitted field (`None`) is
src/service/event.rsmodified+22 -3
@@ -37,9 +37,28 @@ pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError
3737 event::read(db, id).await
3838 }
3939
40-/// Every event, newest first.
41-pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
42- event::list_all(db).await
40+/// The `GET /events` list — visibility-free (every authenticated user sees
41+/// every event), the schedule window and the page pushed into SQL. All four
42+/// window bounds absent is the unfiltered, newest-first read.
43+pub async fn list_windowed(
44+ db: &Database,
45+ starts_after: Option<i64>,
46+ ends_after: Option<i64>,
47+ starts_before: Option<i64>,
48+ ends_before: Option<i64>,
49+ limit: Option<i64>,
50+ offset: i64,
51+) -> Result<(Vec<Event>, i64), AppError> {
52+ event::list_windowed(
53+ db,
54+ starts_after,
55+ ends_after,
56+ starts_before,
57+ ends_before,
58+ limit,
59+ offset,
60+ )
61+ .await
4362 }
4463
4564 /// Only what the request carried is written: an omitted field (`None`) is
src/service/exam.rsmodified+196 -12
@@ -113,8 +113,34 @@ pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError>
113113 exam::read(db, id).await
114114 }
115115
116-pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
117- exam::list_all(db).await
116+/// The `GET /exams` list. `visible`/`managed` are the non-manager read (the
117+/// exams of the caller's visible instances, a draft only where they manage
118+/// the owner instance); both `None` is the manager+ whole-table read. The
119+/// schedule window, the visibility, the draft rule, the page, and the count
120+/// share one SQL `WHERE` — see [`exam::list_windowed`].
121+pub async fn list_windowed(
122+ db: &Database,
123+ visible: Option<&[ClassCourseId]>,
124+ managed: Option<&[ClassCourseId]>,
125+ starts_after: Option<i64>,
126+ ends_after: Option<i64>,
127+ starts_before: Option<i64>,
128+ ends_before: Option<i64>,
129+ limit: Option<i64>,
130+ offset: i64,
131+) -> Result<(Vec<Exam>, i64), AppError> {
132+ exam::list_windowed(
133+ db,
134+ visible,
135+ managed,
136+ starts_after,
137+ ends_after,
138+ starts_before,
139+ ends_before,
140+ limit,
141+ offset,
142+ )
143+ .await
118144 }
119145
120146 /// One instance's exams, newest first — the read behind
@@ -126,16 +152,6 @@ pub async fn list_for_class_course(
126152 exam::list_for_class_course(db, class_course).await
127153 }
128154
129-/// Every exam of every instance in `instances` (one query) — the report-card
130-/// and marks reports' cross-instance read, and the list behind a caller's
131-/// visible instances.
132-pub async fn list_for_class_course_courses(
133- db: &Database,
134- instances: &[ClassCourseId],
135-) -> Result<Vec<Exam>, AppError> {
136- exam::list_for_class_course_courses(db, instances).await
137-}
138-
139155 /// Every exam of every catalog course in `courses` (one query) — the catalog
140156 /// as one user sees it, across the instances those courses are taught in.
141157 pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
@@ -821,4 +837,172 @@ mod tests {
821837 "neither refusal wrote"
822838 );
823839 }
840+
841+ /// An exam with full control over the schedule and the draft flag — the
842+ /// window and draft-rule tests need shapes [`exam_on`] does not make.
843+ async fn exam_shaped(
844+ db: &Database,
845+ instance: &ClassCourse,
846+ schedule: ExamSchedule,
847+ draft: bool,
848+ title: &str,
849+ ) -> Exam {
850+ let creator = crate::db::class_member::tests::fixture_user(db, "window-author").await;
851+ let term = crate::db::term::a_test_term(db).await;
852+ let allowed = Settings::defaults().get_exam_kinds().to_vec();
853+ crate::db::exam::create(
854+ db,
855+ &creator,
856+ instance.get_id(),
857+ &term,
858+ ExamTitle::try_new(title).unwrap(),
859+ ExamDescription::try_new("").unwrap(),
860+ ExamKind::try_new("yazili", &allowed).unwrap(),
861+ schedule,
862+ ExamAttemptLimit::try_new(1).unwrap(),
863+ true,
864+ false,
865+ draft,
866+ )
867+ .await
868+ .unwrap()
869+ }
870+
871+ /// `list_windowed` in SQL must answer exactly what the old
872+ /// list-and-retain read answered: visibility (any addressed instance),
873+ /// the draft rule (only where the caller manages the owner instance),
874+ /// the schedule window (schedule-less rows out, ascending order), and a
875+ /// `total` that is the filtered count even when the page is short.
876+ #[tokio::test]
877+ async fn the_exam_list_window_keeps_visibility_and_draft_rules() {
878+ let (db, _leases) = crate::database::init_test_db().await;
879+ let manager = staff(&db, "window-mudur", Role::Manager).await;
880+ let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
881+ let geometry = crate::db::class_member::tests::a_course("geometry", &db).await;
882+ let a = instance_in(&db, manager.get_id(), "8-A", &algebra, None).await;
883+ let b = instance_in(&db, manager.get_id(), "8-B", &geometry, None).await;
884+
885+ let now = Timestamp::now().as_millis();
886+ let sync =
887+ |starts_at: i64| -> ExamSchedule {
888+ ExamSchedule::try_new(
889+ Some(ExamMode::try_new("sync").unwrap()),
890+ Some(Timestamp::from_millis(starts_at)),
891+ Some(Timestamp::from_millis(starts_at + 3_600_000)),
892+ None,
893+ )
894+ .unwrap()
895+ };
896+ // On A: a scheduled exam ahead, a scheduled draft ahead, a
897+ // window-less (`sync`-less, so no-mode) published exam, and one that
898+ // already ran. On B: a draft of *another* instance.
899+ let ahead = exam_shaped(&db, &a, sync(now + 3_600_000), false, "ahead").await;
900+ let ahead_draft = exam_shaped(&db, &a, sync(now + 3_600_000), true, "ahead-draft").await;
901+ let open = exam_shaped(&db, &a, ExamSchedule::default(), false, "open").await;
902+ let ran = exam_shaped(&db, &a, sync(now - 3_600_000), false, "ran").await;
903+ let other_draft = exam_shaped(&db, &b, sync(now + 3_600_000), true, "other-draft").await;
904+
905+ // Manager+: the whole table, newest first.
906+ let (rows, total) = list_windowed(&db, None, None, None, None, None, None, None, 0)
907+ .await
908+ .unwrap();
909+ assert_eq!(total, 5);
910+ let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
911+ assert_eq!(
912+ listed,
913+ [&other_draft, &ran, &open, &ahead_draft, &ahead]
914+ .into_iter()
915+ .map(|exam| exam.get_id().clone())
916+ .collect::<Vec<_>>()
917+ );
918+
919+ // Manager+ WITH a window: the window predicates must name the
920+ // unaliased `exam` (the audience join only exists on the other
921+ // branch). This exact call 500'd with "missing FROM-clause entry for
922+ // table e" while the predicates were `e.`-qualified.
923+ let (rows, total) = list_windowed(&db, None, None, None, Some(now), None, None, None, 0)
924+ .await
925+ .unwrap();
926+ assert_eq!(total, 3);
927+ let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
928+ assert_eq!(
929+ listed,
930+ [&ahead, &ahead_draft, &other_draft]
931+ .into_iter()
932+ .map(|exam| exam.get_id().clone())
933+ .collect::<Vec<_>>()
934+ );
935+ let (_, total) =
936+ list_windowed(&db, None, None, None, None, Some(now + 45 * 60_000), None, None, 0)
937+ .await
938+ .unwrap();
939+ assert_eq!(total, 1, "starts_before keeps only the already-run exam");
940+
941+ // A viewer of A who manages nothing: A's published exams only — both
942+ // drafts (A's own and the other instance's) stay hidden.
943+ let visible = vec![a.get_id().clone()];
944+ let nothing: Vec<ClassCourseId> = Vec::new();
945+ let (rows, total) =
946+ list_windowed(&db, Some(&visible), Some(&nothing), None, None, None, None, None, 0)
947+ .await
948+ .unwrap();
949+ assert_eq!(total, 3);
950+ assert!(rows.iter().all(|exam| !exam.is_draft()));
951+
952+ // A's teacher manages A: sees A's draft — and still not B's.
953+ let manages_a = vec![a.get_id().clone()];
954+ let (rows, total) =
955+ list_windowed(&db, Some(&visible), Some(&manages_a), None, None, None, None, None, 0)
956+ .await
957+ .unwrap();
958+ assert_eq!(total, 4);
959+ assert!(rows.iter().any(|exam| exam.get_id() == ahead_draft.get_id()));
960+ assert!(!rows.iter().any(|exam| exam.get_id() == other_draft.get_id()));
961+
962+ // The window rides the same WHERE: `ends_after=now` keeps the
963+ // scheduled ahead pair (the draft included — a draft is visible where
964+ // it is visible), drops the open exam (no schedule) and the one that
965+ // ran, and flips the order to schedule ascending, id tie-break.
966+ let (rows, total) = list_windowed(
967+ &db,
968+ Some(&visible),
969+ Some(&manages_a),
970+ None,
971+ Some(now),
972+ None,
973+ None,
974+ None,
975+ 0,
976+ )
977+ .await
978+ .unwrap();
979+ assert_eq!(total, 2);
980+ let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
981+ assert_eq!(listed, vec![ahead.get_id().clone(), ahead_draft.get_id().clone()]);
982+
983+ // A short page of the filtered set still reports the filtered total.
984+ let (rows, total) = list_windowed(
985+ &db,
986+ Some(&visible),
987+ Some(&manages_a),
988+ None,
989+ Some(now),
990+ None,
991+ None,
992+ Some(1),
993+ 0,
994+ )
995+ .await
996+ .unwrap();
997+ assert_eq!((rows.len(), total), (1, 2));
998+
999+ // A viewer of B manages nothing, and B's only exam is a draft: the
1000+ // draft wall leaves them an empty page, not an error.
1001+ let sees_b = vec![b.get_id().clone()];
1002+ let (rows, total) =
1003+ list_windowed(&db, Some(&sees_b), Some(&nothing), None, None, None, None, None, 0)
1004+ .await
1005+ .unwrap();
1006+ assert!(rows.is_empty() && total == 0);
1007+ }
8241008 }
src/service/homework.rsmodified+44 -4
@@ -63,8 +63,38 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, Ap
6363 homework::read(db, id).await
6464 }
6565
66-pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
67- homework::list_all(db).await
66+/// The optional predicates of the cross-instance homework reads — the
67+/// `?due_after=&due_before=&class_course=` scoping of `GET /homework`.
68+/// Absent fields widen the read; none of them widens the caller's
69+/// visibility, which the web layer still applies on top.
70+#[derive(Debug, Clone, Default)]
71+pub struct HomeworkListFilter {
72+ /// Keep homework due at or after this instant (Unix ms) — the open tab.
73+ pub due_after: Option<i64>,
74+ /// Keep homework due before this instant (Unix ms) — the past tab.
75+ pub due_before: Option<i64>,
76+ /// Keep only this class×course instance's homework.
77+ pub class_course: Option<ClassCourseId>,
78+}
79+
80+/// Every homework, newest first — the manager+ view, narrowed by `filter`
81+/// in SQL and paged in the database (a manager retains nothing in Rust, so
82+/// the window and the count are both the database's).
83+pub async fn list_all(
84+ db: &Database,
85+ filter: &HomeworkListFilter,
86+ limit: Option<i64>,
87+ offset: i64,
88+) -> Result<(Vec<Homework>, i64), AppError> {
89+ homework::list_all(
90+ db,
91+ filter.due_after,
92+ filter.due_before,
93+ filter.class_course.as_ref(),
94+ limit,
95+ offset,
96+ )
97+ .await
6898 }
6999
70100 /// The homework of one class×course instance, newest first — the read behind
@@ -77,12 +107,22 @@ pub async fn list_for_class_course(
77107 }
78108
79109 /// Every homework of every instance in `instances` (one query) — the read
80-/// behind a caller's visible courses.
110+/// behind a caller's visible courses, narrowed by `filter` in SQL. Unpaged:
111+/// the caller may still drop rows in Rust (a student's audience), so a
112+/// window here could only hide rows that trim was about to keep.
81113 pub async fn list_for_class_courses(
82114 db: &Database,
83115 instances: &[ClassCourseId],
116+ filter: &HomeworkListFilter,
84117 ) -> Result<Vec<Homework>, AppError> {
85- homework::list_for_class_courses(db, instances).await
118+ homework::list_for_class_courses(
119+ db,
120+ instances,
121+ filter.due_after,
122+ filter.due_before,
123+ filter.class_course.as_ref(),
124+ )
125+ .await
86126 }
87127
88128 /// The homework of one instance that `user` is meant to see — the per-instance
src/service/menu.rsmodified+5 -2
@@ -42,15 +42,18 @@ pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError>
4242 menu::read(db, id).await
4343 }
4444
45-/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds.
45+/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds. `slot`,
46+/// when given, narrows to menus published under that exact snapshotted
47+/// slot text.
4648 pub async fn list(
4749 db: &Database,
4850 from: Option<&MenuDate>,
4951 to: Option<&MenuDate>,
52+ slot: Option<&str>,
5053 limit: Option<i64>,
5154 offset: i64,
5255 ) -> Result<(Vec<Menu>, i64), AppError> {
53- menu::list(db, from, to, limit, offset).await
56+ menu::list(db, from, to, slot, limit, offset).await
5457 }
5558
5659 /// Change a menu's seat cap; `None` keeps it, `Some(None)` clears it.
src/service/message.rsmodified+2 -1
@@ -29,10 +29,11 @@ pub async fn list_folder(
2929 user: &UserId,
3030 folder: Folder,
3131 read: Option<bool>,
32+ q: Option<&str>,
3233 limit: Option<i64>,
3334 offset: i64,
3435 ) -> Result<(Vec<Message>, i64), AppError> {
35- message::list_folder(db, user, folder, read, limit, offset).await
36+ message::list_folder(db, user, folder, read, q, limit, offset).await
3637 }
3738
3839 pub async fn read_for(
src/service/pomodoro.rsmodified+13 -3
@@ -5,6 +5,7 @@
55
66 use crate::database::Database;
77 use crate::db::pomodoro;
8+pub(crate) use crate::db::pomodoro::PomodoroLogPage;
89 use crate::domain::pomodoro::PomodoroSession;
910 use crate::domain::user::UserId;
1011 use crate::error::AppError;
@@ -25,7 +26,16 @@ pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, App
2526 pomodoro::finish(db, user).await
2627 }
2728
28-/// Every session of `user`, newest first — the running one included.
29-pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {
30- pomodoro::list_for_user(db, user).await
29+/// A page of `user`'s log, newest first — the running one included — with the
30+/// half-open `[from, to)` window (unix ms) applied before the count and the
31+/// focus sum.
32+pub(crate) async fn page_for_user(
33+ db: &Database,
34+ user: &UserId,
35+ from: Option<i64>,
36+ to: Option<i64>,
37+ limit: Option<i64>,
38+ offset: i64,
39+) -> Result<PomodoroLogPage, AppError> {
40+ pomodoro::page_for_user(db, user, from, to, limit, offset).await
3141 }
src/service/pool_question.rsmodified+12 -10
@@ -20,16 +20,18 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuest
2020 pool_question::read(db, id).await
2121 }
2222
23-/// Every question, newest first — the teacher+ view (approval queue and
24-/// pool in one list).
25-pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {
26- pool_question::list_all(db).await
27-}
28-
29-/// The pool as a non-staff user sees it, newest first: every approved
30-/// question, plus the caller's own pending ones.
31-pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {
32- pool_question::list_visible_to(db, user).await
23+/// One page of the caller's question list — visibility gate and optional
24+/// status filter in one SQL `WHERE`, so `total` counts the filtered set.
25+/// `viewer = None` is the teacher+ view (everything); `Some(me)` the pool
26+/// plus the caller's own pending questions.
27+pub async fn list(
28+ db: &Database,
29+ viewer: Option<&UserId>,
30+ status: Option<&str>,
31+ limit: Option<i64>,
32+ offset: i64,
33+) -> Result<(Vec<PoolQuestion>, i64), AppError> {
34+ pool_question::list(db, viewer, status, limit, offset).await
3335 }
3436
3537 /// Approve a pending question, stamping `approver`. A `None` from the
src/service/user.rsmodified+5 -2
@@ -131,13 +131,16 @@ pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError>
131131 user::read(db, id).await
132132 }
133133
134-/// Every account, newest first — the web layer's paging read.
134+/// Every account, newest first — or only the roles `roles` names, when the
135+/// set is `Some` (the admin directory's tabs). The narrowing is the query's
136+/// `WHERE`, so `total` counts the filtered set and paging stays inside it.
135137 pub async fn list_all(
136138 db: &Database,
139+ roles: Option<&[Role]>,
137140 limit: Option<i64>,
138141 offset: i64,
139142 ) -> Result<(Vec<User>, i64), AppError> {
140- user::list_all(db, limit, offset).await
143+ user::list_all(db, roles, limit, offset).await
141144 }
142145
143146 /// The users behind `ids` in one query; missing ids simply absent.
src/web/appointments.rsmodified+627 -13
@@ -5,12 +5,14 @@ use axum::Json;
55 use axum::extract::{Path, Query};
66 use axum::http::StatusCode;
77 use serde::{Deserialize, Serialize};
8-use utoipa::ToSchema;
8+use utoipa::{IntoParams, ToSchema};
99 use utoipa_axum::router::OpenApiRouter;
1010 use utoipa_axum::routes;
1111
1212 use crate::database::Database;
13-use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason};
13+use crate::domain::appointment::{
14+ Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
15+};
1416 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
1517 use crate::domain::role::Role;
1618 use crate::domain::timestamp::Timestamp;
@@ -379,6 +381,72 @@ async fn publish_slots(
379381 Ok((StatusCode::CREATED, Json(items)))
380382 }
381383
384+/// One teacher's window filter, shared by both doors: `me` is the caller,
385+/// blank is refused, and a well-formed-but-unknown id stands — it names no
386+/// row, so the filtered page is simply empty — while a malformed one is a
387+/// 400. Never [`UserId::from_key`] into a nil id: that would read as an
388+/// empty 200 instead of the caller's error.
389+fn teacher_filter(raw: Option<&str>, caller: &UserId) -> Result<Option<UserId>, AppError> {
390+ let Some(raw) = raw else {
391+ return Ok(None);
392+ };
393+ let key = raw.trim();
394+ if key.is_empty() {
395+ return Err(AppError::Validation(ValidationError::Invalid {
396+ field: "teacher",
397+ reason: "must not be empty",
398+ }));
399+ }
400+ Ok(Some(match key {
401+ "me" => *caller,
402+ other => {
403+ let id = UserId::from_key(other);
404+ if id.uuid().is_nil() {
405+ return Err(AppError::Validation(ValidationError::Invalid {
406+ field: "teacher",
407+ reason: "must be a hyphenated uuid",
408+ }));
409+ }
410+ id
411+ }
412+ }))
413+}
414+
415+/// A `?starts_after=`/`?starts_before=` instant: unix milliseconds, negative
416+/// refused, absent left absent.
417+fn starts_bound_filter(field: &'static str, raw: Option<i64>) -> Result<Option<Timestamp>, AppError> {
418+ match raw {
419+ None => Ok(None),
420+ Some(value) if value < 0 => Err(AppError::Validation(ValidationError::Invalid {
421+ field,
422+ reason: "must not be negative",
423+ })),
424+ Some(value) => Ok(Some(Timestamp::from_millis(value))),
425+ }
426+}
427+
428+/// Optional list filters on the slots door. Absent, the response is the
429+/// unfiltered calendar exactly as it has always been.
430+#[derive(Debug, Deserialize, IntoParams)]
431+struct SlotFilter {
432+ /// Narrow to one teacher's slots: `me` for the caller, else a user id.
433+ #[param(example = "me")]
434+ teacher: Option<String>,
435+ /// Keep only slots starting at or after this unix-millisecond instant.
436+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
437+ starts_after: Option<i64>,
438+}
439+
440+impl SlotFilter {
441+ fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> {
442+ teacher_filter(self.teacher.as_deref(), caller)
443+ }
444+
445+ fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> {
446+ starts_bound_filter("starts_after", self.starts_after)
447+ }
448+}
449+
382450 /// List slots, earliest first. Teacher+ see their own calendar, past occurrences
383451 /// included; everyone else sees every slot that has not started yet — the
384452 /// bookable calendar, bounded exactly as booking is, so a slot already underway
@@ -390,6 +458,17 @@ async fn publish_slots(
390458 /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit
391459 /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope.
392460 ///
461+/// Optional filters narrow the answer without ever widening it. `?teacher=`
462+/// names one teacher — `me` for the caller, else a user id — and
463+/// `?starts_after=` (unix milliseconds, inclusive) keeps the windows that
464+/// start at or after the instant, in the SQL so the past is never loaded to
465+/// be thrown away. A teacher+ caller's universe is their own calendar, so
466+/// `teacher=me` reads the same as absent and naming another teacher is the
467+/// empty intersection: a colleague's slots, past ones included, stay
468+/// private. For everyone else the universe is the bookable calendar, so a
469+/// named teacher's upcoming slots are exactly what the absent call already
470+/// offered.
471+///
393472 /// Each slot carries its teacher's `PersonRef` (id, username, name) to *every*
394473 /// authenticated caller, parents included — deliberate, and not to be
395474 /// "tightened". A parent's three direct routes to that identity all refuse
@@ -406,10 +485,10 @@ async fn publish_slots(
406485 path = "/slots",
407486 tag = "appointments",
408487 security(("session_cookie" = [])),
409- params(PageParams),
488+ params(PageParams, SlotFilter),
410489 responses(
411490 (status = 200, description = "A page of slots (all of them when unpaged)", body = Page<SlotResponse>),
412- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
491+ (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
413492 (status = 401, description = "Not authenticated", body = ErrorResponse),
414493 ),
415494 )]
@@ -417,15 +496,39 @@ async fn list_slots(
417496 State(st): State<AppState>,
418497 CurrentUser(user): CurrentUser,
419498 Query(page): Query<PageParams>,
499+ Query(filter): Query<SlotFilter>,
420500 ) -> Result<Json<Page<SlotResponse>>, AppError> {
421501 let (limit, offset) = page.resolve()?;
502+ let narrow_to = filter.resolve_teacher(user.get_id())?;
503+ let starts_after = filter.resolve_starts_after()?;
422504 let (slots, people) = if user.get_role().at_least(Role::Teacher) {
423- (
424- service::appointment_slot::list_for_teacher(&st.db, user.get_id()).await?,
425- PersonRef::map_of(&[&user]),
426- )
505+ // The calendar arm's universe is the caller's own published rows,
506+ // past occurrences included. The `teacher` filter narrows inside it:
507+ // `me` is the caller's own calendar (the same rows as absent), and
508+ // naming anyone else is the empty intersection — which it must be,
509+ // or the param would hand over a colleague's calendar.
510+ match narrow_to {
511+ Some(other) if other != *user.get_id() => {
512+ (Vec::new(), PersonRef::map_of(&[&user]))
513+ }
514+ _ => (
515+ service::appointment_slot::list_calendar(
516+ &st.db,
517+ user.get_id(),
518+ starts_after,
519+ )
520+ .await?,
521+ PersonRef::map_of(&[&user]),
522+ ),
523+ }
427524 } else {
428- let mut slots = service::appointment_slot::list_upcoming(&st.db, Timestamp::now()).await?;
525+ let mut slots = service::appointment_slot::list_upcoming(
526+ &st.db,
527+ Timestamp::now(),
528+ narrow_to.as_ref(),
529+ starts_after,
530+ )
531+ .await?;
429532 // The teachers' live rows, not the slots' word for it: a demotion
430533 // leaves the calendar behind, and an inert slot must not be offered.
431534 // Keying the person map off that same read makes the filter free.
@@ -587,20 +690,98 @@ async fn book(
587690 ))
588691 }
589692
693+/// Optional list filters on the bookings door. Absent, the response is the
694+/// caller's listing exactly as it has always been.
695+#[derive(Debug, Deserialize, IntoParams)]
696+struct AppointmentFilter {
697+ /// Narrow to one booking state: `pending`, `approved`, `rejected` or
698+ /// `cancelled`.
699+ #[param(example = "pending")]
700+ status: Option<String>,
701+ /// Keep only meetings starting at or after this unix-millisecond instant.
702+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
703+ starts_after: Option<i64>,
704+ /// Keep only meetings starting before this unix-millisecond instant —
705+ /// exclusive, so `[starts_after, starts_before)` is a closed-open month.
706+ #[param(minimum = 0, example = 1_760_259_199_999_i64)]
707+ starts_before: Option<i64>,
708+ /// Narrow to bookings on one teacher's slots: `me` for the caller, else
709+ /// a user id.
710+ #[param(example = "me")]
711+ teacher: Option<String>,
712+}
713+
714+impl AppointmentFilter {
715+ /// The wire word against the closed vocabulary the rows store
716+ /// ([`AppointmentStatus::as_str`]): an unknown or blank word is a 400
717+ /// naming the field, never a silent whole-list read.
718+ fn resolve_status(&self) -> Result<Option<AppointmentStatus>, AppError> {
719+ const STATUSES: [AppointmentStatus; 4] = [
720+ AppointmentStatus::Pending,
721+ AppointmentStatus::Approved,
722+ AppointmentStatus::Rejected,
723+ AppointmentStatus::Cancelled,
724+ ];
725+ let Some(raw) = self.status.as_deref() else {
726+ return Ok(None);
727+ };
728+ let word = raw.trim();
729+ if word.is_empty() {
730+ return Err(AppError::Validation(ValidationError::Invalid {
731+ field: "status",
732+ reason: "must not be empty",
733+ }));
734+ }
735+ STATUSES
736+ .into_iter()
737+ .find(|status| status.as_str() == word)
738+ .map(Some)
739+ .ok_or_else(|| {
740+ AppError::Validation(ValidationError::Invalid {
741+ field: "status",
742+ reason: "must be one of: pending, approved, rejected, cancelled",
743+ })
744+ })
745+ }
746+
747+ fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> {
748+ starts_bound_filter("starts_after", self.starts_after)
749+ }
750+
751+ fn resolve_starts_before(&self) -> Result<Option<Timestamp>, AppError> {
752+ starts_bound_filter("starts_before", self.starts_before)
753+ }
754+
755+ fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> {
756+ teacher_filter(self.teacher.as_deref(), caller)
757+ }
758+}
759+
590760 /// List bookings, newest first. Students and parents see the ones they
591761 /// requested; teacher+ see the ones aimed at their own slots — their request
592762 /// inbox. Managers and admins read their own inbox too (they may still decide
593763 /// any booking by id). Paged via `?limit=&offset=` (omit `limit` for every
594764 /// booking); returns a `{items, total, limit, offset}` envelope.
765+///
766+/// Optional filters narrow the answer without ever widening it. `?status=`
767+/// is one of `pending`, `approved`, `rejected`, `cancelled`; `?starts_after=`
768+/// and `?starts_before=` (unix milliseconds) keep the meetings whose start
769+/// sits in `[after, before)` — a standing proposal's time when one stands,
770+/// the slot's window otherwise, so a booking whose slot is gone (no window
771+/// at all) is left out; `?teacher=` names the booked slot's teacher, `me` or
772+/// a user id, joined through the slot. A teacher+ caller's universe is their
773+/// own inbox, so `teacher=me` reads the same as absent and naming another
774+/// teacher is the empty intersection rather than a read of that teacher's
775+/// inbox.
595776 #[utoipa::path(
596777 get,
597778 path = "/",
598779 tag = "appointments",
599780 security(("session_cookie" = [])),
600- params(PageParams),
781+ params(PageParams, AppointmentFilter),
601782 responses(
602783 (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<AppointmentResponse>),
603- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
784+ (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
604785 (status = 401, description = "Not authenticated", body = ErrorResponse),
605786 ),
606787 )]
@@ -608,12 +789,44 @@ async fn list_appointments(
608789 State(st): State<AppState>,
609790 CurrentUser(user): CurrentUser,
610791 Query(page): Query<PageParams>,
792+ Query(filter): Query<AppointmentFilter>,
611793 ) -> Result<Json<Page<AppointmentResponse>>, AppError> {
612794 let (limit, offset) = page.resolve()?;
795+ let status = filter.resolve_status()?;
796+ let starts_after = filter.resolve_starts_after()?;
797+ let starts_before = filter.resolve_starts_before()?;
798+ let narrow_to = filter.resolve_teacher(user.get_id())?;
613799 let (rows, total) = if user.get_role().at_least(Role::Teacher) {
614- service::appointment::list_for_teacher(&st.db, user.get_id(), limit, offset).await?
800+ // The inbox arm's universe is the caller's own bookings; the
801+ // `teacher` filter narrows inside it, so naming another teacher is
802+ // the empty intersection — see the slots door, same rule.
803+ match narrow_to {
804+ Some(other) if other != *user.get_id() => (Vec::new(), 0),
805+ _ => {
806+ service::appointment::list_for_teacher(
807+ &st.db,
808+ user.get_id(),
809+ status,
810+ starts_after,
811+ starts_before,
812+ limit,
813+ offset,
814+ )
815+ .await?
816+ }
817+ }
615818 } else {
616- service::appointment::list_for_requester(&st.db, user.get_id(), limit, offset).await?
819+ service::appointment::list_for_requester(
820+ &st.db,
821+ user.get_id(),
822+ status,
823+ starts_after,
824+ starts_before,
825+ narrow_to.as_ref(),
826+ limit,
827+ offset,
828+ )
829+ .await?
617830 };
618831 // Join slots and people onto the page alone — the lookup shrinks with it.
619832 let items = appointment_responses(&rows, &st.db).await?;
@@ -951,4 +1164,405 @@ mod tests {
9511164 let boss = user("mudur", Role::Manager, &db).await;
9521165 assert!(can_manage(&slot, &boss));
9531166 }
1167+
1168+ // ---- the list filters ---------------------------------------------------
1169+
1170+ /// The handlers under test touch `db` alone, but [`AppState`] wants all
1171+ /// of its pieces — built here off the sandboxed per-test database.
1172+ async fn a_state(db: &Database) -> AppState {
1173+ AppState {
1174+ db: db.clone(),
1175+ tenants: crate::database::init_test_tenants().await,
1176+ files_path: std::env::temp_dir(),
1177+ cookie_secure: false,
1178+ rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
1179+ chatbot_limit: Default::default(),
1180+ rag_limit: Default::default(),
1181+ exam_presence: Default::default(),
1182+ board_hub: Default::default(),
1183+ ai: None,
1184+ metrics: crate::telemetry::Metrics::noop(),
1185+ }
1186+ }
1187+
1188+ /// One published slot at an absolute instant.
1189+ async fn a_slot(db: &Database, teacher: &UserId, starts_at: i64, ends_at: i64) {
1190+ service::appointment_slot::create(
1191+ db,
1192+ teacher,
1193+ Timestamp::from_millis(starts_at),
1194+ Timestamp::from_millis(ends_at),
1195+ None,
1196+ )
1197+ .await
1198+ .unwrap();
1199+ }
1200+
1201+ /// The slots door, unpaged.
1202+ async fn slots(st: &AppState, who: &User, filter: SlotFilter) -> Page<SlotResponse> {
1203+ list_slots(
1204+ State(st.clone()),
1205+ CurrentUser(who.clone()),
1206+ Query(PageParams {
1207+ limit: None,
1208+ offset: None,
1209+ }),
1210+ Query(filter),
1211+ )
1212+ .await
1213+ .unwrap()
1214+ .0
1215+ }
1216+
1217+ /// The bookings door, unpaged.
1218+ async fn bookings(
1219+ st: &AppState,
1220+ who: &User,
1221+ filter: AppointmentFilter,
1222+ ) -> Page<AppointmentResponse> {
1223+ list_appointments(
1224+ State(st.clone()),
1225+ CurrentUser(who.clone()),
1226+ Query(PageParams {
1227+ limit: None,
1228+ offset: None,
1229+ }),
1230+ Query(filter),
1231+ )
1232+ .await
1233+ .unwrap()
1234+ .0
1235+ }
1236+
1237+ /// Blank, malformed, and negative filter words are 400s naming the
1238+ /// field; `me` is the caller; a well-formed stranger stands (and names
1239+ /// an empty page — pinned by the handler-level tests).
1240+ #[test]
1241+ fn filter_words_refuse_blank_malformed_and_negative() {
1242+ let caller = UserId::generate();
1243+
1244+ for word in ["", " ", "not-a-uuid"] {
1245+ let filter = SlotFilter {
1246+ teacher: Some(word.into()),
1247+ starts_after: None,
1248+ };
1249+ assert!(
1250+ matches!(
1251+ filter.resolve_teacher(&caller),
1252+ Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "teacher"
1253+ ),
1254+ "`{word}` must refuse as `teacher`"
1255+ );
1256+ }
1257+ assert_eq!(
1258+ SlotFilter {
1259+ teacher: Some("me".into()),
1260+ starts_after: None,
1261+ }
1262+ .resolve_teacher(&caller)
1263+ .unwrap(),
1264+ Some(caller)
1265+ );
1266+ let stranger = UserId::generate();
1267+ assert_eq!(
1268+ SlotFilter {
1269+ teacher: Some(stranger.key()),
1270+ starts_after: None,
1271+ }
1272+ .resolve_teacher(&caller)
1273+ .unwrap(),
1274+ Some(stranger)
1275+ );
1276+
1277+ let filter = SlotFilter {
1278+ teacher: None,
1279+ starts_after: Some(-1),
1280+ };
1281+ assert!(matches!(
1282+ filter.resolve_starts_after(),
1283+ Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_after"
1284+ ));
1285+ assert_eq!(
1286+ SlotFilter {
1287+ teacher: None,
1288+ starts_after: Some(0),
1289+ }
1290+ .resolve_starts_after()
1291+ .unwrap()
1292+ .map(|instant| instant.as_millis()),
1293+ Some(0)
1294+ );
1295+
1296+ let filter = AppointmentFilter {
1297+ status: None,
1298+ starts_after: None,
1299+ starts_before: Some(-5),
1300+ teacher: None,
1301+ };
1302+ assert!(matches!(
1303+ filter.resolve_starts_before(),
1304+ Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_before"
1305+ ));
1306+
1307+ // The closed status vocabulary: exact wire words only — no case
1308+ // play, no blank, no synonym — mirroring what the rows store.
1309+ let status = |word: Option<&str>| AppointmentFilter {
1310+ status: word.map(str::to_string),
1311+ starts_after: None,
1312+ starts_before: None,
1313+ teacher: None,
1314+ };
1315+ assert_eq!(status(None).resolve_status().unwrap(), None);
1316+ assert_eq!(
1317+ status(Some(" pending ")).resolve_status().unwrap(),
1318+ Some(AppointmentStatus::Pending)
1319+ );
1320+ assert_eq!(
1321+ status(Some("cancelled")).resolve_status().unwrap(),
1322+ Some(AppointmentStatus::Cancelled)
1323+ );
1324+ for word in ["", " ", "APPROVED", "live", "confirmed"] {
1325+ assert!(
1326+ matches!(
1327+ status(Some(word)).resolve_status(),
1328+ Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "status"
1329+ ),
1330+ "`{word}` must refuse as `status`"
1331+ );
1332+ }
1333+ }
1334+
1335+ /// The slots door: absent filters are today's response per role —
1336+ /// teacher+ read their own calendar with the past included, everyone
1337+ /// else reads the bookable calendar — `teacher=me` is the caller's own
1338+ /// set, a named other teacher narrows the bookable calendar but never
1339+ /// opens a colleague's calendar, and `starts_after` cuts with `total`
1340+ /// reporting the filtered count.
1341+ #[tokio::test]
1342+ async fn slot_filters_narrow_without_widening() {
1343+ let (db, _leases) = init_test_db().await;
1344+ let st = a_state(&db).await;
1345+ let now = Timestamp::now().as_millis();
1346+ let ali = user("ali-ogretmen", Role::Teacher, &db).await;
1347+ let ayse = user("ayse-ogretmen", Role::Teacher, &db).await;
1348+ let veli = user("veli-veli", Role::Student, &db).await;
1349+
1350+ a_slot(&db, ali.get_id(), now - 10_000, now - 5_000).await; // ali's past
1351+ a_slot(&db, ali.get_id(), now + 5_000, now + 10_000).await;
1352+ a_slot(&db, ali.get_id(), now + 60_000, now + 90_000).await;
1353+ a_slot(&db, ayse.get_id(), now + 30_000, now + 40_000).await;
1354+
1355+ let none = || SlotFilter {
1356+ teacher: None,
1357+ starts_after: None,
1358+ };
1359+ let me = || SlotFilter {
1360+ teacher: Some("me".into()),
1361+ starts_after: None,
1362+ };
1363+ let of = |who: &UserId| SlotFilter {
1364+ teacher: Some(who.key()),
1365+ starts_after: None,
1366+ };
1367+
1368+ // Student, no filters: the bookable calendar — ali's past stays out,
1369+ // earliest first, exactly as the absent call has always answered.
1370+ let page = slots(&st, &veli, none()).await;
1371+ assert_eq!(page.total, 3);
1372+ let starts: Vec<i64> = page.items.iter().map(|slot| slot.starts_at).collect();
1373+ let mut sorted = starts.clone();
1374+ sorted.sort_unstable();
1375+ assert_eq!(starts, sorted);
1376+
1377+ // Student, teacher=me: they publish nothing — an empty page, not an
1378+ // error.
1379+ let page = slots(&st, &veli, me()).await;
1380+ assert_eq!((page.items.len(), page.total), (0, 0));
1381+
1382+ // Student, teacher=ali: exactly ali's upcoming pair — a narrowing of
1383+ // the calendar they may already see, his past slot still private.
1384+ let page = slots(&st, &veli, of(ali.get_id())).await;
1385+ assert_eq!(page.total, 2);
1386+ assert!(
1387+ page.items
1388+ .iter()
1389+ .all(|slot| slot.teacher.id == ali.get_id().key() && slot.starts_at > now)
1390+ );
1391+
1392+ // Student, teacher=<well-formed nobody>: an empty page, not a 404.
1393+ let page = slots(&st, &veli, of(&UserId::generate())).await;
1394+ assert_eq!((page.items.len(), page.total), (0, 0));
1395+
1396+ // Teacher, no filters: their own calendar, past occurrences
1397+ // included — today's arm.
1398+ let page = slots(&st, &ali, none()).await;
1399+ assert_eq!(page.total, 3);
1400+
1401+ // Teacher, teacher=me: the same calendar as absent.
1402+ let page = slots(&st, &ali, me()).await;
1403+ assert_eq!(page.total, 3);
1404+
1405+ // Teacher, teacher=ayse: the empty intersection. Naming a colleague
1406+ // must not hand over their calendar, past rows included.
1407+ let page = slots(&st, &ali, of(ayse.get_id())).await;
1408+ assert_eq!((page.items.len(), page.total), (0, 0));
1409+
1410+ // Teacher, starts_after=now: the past occurrence is cut in the SQL,
1411+ // and total is the filtered count.
1412+ let page = slots(
1413+ &st,
1414+ &ali,
1415+ SlotFilter {
1416+ teacher: None,
1417+ starts_after: Some(now),
1418+ },
1419+ )
1420+ .await;
1421+ assert_eq!(page.total, 2);
1422+ assert!(page.items.iter().all(|slot| slot.starts_at >= now));
1423+
1424+ // Both filters together, on the student arm.
1425+ let page = slots(
1426+ &st,
1427+ &veli,
1428+ SlotFilter {
1429+ teacher: Some(ayse.get_id().key()),
1430+ starts_after: Some(now),
1431+ },
1432+ )
1433+ .await;
1434+ assert_eq!(page.total, 1);
1435+ assert_eq!(page.items[0].starts_at, now + 30_000);
1436+ }
1437+
1438+ /// The bookings door: `status` and `starts_after` (the meeting's
1439+ /// effective start) narrow each side's own listing, `teacher` joins
1440+ /// through the slot, and a teacher+ caller naming another teacher gets
1441+ /// the empty intersection — never that teacher's inbox.
1442+ #[tokio::test]
1443+ async fn booking_filters_narrow_without_widening() {
1444+ let (db, _leases) = init_test_db().await;
1445+ let st = a_state(&db).await;
1446+ let now = Timestamp::now().as_millis();
1447+ let ali = user("ali-ogretmen", Role::Teacher, &db).await;
1448+ let ayse = user("ayse-ogretmen", Role::Teacher, &db).await;
1449+ let veli = user("veli-veli", Role::Student, &db).await;
1450+ let reason = AppointmentReason::try_new("görüşme").unwrap();
1451+
1452+ let ali_slot = service::appointment_slot::create(
1453+ &db,
1454+ ali.get_id(),
1455+ Timestamp::from_millis(now + 60_000),
1456+ Timestamp::from_millis(now + 120_000),
1457+ None,
1458+ )
1459+ .await
1460+ .unwrap();
1461+ let ayse_slot = service::appointment_slot::create(
1462+ &db,
1463+ ayse.get_id(),
1464+ Timestamp::from_millis(now + 200_000),
1465+ Timestamp::from_millis(now + 260_000),
1466+ None,
1467+ )
1468+ .await
1469+ .unwrap();
1470+ let pending =
1471+ service::appointment::book(&db, ali_slot.get_id(), veli.get_id(), reason.clone())
1472+ .await
1473+ .unwrap();
1474+ let approved =
1475+ service::appointment::book(&db, ayse_slot.get_id(), veli.get_id(), reason.clone())
1476+ .await
1477+ .unwrap();
1478+ service::appointment::approve(&db, approved.get_id(), ayse.get_id())
1479+ .await
1480+ .unwrap();
1481+
1482+ let none = || AppointmentFilter {
1483+ status: None,
1484+ starts_after: None,
1485+ starts_before: None,
1486+ teacher: None,
1487+ };
1488+ let status = |word: &str| AppointmentFilter {
1489+ status: Some(word.into()),
1490+ starts_after: None,
1491+ starts_before: None,
1492+ teacher: None,
1493+ };
1494+ let after = |millis: i64| AppointmentFilter {
1495+ status: None,
1496+ starts_after: Some(millis),
1497+ starts_before: None,
1498+ teacher: None,
1499+ };
1500+ let with_teacher = |who: &User| AppointmentFilter {
1501+ status: None,
1502+ starts_after: None,
1503+ starts_before: None,
1504+ teacher: Some(who.get_id().key()),
1505+ };
1506+
1507+ // Student, no filters: both bookings — today's response.
1508+ let page = bookings(&st, &veli, none()).await;
1509+ assert_eq!(page.total, 2);
1510+
1511+ // status: only the approved one; total is the filtered count.
1512+ let page = bookings(&st, &veli, status("approved")).await;
1513+ assert_eq!(page.total, 1);
1514+ assert_eq!(page.items[0].id, approved.get_id().key());
1515+ assert_eq!(page.items[0].status, "approved");
1516+
1517+ // A state nothing carries: an empty page, not an error.
1518+ let page = bookings(&st, &veli, status("rejected")).await;
1519+ assert_eq!((page.items.len(), page.total), (0, 0));
1520+
1521+ // teacher: joined through the slot — only the bookings on ali's.
1522+ let page = bookings(&st, &veli, with_teacher(&ali)).await;
1523+ assert_eq!(page.total, 1);
1524+ assert_eq!(page.items[0].id, pending.get_id().key());
1525+
1526+ // starts_after judges the meeting's effective start: the slot's
1527+ // window while no proposal stands.
1528+ let page = bookings(&st, &veli, after(now + 150_000)).await;
1529+ assert_eq!(page.total, 1);
1530+ assert_eq!(page.items[0].id, approved.get_id().key());
1531+
1532+ // starts_before through the door: the late meeting sits outside a
1533+ // window ending at now + 150_000, the early one inside it.
1534+ let page = bookings(
1535+ &st,
1536+ &veli,
1537+ AppointmentFilter {
1538+ status: None,
1539+ starts_after: None,
1540+ starts_before: Some(now + 150_000),
1541+ teacher: None,
1542+ },
1543+ )
1544+ .await;
1545+ assert_eq!(page.total, 1);
1546+ assert_eq!(page.items[0].id, pending.get_id().key());
1547+
1548+ // Teacher+ inbox: only the bookings aimed at their own slots.
1549+ let page = bookings(&st, &ali, none()).await;
1550+ assert_eq!(page.total, 1);
1551+ assert_eq!(page.items[0].id, pending.get_id().key());
1552+
1553+ // Inbox, teacher=me: the same rows.
1554+ let page = bookings(&st, &ali, with_teacher(&ali)).await;
1555+ assert_eq!(page.total, 1);
1556+
1557+ // Inbox, teacher=ayse: the empty intersection — never her inbox.
1558+ let page = bookings(&st, &ali, with_teacher(&ayse)).await;
1559+ assert_eq!((page.items.len(), page.total), (0, 0));
1560+
1561+ // Inbox, starts_after: ali's meeting is the earlier one, so a cut
1562+ // past it empties his inbox while ayse keeps hers.
1563+ let page = bookings(&st, &ali, after(now + 150_000)).await;
1564+ assert_eq!((page.items.len(), page.total), (0, 0));
1565+ let page = bookings(&st, &ayse, after(now + 150_000)).await;
1566+ assert_eq!(page.total, 1);
1567+ }
9541568 }
src/web/bank_questions.rsmodified+117 -6
@@ -168,6 +168,44 @@ struct BankQuestionFilter {
168168 visibility: Option<String>,
169169 }
170170
171+impl BankQuestionFilter {
172+ /// Validate + canonicalize: a malformed `subject`/`owner` key is a 400
173+ /// naming the field, never the nil id silently matching nothing — same
174+ /// as [`super::offerings::OfferingFilter`]. `owner=me` is the caller.
175+ fn resolve(&self, caller: &UserId) -> Result<(Option<SubjectId>, Option<UserId>), AppError> {
176+ let subject = match self.subject.as_deref().map(str::trim) {
177+ None => None,
178+ Some(key) => {
179+ let id = SubjectId::from_key(key);
180+ if id.uuid().is_nil() {
181+ return Err(ValidationError::Invalid {
182+ field: "subject",
183+ reason: "must be a hyphenated uuid",
184+ }
185+ .into());
186+ }
187+ Some(id)
188+ }
189+ };
190+ let owner = match self.owner.as_deref().map(str::trim) {
191+ None => None,
192+ Some("me") => Some(*caller),
193+ Some(key) => {
194+ let id = UserId::from_key(key);
195+ if id.uuid().is_nil() {
196+ return Err(ValidationError::Invalid {
197+ field: "owner",
198+ reason: "must be a hyphenated uuid",
199+ }
200+ .into());
201+ }
202+ Some(id)
203+ }
204+ };
205+ Ok((subject, owner))
206+ }
207+}
208+
171209 /// A bank template as its readers see it — `correct` included (teacher+ only,
172210 /// so the answer key is theirs to see). Its images, if any, are fetched
173211 /// through the image endpoints.
@@ -482,6 +520,10 @@ async fn create_question(
482520 /// carries the resolved `subject_name`/`owner_name` so a client needn't look
483521 /// them up per row, plus `used_count` — how many exam questions were copied out
484522 /// of that template (one grouped query for the page, not one per row).
523+///
524+/// A `subject`/`owner` key that is empty or not a hyphenated uuid is a 400
525+/// naming the field; a well-formed id that names nothing is just an empty
526+/// page.
485527 #[utoipa::path(
486528 get,
487529 path = "/",
@@ -490,7 +532,7 @@ async fn create_question(
490532 params(BankQuestionFilter, PageParams),
491533 responses(
492534 (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page<BankQuestionResponse>),
493- (status = 400, description = "Invalid limit, offset, or visibility", body = ErrorResponse),
535+ (status = 400, description = "Invalid limit, offset, subject, owner, or visibility", body = ErrorResponse),
494536 (status = 401, description = "Not authenticated", body = ErrorResponse),
495537 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
496538 ),
@@ -502,11 +544,7 @@ async fn list_questions(
502544 Query(page): Query<PageParams>,
503545 ) -> Result<Json<Page<BankQuestionResponse>>, AppError> {
504546 let (limit, offset) = page.resolve()?;
505- let subject = filter.subject.as_deref().map(SubjectId::from_key);
506- let owner = filter.owner.as_deref().map(|owner| match owner {
507- "me" => *user.get_id(),
508- id => UserId::from_key(id),
509- });
547+ let (subject, owner) = filter.resolve(user.get_id())?;
510548 // Same newtype the PATCH validates against, so an unknown shelf is the same
511549 // 400 ("visibility must be private or school") on both routes.
512550 let visibility = filter
@@ -1018,4 +1056,77 @@ mod tests {
10181056 assert!(!can_see(&question, &student));
10191057 assert!(can_see(&question, &admin));
10201058 }
1059+
1060+ /// The field a filter's validation error names, or a panic.
1061+ fn invalid_field(result: Result<(Option<SubjectId>, Option<UserId>), AppError>) -> &'static str {
1062+ match result {
1063+ Err(AppError::Validation(ValidationError::Invalid { field, .. })) => field,
1064+ other => panic!("expected a field validation error, got {other:?}"),
1065+ }
1066+ }
1067+
1068+ /// A malformed or empty `subject`/`owner` key is a 400 naming the field —
1069+ /// never the nil id silently matching nothing. `owner=me` is the caller,
1070+ /// and a well-formed key passes through unchanged.
1071+ #[tokio::test]
1072+ async fn subject_and_owner_keys_are_validated() {
1073+ let (db, _leases) = init_test_db().await;
1074+ let caller = user("ogretmen", Role::Teacher, &db).await;
1075+
1076+ let filter = |subject: Option<&str>, owner: Option<&str>| BankQuestionFilter {
1077+ subject: subject.map(str::to_string),
1078+ owner: owner.map(str::to_string),
1079+ q: None,
1080+ visibility: None,
1081+ };
1082+
1083+ assert_eq!(
1084+ invalid_field(filter(Some("not-a-uuid"), None).resolve(caller.get_id())),
1085+ "subject"
1086+ );
1087+ assert_eq!(
1088+ invalid_field(filter(Some(""), None).resolve(caller.get_id())),
1089+ "subject"
1090+ );
1091+ assert_eq!(
1092+ invalid_field(filter(None, Some("not-a-uuid")).resolve(caller.get_id())),
1093+ "owner"
1094+ );
1095+ assert_eq!(
1096+ invalid_field(filter(None, Some(" ")).resolve(caller.get_id())),
1097+ "owner"
1098+ );
1099+
1100+ // `me` resolves to the caller; a well-formed key passes through.
1101+ let (_, owner) = filter(None, Some("me")).resolve(caller.get_id()).unwrap();
1102+ assert_eq!(owner, Some(*caller.get_id()));
1103+ let well_formed = "019732e3-7b00-7000-8000-00000000dead";
1104+ let (subject, owner) = filter(Some(well_formed), Some(well_formed))
1105+ .resolve(caller.get_id())
1106+ .unwrap();
1107+ assert_eq!(subject.map(|s| s.uuid()), Some(UserId::from_key(well_formed).uuid()));
1108+ assert_eq!(owner.map(|o| o.uuid()), Some(UserId::from_key(well_formed).uuid()));
1109+ }
1110+
1111+ /// A well-formed id that names nothing is a 200 with an empty page and
1112+ /// `total` 0 — only a malformed key is a 400.
1113+ #[tokio::test]
1114+ async fn a_well_formed_but_unmatched_owner_is_an_empty_page() {
1115+ let (db, _leases) = init_test_db().await;
1116+ let stranger = UserId::from_key("019732e3-7b00-7000-8000-00000000dead");
1117+ let (items, total) = bank_question::list(
1118+ &db,
1119+ None,
1120+ Some(&stranger),
1121+ None,
1122+ None,
1123+ None,
1124+ None,
1125+ 0,
1126+ )
1127+ .await
1128+ .unwrap();
1129+ assert!(items.is_empty());
1130+ assert_eq!(total, 0);
1131+ }
10211132 }
src/web/boards.rsmodified+18 -2
@@ -212,6 +212,11 @@ struct ListFilter {
212212 /// for both. A closed board is never deleted, so this is how a heavy
213213 /// creator trims a list of retired boards.
214214 open: Option<bool>,
215+ /// Free-text search over the title: a case- and diacritic-insensitive
216+ /// substring (`geometri` finds `Geometri`). Literal text — `%` and `_`
217+ /// carry no special meaning. Blank means no search.
218+ #[param(example = "geometri")]
219+ q: Option<String>,
215220 }
216221
217222 /// Every board the caller may open — the ones they created and the ones they
@@ -223,6 +228,10 @@ struct ListFilter {
223228 /// that has spent its lifetime stroke budget but was never drawn on again, are
224229 /// both still open — the closing stamp is only ever written by `/close` or by
225230 /// the append that the lifetime cap refuses.
231+///
232+/// `?q=` narrows further by title: a case- and diacritic-insensitive
233+/// substring, composed with `open`; `total` counts the matches. Blank means
234+/// no search.
226235 #[utoipa::path(
227236 get,
228237 path = "/",
@@ -243,8 +252,15 @@ async fn list_boards(
243252 Query(page): Query<PageParams>,
244253 ) -> Result<Json<Page<BoardResponse>>, AppError> {
245254 let (limit, offset) = page.resolve()?;
246- let (boards, total) =
247- board::list_for_user(&st.db, user.get_id(), filter.open, limit, offset).await?;
255+ let (boards, total) = board::list_for_user(
256+ &st.db,
257+ user.get_id(),
258+ filter.open,
259+ filter.q.as_deref(),
260+ limit,
261+ offset,
262+ )
263+ .await?;
248264 let items = boards.iter().map(BoardResponse::new).collect();
249265 Ok(Json(Page::new(items, total, limit, offset)))
250266 }
src/web/course_notes.rsmodified+86 -3
@@ -27,7 +27,7 @@ use crate::domain::course_note_file::{
2727 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
2828 };
2929 use crate::domain::rag_output::{RagOutput, RagOutputId};
30-use crate::error::{AppError, ErrorResponse};
30+use crate::error::{AppError, ErrorResponse, ValidationError};
3131 use crate::module::Module;
3232 use crate::service;
3333 use crate::service::course::{can_manage_course, can_view_course};
@@ -160,9 +160,40 @@ struct CourseFilter {
160160 course: String,
161161 }
162162
163+impl CourseFilter {
164+ /// Validate: `course` is required, so an empty key is a 400 ("must not
165+ /// be empty") and a non-uuid is a 400 naming the field — never the nil
166+ /// id silently 404ing as a missing course. A well-formed id that names
167+ /// no course stays a 404: the course read below must succeed for the
168+ /// auth check.
169+ fn resolve(&self) -> Result<CourseId, AppError> {
170+ let key = self.course.trim();
171+ if key.is_empty() {
172+ return Err(ValidationError::Invalid {
173+ field: "course",
174+ reason: "must not be empty",
175+ }
176+ .into());
177+ }
178+ let id = CourseId::from_key(key);
179+ if id.uuid().is_nil() {
180+ return Err(ValidationError::Invalid {
181+ field: "course",
182+ reason: "must be a hyphenated uuid",
183+ }
184+ .into());
185+ }
186+ Ok(id)
187+ }
188+}
189+
163190 /// List a course's notes, newest first. Visible to whoever can view the
164191 /// course (its creator, a manager/admin, or anyone the course reaches).
165192 /// Paged via `?limit=&offset=`.
193+///
194+/// `course` must be a hyphenated uuid: empty or malformed is a 400 naming
195+/// the field; a well-formed id that names no course stays a 404, since the
196+/// course must be read for the auth check.
166197 #[utoipa::path(
167198 get,
168199 path = "/",
@@ -171,7 +202,7 @@ struct CourseFilter {
171202 params(CourseFilter, PageParams),
172203 responses(
173204 (status = 200, description = "A page of the course's notes (all of them when unpaged)", body = Page<CourseNoteResponse>),
174- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
205+ (status = 400, description = "Invalid limit, offset, or course key", body = ErrorResponse),
175206 (status = 401, description = "Not authenticated", body = ErrorResponse),
176207 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
177208 (status = 404, description = "Course not found", body = ErrorResponse),
@@ -183,7 +214,8 @@ async fn list(
183214 Query(filter): Query<CourseFilter>,
184215 Query(page): Query<PageParams>,
185216 ) -> Result<Json<Page<CourseNoteResponse>>, AppError> {
186- let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course))
217+ let course_id = filter.resolve()?;
218+ let course = crate::service::course::read(&st.db, &course_id)
187219 .await?
188220 .ok_or(AppError::NotFound)?;
189221 if !can_view_course(&course, &user, &st.db).await? {
@@ -720,3 +752,54 @@ async fn reindex_rag(
720752 spawn_index(&st, &tenant, note);
721753 Ok(StatusCode::ACCEPTED.into_response())
722754 }
755+
756+#[cfg(test)]
757+mod tests {
758+ use super::*;
759+
760+ /// `course` is required and must be a real key: empty is "must not be
761+ /// empty", a non-uuid is "must be a hyphenated uuid" — never the nil id
762+ /// silently 404ing as a missing course. A well-formed id passes through,
763+ /// and one that names no course stays on the 404 path (the course read
764+ /// the handler runs next must miss for the auth check).
765+ #[tokio::test]
766+ async fn course_key_is_validated_before_the_course_read() {
767+ let (db, _leases) = crate::database::init_test_db().await;
768+ let filter = |course: &str| CourseFilter {
769+ course: course.to_string(),
770+ };
771+
772+ match filter("").resolve() {
773+ Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
774+ assert_eq!(field, "course");
775+ assert_eq!(reason, "must not be empty");
776+ }
777+ other => panic!("expected an empty-course error, got {other:?}"),
778+ }
779+ match filter(" ").resolve() {
780+ Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
781+ assert_eq!(field, "course");
782+ assert_eq!(reason, "must not be empty");
783+ }
784+ other => panic!("expected a blank-course error, got {other:?}"),
785+ }
786+ match filter("not-a-uuid").resolve() {
787+ Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
788+ assert_eq!(field, "course");
789+ assert_eq!(reason, "must be a hyphenated uuid");
790+ }
791+ other => panic!("expected a malformed-course error, got {other:?}"),
792+ }
793+
794+ // A well-formed id passes through; if it names no course, the read
795+ // the handler does next misses and the route answers 404.
796+ let id = filter("019732e3-7b00-7000-8000-00000000dead")
797+ .resolve()
798+ .unwrap();
799+ assert_eq!(
800+ id.uuid(),
801+ uuid::Uuid::parse_str("019732e3-7b00-7000-8000-00000000dead").unwrap()
802+ );
803+ assert!(service::course::read(&db, &id).await.unwrap().is_none());
804+ }
805+}
src/web/courses.rsmodified+327 -5
@@ -3,7 +3,7 @@ use axum::Json;
33 use axum::extract::{Path, Query};
44 use axum::http::StatusCode;
55 use serde::{Deserialize, Serialize};
6-use utoipa::ToSchema;
6+use utoipa::{IntoParams, ToSchema};
77 use utoipa_axum::router::OpenApiRouter;
88 use utoipa_axum::routes;
99
@@ -17,6 +17,7 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou
1717 use crate::domain::course_offering::CourseOfferingId;
1818 use crate::domain::role::Role;
1919 use crate::domain::subject::{SubjectDescription, SubjectName};
20+use crate::domain::text_fold::search_fold;
2021 use crate::domain::user::{User, UserId};
2122 use crate::error::{AppError, ErrorResponse};
2223 use crate::service;
@@ -133,8 +134,24 @@ fn owns_course(course: &Course, user: &User) -> bool {
133134 /// homework. Below `teacher` a course is visible only the way it is to any
134135 /// other student: by enrollment.
135136 pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> {
137+ visible_courses_filtered(user, db, None, None, None).await
138+}
139+
140+/// [`visible_courses`] narrowed by the `GET /courses` filters. The filters
141+/// ride *after* the visibility union and *before* any paging, so a filter can
142+/// only ever narrow what the caller already reaches and `total` is the
143+/// filtered length. For a manager the filters go into the catalog query
144+/// itself ([`crate::service::course::list_filtered`]); below manager the
145+/// union is Rust, so the same text fold filters the merged list in memory.
146+pub(crate) async fn visible_courses_filtered(
147+ user: &User,
148+ db: &Database,
149+ kind: Option<CourseKind>,
150+ q: Option<&str>,
151+ taught: Option<bool>,
152+) -> Result<Vec<Course>, AppError> {
136153 if user.get_role().at_least(Role::Manager) {
137- return service::course::list_all(db).await;
154+ return service::course::list_filtered(db, kind, q, taught).await;
138155 }
139156 let mut courses = if user.get_role().at_least(Role::Teacher) {
140157 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<Vec<Co
154171 }
155172 // Both sources come newest-first; re-sort so the merged list is too.
156173 courses.sort_by_key(|course| std::cmp::Reverse(course.get_id().key()));
174+ // The same fold both sides of the manager arm's SQL uses, so a `q`
175+ // matches identically above and below manager; blank means no filter.
176+ let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
177+ courses.retain(|course| {
178+ kind.as_ref().is_none_or(|want| course.get_kind() == want)
179+ && taught.is_none_or(|taught| (course.get_class_course_count() > 0) == taught)
180+ && needle.as_deref().is_none_or(|needle| {
181+ search_fold(course.get_title().as_str()).contains(needle)
182+ || search_fold(course.get_description().as_str()).contains(needle)
183+ })
184+ });
157185 Ok(courses)
158186 }
159187
@@ -391,29 +419,75 @@ async fn create_course(
391419 ))
392420 }
393421
422+/// The `GET /courses` filters, both optional and combinable. They narrow the
423+/// caller's visible set — they never widen it: a student filtering by `kind`
424+/// still sees only the courses they reach.
425+#[derive(Debug, Deserialize, IntoParams)]
426+struct CourseListFilter {
427+ /// Narrow to one kind: `course` (a regular class), `study` (a supervised
428+ /// study session), or `club`. Omit for every kind.
429+ #[param(example = "course")]
430+ kind: Option<String>,
431+ /// Case- and diacritic-insensitive fragment of the title or description.
432+ /// Omit — or leave blank — to filter nothing; `%` and `_` are literal.
433+ #[param(example = "matematik")]
434+ q: Option<String>,
435+ /// Keep only courses taught somewhere (`true`, `class_course_count > 0`)
436+ /// or nowhere yet (`false`, `= 0`). Omit for both.
437+ #[param(example = true)]
438+ taught: Option<bool>,
439+}
440+
441+impl CourseListFilter {
442+ /// `kind` parses through the write-path validator, so an unknown or empty
443+ /// spelling is the same 400 a create/PATCH gets; `taught` needs no parse —
444+ /// the query extractor itself 400s a `?taught=` that is not `true`/`false`,
445+ /// naming the field; `q` passes through raw — each arm trims, folds and
446+ /// blanks it identically.
447+ fn resolve(self) -> Result<(Option<CourseKind>, Option<String>, Option<bool>), AppError> {
448+ let kind = match self.kind {
449+ Some(kind) => Some(CourseKind::try_new(&kind)?),
450+ None => None,
451+ };
452+ Ok((kind, self.q, self.taught))
453+ }
454+}
455+
394456 /// List the catalog courses visible to the caller: every course for manager+,
395457 /// otherwise the courses they teach somewhere plus the ones they're enrolled
396458 /// in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a
397459 /// `{items, total, limit, offset}` envelope.
460+///
461+/// `kind` narrows to one flavor, `q` filters by a case- and
462+/// diacritic-insensitive fragment of the title or description (blank =
463+/// unfiltered), and `taught` keeps only the courses a class section teaches
464+/// (`true`) or none yet (`false`). All apply to the caller's visible set
465+/// only — after the visibility gate and before the window is cut — so
466+/// `total` is the filtered length.
398467 #[utoipa::path(
399468 get,
400469 path = "/",
401470 tag = "courses",
402471 security(("session_cookie" = [])),
403- params(PageParams),
472+ params(CourseListFilter, PageParams),
404473 responses(
405474 (status = 200, description = "A page of the caller's visible courses (all of them when unpaged)", body = Page<CourseResponse>),
406- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
475+ (status = 400, description = "Unknown or empty kind, a `taught` that is not true/false, or invalid limit or offset", body = ErrorResponse),
407476 (status = 401, description = "Not authenticated", body = ErrorResponse),
408477 ),
409478 )]
410479 async fn list_courses(
411480 State(st): State<AppState>,
412481 CurrentUser(user): CurrentUser,
482+ Query(filter): Query<CourseListFilter>,
413483 Query(page): Query<PageParams>,
414484 ) -> Result<Json<Page<CourseResponse>>, AppError> {
415485 let (limit, offset) = page.resolve()?;
416- let courses = visible_courses(&user, &st.db).await?;
486+ let (kind, q, taught) = filter.resolve()?;
487+ // The filters ride inside the visible set — SQL for a manager, the
488+ // union's tail in Rust below one — so total is the filtered length
489+ // before the window is cut.
490+ let courses = visible_courses_filtered(&user, &st.db, kind, q.as_deref(), taught).await?;
417491 let total = courses.len() as i64;
418492 // Paged in the web layer: the visible set is a Rust union of two lists.
419493 let window = paginate(&courses, limit, offset);
@@ -883,6 +957,254 @@ mod tests {
883957 .unwrap()
884958 }
885959
960+ /// A catalog course with caller-chosen fields, minted through the real
961+ /// create path.
962+ async fn shaped_course(
963+ creator: &User,
964+ db: &Database,
965+ title: &str,
966+ description: &str,
967+ kind: &str,
968+ ) -> Course {
969+ service::course::create(
970+ db,
971+ creator.get_id(),
972+ CourseTitle::try_new(title).unwrap(),
973+ CourseDescription::try_new(description).unwrap(),
974+ CourseKind::try_new(kind).unwrap(),
975+ )
976+ .await
977+ .unwrap()
978+ }
979+
980+ fn titles(courses: &[Course]) -> Vec<&str> {
981+ courses
982+ .iter()
983+ .map(|course| course.get_title().as_str())
984+ .collect()
985+ }
986+
987+ fn a_kind(kind: &str) -> CourseKind {
988+ CourseKind::try_new(kind).unwrap()
989+ }
990+
991+ /// An unknown or empty `kind` is the write path's own 400, naming the
992+ /// field; `q` passes through verbatim (each arm folds it).
993+ #[tokio::test]
994+ async fn the_kind_filter_parses_through_the_write_path() {
995+ for kind in ["nope", ""] {
996+ let err = CourseListFilter {
997+ kind: Some(kind.to_string()),
998+ q: None,
999+ taught: None,
1000+ }
1001+ .resolve()
1002+ .unwrap_err();
1003+ assert!(
1004+ matches!(
1005+ &err,
1006+ AppError::Validation(crate::error::ValidationError::Invalid { field, .. })
1007+ if *field == "kind"
1008+ ),
1009+ "{kind:?}: {err:?}"
1010+ );
1011+ }
1012+ let (kind, q, taught) = CourseListFilter {
1013+ kind: Some("club".to_string()),
1014+ q: Some(" ".to_string()),
1015+ taught: None,
1016+ }
1017+ .resolve()
1018+ .unwrap();
1019+ assert_eq!(kind.as_ref().map(CourseKind::as_str), Some("club"));
1020+ assert_eq!(q.as_deref(), Some(" "));
1021+ assert_eq!(taught, None);
1022+ }
1023+
1024+ /// Manager arm: kind and q narrow the catalog, total is the filtered
1025+ /// length, a miss is an empty list, and `%`/`_` are literal.
1026+ #[tokio::test]
1027+ async fn kind_and_q_narrow_the_manager_catalog() {
1028+ let (db, _leases) = init_test_db().await;
1029+ let boss = user("boss", Role::Manager, &db).await;
1030+ shaped_course(&boss, &db, "Matematik", "Cebir ve Geometri", "course").await;
1031+ shaped_course(&boss, &db, "Satranç Kulübü", "", "club").await;
1032+ shaped_course(&boss, &db, "Biyoloji Etüdü", "canlı yayın", "study").await;
1033+ // "Matematik" is taught by a real class section; the other two are
1034+ // attached nowhere, so the taught axis has both values in play.
1035+ let class = crate::db::class_group::create(
1036+ &db,
1037+ boss.get_id(),
1038+ crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
1039+ crate::domain::grade::GradeLevel::new(9).unwrap(),
1040+ None,
1041+ None,
1042+ )
1043+ .await
1044+ .unwrap();
1045+ let matematik = visible_courses_filtered(&boss, &db, None, None, None)
1046+ .await
1047+ .unwrap()
1048+ .into_iter()
1049+ .find(|course| course.get_title().as_str() == "Matematik")
1050+ .unwrap();
1051+ service::class_course::attach(&db, class.get_id(), matematik.get_id(), boss.get_id())
1052+ .await
1053+ .unwrap();
1054+
1055+ // No filters: the whole catalog, newest first — today's response,
1056+ // taught and untaught alike.
1057+ let all = visible_courses_filtered(&boss, &db, None, None, None)
1058+ .await
1059+ .unwrap();
1060+ assert_eq!(
1061+ titles(&all),
1062+ vec!["Biyoloji Etüdü", "Satranç Kulübü", "Matematik"]
1063+ );
1064+
1065+ // kind: exact flavor only.
1066+ let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, None)
1067+ .await
1068+ .unwrap();
1069+ assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]);
1070+
1071+ // q: title fragment, case- and diacritic-insensitive.
1072+ let q = visible_courses_filtered(&boss, &db, None, Some("SATRANÇ"), None)
1073+ .await
1074+ .unwrap();
1075+ assert_eq!(titles(&q), vec!["Satranç Kulübü"]);
1076+ // q: description fragment too.
1077+ let q = visible_courses_filtered(&boss, &db, None, Some("canlı"), None)
1078+ .await
1079+ .unwrap();
1080+ assert_eq!(titles(&q), vec!["Biyoloji Etüdü"]);
1081+ // q: `position`, not `LIKE` — no wildcard surprises.
1082+ for wildcard in ["%", "_"] {
1083+ let q = visible_courses_filtered(&boss, &db, None, Some(wildcard), None)
1084+ .await
1085+ .unwrap();
1086+ assert!(q.is_empty(), "{wildcard:?} acted as a wildcard");
1087+ }
1088+
1089+ // Combined filters AND; a miss is 200 empty, not an error.
1090+ let miss =
1091+ visible_courses_filtered(&boss, &db, Some(a_kind("course")), Some("satranç"), None)
1092+ .await
1093+ .unwrap();
1094+ assert!(miss.is_empty());
1095+ let hit = visible_courses_filtered(&boss, &db, Some(a_kind("study")), Some("CANLI"), None)
1096+ .await
1097+ .unwrap();
1098+ assert_eq!(titles(&hit), vec!["Biyoloji Etüdü"]);
1099+
1100+ // Blank q is no filter — the unfiltered catalog again.
1101+ let blank = visible_courses_filtered(&boss, &db, None, Some(" "), None)
1102+ .await
1103+ .unwrap();
1104+ assert_eq!(titles(&blank), titles(&all));
1105+
1106+ // taught: true keeps the attached one, false the unattached two, and
1107+ // it composes with kind.
1108+ let taught = visible_courses_filtered(&boss, &db, None, None, Some(true))
1109+ .await
1110+ .unwrap();
1111+ assert_eq!(titles(&taught), vec!["Matematik"]);
1112+ let untaught = visible_courses_filtered(&boss, &db, None, None, Some(false))
1113+ .await
1114+ .unwrap();
1115+ assert_eq!(titles(&untaught), vec!["Biyoloji Etüdü", "Satranç Kulübü"]);
1116+ let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(false))
1117+ .await
1118+ .unwrap();
1119+ assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]);
1120+ let miss = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(true))
1121+ .await
1122+ .unwrap();
1123+ assert!(miss.is_empty());
1124+
1125+ // The window is cut after the filter: one course per page while the
1126+ // total stays the filtered length (the handler's `total` is
1127+ // `courses.len()` taken *before* `paginate`).
1128+ let dersler = visible_courses_filtered(&boss, &db, Some(a_kind("course")), None, None)
1129+ .await
1130+ .unwrap();
1131+ assert_eq!(dersler.len(), 1);
1132+ assert_eq!(paginate(&dersler, Some(1), 0).len(), 1);
1133+ }
1134+
1135+ /// Below manager the filters ride the Rust union: they can narrow what a
1136+ /// student reaches but never widen it.
1137+ #[tokio::test]
1138+ async fn filters_narrow_but_never_widen_a_students_visible_set() {
1139+ let (db, _leases) = init_test_db().await;
1140+ let boss = user("boss2", Role::Manager, &db).await;
1141+ let student = user("ogrenci", Role::Student, &db).await;
1142+ let (instance, _ders) = crate::db::course::a_test_instance(&db).await;
1143+ shaped_course(&boss, &db, "Satranç Kulübü", "zeka oyunu", "club").await;
1144+ service::enrollment::enroll(&db, &instance, student.get_id(), boss.get_id())
1145+ .await
1146+ .unwrap();
1147+
1148+ // Unfiltered: only the enrolled ders — the club is real but not theirs.
1149+ let mine = visible_courses_filtered(&student, &db, None, None, None)
1150+ .await
1151+ .unwrap();
1152+ assert_eq!(titles(&mine), vec!["test course"]);
1153+
1154+ // kind=club: the club exists in the catalog, the student still sees none.
1155+ let clubs = visible_courses_filtered(&student, &db, Some(a_kind("club")), None, None)
1156+ .await
1157+ .unwrap();
1158+ assert!(clubs.is_empty());
1159+ // q over the club's own title finds nothing they cannot reach either.
1160+ let q = visible_courses_filtered(&student, &db, None, Some("satranç"), None)
1161+ .await
1162+ .unwrap();
1163+ assert!(q.is_empty());
1164+
1165+ // taught: their ders is taught (the attached instance), the club is
1166+ // not — the axis narrows both ways without widening anything.
1167+ let taught = visible_courses_filtered(&student, &db, None, None, Some(true))
1168+ .await
1169+ .unwrap();
1170+ assert_eq!(titles(&taught), vec!["test course"]);
1171+ let untaught = visible_courses_filtered(&student, &db, None, None, Some(false))
1172+ .await
1173+ .unwrap();
1174+ assert!(untaught.is_empty());
1175+
1176+ // Their own ders survives both filters.
1177+ let dersler = visible_courses_filtered(&student, &db, Some(a_kind("course")), None, None)
1178+ .await
1179+ .unwrap();
1180+ assert_eq!(titles(&dersler), vec!["test course"]);
1181+ let q = visible_courses_filtered(&student, &db, None, Some("TEST"), None)
1182+ .await
1183+ .unwrap();
1184+ assert_eq!(titles(&q), vec!["test course"]);
1185+ }
1186+
1187+ /// `?taught=` present but empty is refused by the query extractor itself —
1188+ /// a 400 naming the field; only `true`/`false` parse.
1189+ #[test]
1190+ fn an_empty_taught_is_rejected_naming_the_field() {
1191+ let uri = axum::http::Uri::from_static("/courses?taught=");
1192+ let err = Query::<CourseListFilter>::try_from_uri(&uri).unwrap_err();
1193+ assert!(err.to_string().contains("taught"), "{err}");
1194+ for ok in [
1195+ "/courses?taught=true",
1196+ "/courses?taught=false",
1197+ "/courses?q=x",
1198+ "/courses",
1199+ ] {
1200+ let uri = axum::http::Uri::from_static(ok);
1201+ assert!(
1202+ Query::<CourseListFilter>::try_from_uri(&uri).is_ok(),
1203+ "{ok:?} refused"
1204+ );
1205+ }
1206+ }
1207+
8861208 /// The leak: `creator` is a historical column that demotion never sweeps,
8871209 /// so the grant itself has to re-read the live role on every call.
8881210 #[tokio::test]
src/web/events.rsmodified+20 -24
@@ -24,24 +24,10 @@ use crate::service;
2424 use crate::state::AppState;
2525
2626 use super::{
27- CurrentUser, Page, PageParams, PersonRef, RequireTeacher, Scheduled, WindowParams,
28- check_not_past, check_time_range, paginate, person_map, set_or_clear,
27+ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, WindowParams, check_not_past,
28+ check_time_range, paginate, person_map, set_or_clear,
2929 };
3030
31-impl Scheduled for Event {
32- fn starts_at_ms(&self) -> Option<i64> {
33- self.get_starts_at().map(|at| at.as_millis())
34- }
35-
36- fn ends_at_ms(&self) -> Option<i64> {
37- self.get_ends_at().map(|at| at.as_millis())
38- }
39-
40- fn order_key(&self) -> String {
41- self.get_id().key()
42- }
43-}
44-
4531 pub fn routes() -> OpenApiRouter<AppState> {
4632 OpenApiRouter::new()
4733 .routes(routes!(create_event, list_events))
@@ -358,7 +344,10 @@ async fn create_event(
358344 /// milliseconds) narrows the list to upcoming/unfinished events and flips the
359345 /// order to ascending by schedule, so `?ends_after=<now>&limit=20` returns the
360346 /// twenty *soonest* events rather than the twenty newest-created. Events with
361-/// no schedule are excluded by either parameter.
347+/// no schedule are excluded by either parameter. `?starts_before=` /
348+/// `?ends_before=` are the mirror bounds (strictly before); with any bound
349+/// set the page, the count, and the window share one SQL `WHERE`, so a
350+/// filtered page never decodes the events it skips.
362351 #[utoipa::path(
363352 get,
364353 path = "/",
@@ -378,13 +367,20 @@ async fn list_events(
378367 Query(page): Query<PageParams>,
379368 ) -> Result<Json<Page<EventResponse>>, AppError> {
380369 let (limit, offset) = page.resolve()?;
381- let events = window.apply(service::event::list_all(&st.db).await?)?;
382- let total = events.len() as i64;
383- // Paged in the web layer: `WindowParams` filters and re-orders in Rust.
384- let items = paginate(&events, limit, offset)
385- .iter()
386- .map(EventResponse::new)
387- .collect();
370+ window.validate()?;
371+ // The window and the page are one SQL statement; `total` is a count over
372+ // the same WHERE, so a filtered page never loads the rows it skips.
373+ let (events, total) = service::event::list_windowed(
374+ &st.db,
375+ window.starts_after,
376+ window.ends_after,
377+ window.starts_before,
378+ window.ends_before,
379+ limit,
380+ offset,
381+ )
382+ .await?;
383+ let items = events.iter().map(EventResponse::new).collect();
388384 Ok(Json(Page::new(items, total, limit, offset)))
389385 }
390386
src/web/exams/mod.rsmodified+38 -30
@@ -36,7 +36,7 @@ use super::bank_questions::BankQuestionResponse;
3636 use super::instances::can_view_instance;
3737 use super::{
3838 ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef,
39- RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,
39+ RequireTeacher, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,
4040 person_map, read_image_upload, remove_blob, set_or_clear, store_blob,
4141 };
4242
@@ -52,20 +52,6 @@ pub(crate) use images::*;
5252 pub(crate) use questions::*;
5353 pub(crate) use review::*;
5454
55-impl Scheduled for Exam {
56- fn starts_at_ms(&self) -> Option<i64> {
57- self.get_starts_at().map(|at| at.as_millis())
58- }
59-
60- fn ends_at_ms(&self) -> Option<i64> {
61- self.get_ends_at().map(|at| at.as_millis())
62- }
63-
64- fn order_key(&self) -> String {
65- self.get_id().key()
66- }
67-}
68-
6955 pub fn routes() -> OpenApiRouter<AppState> {
7056 OpenApiRouter::new()
7157 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
@@ -245,6 +231,10 @@ struct ExamStatisticsResponse {
245231 /// schedule — so `?ends_after=<now>&limit=20` returns the twenty *soonest*
246232 /// exams rather than the twenty newest-created. Exams without a window
247233 /// (no `mode`, or `open`) are excluded by either parameter.
234+/// `?starts_before=` / `?ends_before=` are the mirror bounds (strictly
235+/// before). Visibility, the draft rule, the window, the page, and the count
236+/// share one SQL `WHERE`, so a filtered page never decodes the exams it
237+/// skips.
248238 #[utoipa::path(
249239 get,
250240 path = "/",
@@ -264,29 +254,47 @@ async fn list_exams(
264254 Query(page): Query<PageParams>,
265255 ) -> Result<Json<Page<ExamResponse>>, AppError> {
266256 let (limit, offset) = page.resolve()?;
267- let exams = if user.get_role().at_least(Role::Manager) {
268- service::exam::list_all(&st.db).await?
257+ window.validate()?;
258+ // Visibility and the draft rule ride the same WHERE as the page and the
259+ // count: a manager+ reads the whole table, everyone else the exams of
260+ // their visible instances — a draft only where they manage the instance.
261+ let (exams, total) = if user.get_role().at_least(Role::Manager) {
262+ service::exam::list_windowed(
263+ &st.db,
264+ None,
265+ None,
266+ window.starts_after,
267+ window.ends_after,
268+ window.starts_before,
269+ window.ends_before,
270+ limit,
271+ offset,
272+ )
273+ .await?
269274 } else {
270275 let instances = visible_instances(&user, &st.db).await?;
271- let ids: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect();
276+ let visible: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect();
272277 // Drafts show only where the caller manages the instance (as one of
273278 // its teachers — the manager+ path above already saw everything).
274- let managed: HashSet<String> = instances
279+ let managed: Vec<_> = instances
275280 .iter()
276281 .filter(|(_, manages)| *manages)
277- .map(|(instance, _)| instance.get_id().key())
282+ .map(|(instance, _)| instance.get_id().clone())
278283 .collect();
279- let mut exams = service::exam::list_for_class_course_courses(&st.db, &ids).await?;
280- exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_class_course().key()));
281- exams
284+ service::exam::list_windowed(
285+ &st.db,
286+ Some(&visible),
287+ Some(&managed),
288+ window.starts_after,
289+ window.ends_after,
290+ window.starts_before,
291+ window.ends_before,
292+ limit,
293+ offset,
294+ )
295+ .await?
282296 };
283- let exams = window.apply(exams)?;
284- let total = exams.len() as i64;
285- // Paged in the web layer: the draft filter and the window are Rust.
286- let items = paginate(&exams, limit, offset)
287- .iter()
288- .map(ExamResponse::new)
289- .collect();
297+ let items = exams.iter().map(ExamResponse::new).collect();
290298 Ok(Json(Page::new(items, total, limit, offset)))
291299 }
292300
src/web/homework.rsmodified+498 -26
@@ -15,7 +15,7 @@ use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
1515 use axum::http::{HeaderValue, StatusCode};
1616 use axum::response::{IntoResponse, Response};
1717 use serde::{Deserialize, Serialize};
18-use utoipa::ToSchema;
18+use utoipa::{IntoParams, ToSchema};
1919 use utoipa_axum::router::OpenApiRouter;
2020 use utoipa_axum::routes;
2121
@@ -138,21 +138,81 @@ async fn homework_with_instance(
138138 Ok((homework, instance))
139139 }
140140
141+/// The optional `?due_after=&due_before=&class_course=` scoping of the list.
142+/// `due_after` keeps homework due at or after an instant (the frontend's open
143+/// tab), `due_before` keeps what is due before one (the past tab) — the two
144+/// bounds share no instant and leave no gap — and `class_course` scopes the
145+/// list to one instance. Absent, each field filters nothing.
146+#[derive(Debug, Deserialize, IntoParams)]
147+struct HomeworkListFilter {
148+ /// Keep homework due at or after this instant (Unix ms).
149+ due_after: Option<i64>,
150+ /// Keep homework due before this instant (Unix ms).
151+ due_before: Option<i64>,
152+ /// Keep only this class×course instance's homework (an instance id).
153+ #[param(example = "019732e3-7b00-7000-8000-00000000face")]
154+ class_course: Option<String>,
155+}
156+
157+impl HomeworkListFilter {
158+ /// Validate the raw query into the service-layer scope. A negative due
159+ /// bound, an empty instance key, and a key that is not a hyphenated uuid
160+ /// (the nil id included — [`ClassCourseId::from_key`] lands there) are
161+ /// refused with the field named; a well-formed id that names no row
162+ /// simply matches nothing.
163+ fn resolve(self) -> Result<service::homework::HomeworkListFilter, AppError> {
164+ let invalid =
165+ |field: &'static str, reason: &'static str| AppError::Validation(ValidationError::Invalid { field, reason });
166+ let due_after = match self.due_after {
167+ None => None,
168+ Some(ms) if ms < 0 => return Err(invalid("due_after", "must not be negative")),
169+ Some(ms) => Some(ms),
170+ };
171+ let due_before = match self.due_before {
172+ None => None,
173+ Some(ms) if ms < 0 => return Err(invalid("due_before", "must not be negative")),
174+ Some(ms) => Some(ms),
175+ };
176+ let class_course = match self.class_course.as_deref().map(str::trim) {
177+ None => None,
178+ Some("") => return Err(invalid("class_course", "must not be empty")),
179+ Some(key) => {
180+ let instance = ClassCourseId::from_key(key);
181+ if instance.uuid().is_nil() {
182+ return Err(invalid("class_course", "must be a hyphenated uuid"));
183+ }
184+ Some(instance)
185+ }
186+ };
187+ Ok(service::homework::HomeworkListFilter {
188+ due_after,
189+ due_before,
190+ class_course,
191+ })
192+ }
193+}
194+
141195 /// List the homework across the caller's instances — their "my homework" view —
142196 /// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every
143197 /// instance's homework; a teacher sees the homework of instances they run; a
144198 /// student sees only the homework they are assigned (whole-roster ones plus any
145199 /// subset that names them, each with its `assigned` narrowed to themselves).
146200 /// Returns a `{items, total, limit, offset}` envelope.
201+///
202+/// `due_after` and `due_before` (Unix ms) carry the frontend's open and past
203+/// tabs — due at or after an instant, due before one — and `class_course`
204+/// scopes the list to a single instance, all before anything leaves the
205+/// database. Omitted, the response is the caller's whole visible homework,
206+/// unchanged.
147207 #[utoipa::path(
148208 get,
149209 path = "/",
150210 tag = "homework",
151211 security(("session_cookie" = [])),
152- params(PageParams),
212+ params(PageParams, HomeworkListFilter),
153213 responses(
154214 (status = 200, description = "A page of the caller's visible homework (all of it when unpaged)", body = Page<HomeworkResponse>),
155- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
215+ (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
156216 (status = 401, description = "Not authenticated", body = ErrorResponse),
157217 ),
158218 )]
@@ -160,33 +220,40 @@ async fn list_homework(
160220 State(st): State<AppState>,
161221 CurrentUser(user): CurrentUser,
162222 Query(page): Query<PageParams>,
223+ Query(filter): Query<HomeworkListFilter>,
163224 ) -> Result<Json<Page<HomeworkResponse>>, AppError> {
164225 let (limit, offset) = page.resolve()?;
226+ let filter = filter.resolve()?;
165227 // The instances this caller manages — empty for a manager+, who manages all
166228 // of them, and who is told apart by this flag.
167229 let manages_all = user.get_role().at_least(Role::Manager);
168- let mut managed: Vec<ClassCourseId> = Vec::new();
169- let homework = if manages_all {
170- service::homework::list_all(&st.db).await?
171- } else {
172- let instances = visible_instances(&user, &st.db).await?;
173- let ids: Vec<ClassCourseId> = instances
174- .iter()
175- .map(|(instance, _)| instance.get_id().clone())
176- .collect();
177- // A student sees only the homework they are assigned; a teacher who
178- // manages an instance sees all of its homework (the manager+ path above
179- // already saw everything).
180- managed = instances
181- .iter()
182- .filter(|(_, manages)| *manages)
183- .map(|(instance, _)| instance.get_id().clone())
184- .collect();
185- let mut homework = service::homework::list_for_class_courses(&st.db, &ids).await?;
186- homework
187- .retain(|hw| managed.contains(hw.get_class_course()) || hw.student_sees(user.get_id()));
188- homework
189- };
230+ if manages_all {
231+ // The SQL WHERE is the whole filter on this path: a manager retains
232+ // nothing in Rust, so the window and the count both run in the
233+ // database and `total` comes back with the page.
234+ let (homework, total) =
235+ service::homework::list_all(&st.db, &filter, limit, offset).await?;
236+ let items = homework.iter().map(HomeworkResponse::new).collect();
237+ return Ok(Json(Page::new(items, total, limit, offset)));
238+ }
239+ let instances = visible_instances(&user, &st.db).await?;
240+ let ids: Vec<ClassCourseId> = instances
241+ .iter()
242+ .map(|(instance, _)| instance.get_id().clone())
243+ .collect();
244+ // A student sees only the homework they are assigned; a teacher who
245+ // manages an instance sees all of its homework (the manager+ path above
246+ // already saw everything).
247+ let managed: Vec<ClassCourseId> = instances
248+ .iter()
249+ .filter(|(_, manages)| *manages)
250+ .map(|(instance, _)| instance.get_id().clone())
251+ .collect();
252+ let mut homework = service::homework::list_for_class_courses(&st.db, &ids, &filter).await?;
253+ // The audience retain stays after the SQL filter and before the window,
254+ // so `total` is the post-retain length, never a page sliced before it.
255+ homework
256+ .retain(|hw| managed.contains(hw.get_class_course()) || hw.student_sees(user.get_id()));
190257 let total = homework.len() as i64;
191258 // Paged in the web layer: the audience filter above is per-row Rust. The
192259 // subset roster rides along only for the rows the caller manages — to a
@@ -195,7 +262,7 @@ async fn list_homework(
195262 let items = paginate(&homework, limit, offset)
196263 .iter()
197264 .map(|hw| {
198- if manages_all || managed.contains(hw.get_class_course()) {
265+ if managed.contains(hw.get_class_course()) {
199266 HomeworkResponse::new(hw)
200267 } else {
201268 HomeworkResponse::for_viewer(hw, user.get_id())
@@ -1277,3 +1344,408 @@ async fn homework_report(
12771344 }
12781345 Ok(Json(Page::new(items, total, limit, offset)))
12791346 }
1347+
1348+#[cfg(test)]
1349+mod tests {
1350+ use super::*;
1351+ use axum::Router;
1352+ use axum::body::Body;
1353+ use axum::http::{Request, StatusCode};
1354+ use tower::ServiceExt;
1355+
1356+ use crate::database::init_test_tenants;
1357+ use crate::db::session;
1358+ use crate::domain::homework::HomeworkTitle;
1359+ use crate::domain::role::Role;
1360+ use crate::domain::subject::{SubjectDescription, SubjectName};
1361+ use crate::domain::user::Username;
1362+ use crate::tenant::{DEMO_SCHOOL_ID, SchoolId};
1363+
1364+ const DAY: i64 = 86_400_000;
1365+
1366+ /// The app behind a live school cookie for `user`, plus the tenant
1367+ /// registry handle. The router is the real one, so the cookie, the
1368+ /// tenant resolution, and the published query params are all exercised.
1369+ async fn app_for(username: &str, role: Role) -> (Router, String, crate::database::Database) {
1370+ let tenants = init_test_tenants().await;
1371+ let school = tenants
1372+ .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
1373+ .await
1374+ .expect("the demo school");
1375+ let user = crate::service::user::create(&school, Username::try_new(username).unwrap(), None)
1376+ .await
1377+ .unwrap();
1378+ let user = crate::service::user::set_role(&school, user.get_id(), role)
1379+ .await
1380+ .unwrap()
1381+ .0;
1382+ let token = session::create(&school, user.get_id()).await.unwrap();
1383+ let cookie = format!("session={DEMO_SCHOOL_ID}.{}", token.token().as_str());
1384+ let state = AppState {
1385+ db: tenants.control().clone(),
1386+ tenants,
1387+ files_path: std::env::temp_dir(),
1388+ cookie_secure: false,
1389+ rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
1390+ chatbot_limit: Default::default(),
1391+ rag_limit: Default::default(),
1392+ exam_presence: Default::default(),
1393+ board_hub: Default::default(),
1394+ ai: None,
1395+ metrics: crate::telemetry::Metrics::noop(),
1396+ };
1397+ (crate::build_router(state), cookie, school)
1398+ }
1399+
1400+ /// One homework with a chosen due instant and audience on `instance`.
1401+ async fn seed_homework_on(
1402+ db: &crate::database::Database,
1403+ instance: &ClassCourseId,
1404+ course: &crate::domain::course::CourseId,
1405+ due_at: i64,
1406+ title: &str,
1407+ assigned: Option<Vec<UserId>>,
1408+ ) -> Homework {
1409+ let subject = crate::db::subject::create(
1410+ db,
1411+ course,
1412+ SubjectName::try_new(title).unwrap(),
1413+ SubjectDescription::try_new("").unwrap(),
1414+ )
1415+ .await
1416+ .unwrap();
1417+ let teacher = crate::service::user::create(db, Username::try_new(title).unwrap(), None)
1418+ .await
1419+ .unwrap();
1420+ crate::db::homework::create(
1421+ db,
1422+ instance,
1423+ subject.get_id(),
1424+ HomeworkTitle::try_new(title).unwrap(),
1425+ None,
1426+ Timestamp::from_millis(due_at),
1427+ assigned,
1428+ teacher.get_id(),
1429+ )
1430+ .await
1431+ .unwrap()
1432+ }
1433+
1434+ /// One homework with a chosen due instant and audience on a fresh
1435+ /// instance; returns the instance and the row.
1436+ async fn seed_homework(
1437+ db: &crate::database::Database,
1438+ due_at: i64,
1439+ title: &str,
1440+ assigned: Option<Vec<UserId>>,
1441+ ) -> (ClassCourseId, Homework) {
1442+ let (instance, course) = crate::db::course::a_test_instance(db).await;
1443+ let homework =
1444+ seed_homework_on(db, &instance, &course, due_at, title, assigned).await;
1445+ (instance, homework)
1446+ }
1447+
1448+ /// A student put on the live roster of the class `instance` belongs to —
1449+ /// the membership `visible_instances` reads for a student.
1450+ async fn join_class(
1451+ db: &crate::database::Database,
1452+ instance: &ClassCourseId,
1453+ student: &UserId,
1454+ ) {
1455+ let instance = crate::service::class_course::read(db, instance)
1456+ .await
1457+ .unwrap()
1458+ .unwrap();
1459+ sqlx::query(
1460+ "INSERT INTO class_member (id, class, app_user, added_by, joined_at) \
1461+ VALUES ($1, $2, $3, $3, 0)",
1462+ )
1463+ .bind(crate::domain::class_group::ClassGroupId::generate().uuid())
1464+ .bind(instance.get_class().uuid())
1465+ .bind(student.uuid())
1466+ .execute(db)
1467+ .await
1468+ .unwrap();
1469+ }
1470+
1471+ async fn get(app: &Router, uri: &str, cookie: &str) -> (StatusCode, serde_json::Value) {
1472+ let response = app
1473+ .clone()
1474+ .oneshot(
1475+ Request::builder()
1476+ .uri(uri)
1477+ .header("cookie", cookie)
1478+ .body(Body::empty())
1479+ .unwrap(),
1480+ )
1481+ .await
1482+ .unwrap();
1483+ let status = response.status();
1484+ let body = axum::body::to_bytes(response.into_body(), 1 << 20)
1485+ .await
1486+ .unwrap();
1487+ let json = if body.is_empty() {
1488+ serde_json::Value::Null
1489+ } else {
1490+ serde_json::from_slice(&body).unwrap()
1491+ };
1492+ (status, json)
1493+ }
1494+
1495+ /// The manager path: the due window and the instance scope narrow in SQL,
1496+ /// the page window applies after the filter, and `total` stays the
1497+ /// filtered length. Absent params are exactly the old response.
1498+ #[tokio::test]
1499+ async fn manager_filters_open_past_and_instance_in_sql() {
1500+ let now = Timestamp::now().as_millis();
1501+ let (app, cookie, school) = app_for("mudur-filter", Role::Manager).await;
1502+ let (_, past) = seed_homework(&school, now - DAY, "past-here", None).await;
1503+ let (_, open) = seed_homework(&school, now + DAY, "open-here", None).await;
1504+ let (there, open_there) = seed_homework(&school, now + 2 * DAY, "open-there", None).await;
1505+
1506+ // Absent params: every row, newest first — the old response.
1507+ let (status, body) = get(&app, "/homework", &cookie).await;
1508+ assert_eq!(status, StatusCode::OK);
1509+ assert_eq!(body["total"], 3);
1510+ let ids: Vec<String> = body["items"]
1511+ .as_array()
1512+ .unwrap()
1513+ .iter()
1514+ .map(|row| row["id"].as_str().unwrap().to_string())
1515+ .collect();
1516+ assert_eq!(
1517+ ids,
1518+ vec![
1519+ open_there.get_id().key(),
1520+ open.get_id().key(),
1521+ past.get_id().key()
1522+ ]
1523+ );
1524+
1525+ // The open tab: due at or after the bound.
1526+ let (status, body) = get(&app, &format!("/homework?due_after={now}"), &cookie).await;
1527+ assert_eq!(status, StatusCode::OK);
1528+ assert_eq!(body["total"], 2);
1529+ assert!(
1530+ body["items"]
1531+ .as_array()
1532+ .unwrap()
1533+ .iter()
1534+ .all(|row| row["due_at"].as_i64().unwrap() >= now)
1535+ );
1536+
1537+ // The past tab: due strictly before the bound — no overlap, no gap.
1538+ let (status, body) = get(&app, &format!("/homework?due_before={now}"), &cookie).await;
1539+ assert_eq!(status, StatusCode::OK);
1540+ assert_eq!(body["total"], 1);
1541+ assert_eq!(body["items"][0]["id"], past.get_id().key().to_string());
1542+
1543+ // The instance scope: only `there`'s rows.
1544+ let (status, body) = get(
1545+ &app,
1546+ &format!("/homework?class_course={}", there.key()),
1547+ &cookie,
1548+ )
1549+ .await;
1550+ assert_eq!(status, StatusCode::OK);
1551+ assert_eq!(body["total"], 1);
1552+ assert_eq!(body["items"][0]["id"], open_there.get_id().key().to_string());
1553+
1554+ // A well-formed id that names no row: an empty page, not a 404.
1555+ let stranger = ClassCourseId::generate();
1556+ let (status, body) = get(
1557+ &app,
1558+ &format!("/homework?class_course={}", stranger.key()),
1559+ &cookie,
1560+ )
1561+ .await;
1562+ assert_eq!(status, StatusCode::OK);
1563+ assert_eq!(body["total"], 0);
1564+ assert!(body["items"].as_array().unwrap().is_empty());
1565+
1566+ // The window applies after the filter; total is the filtered count.
1567+ let (status, body) =
1568+ get(&app, &format!("/homework?due_after={now}&limit=1"), &cookie).await;
1569+ assert_eq!(status, StatusCode::OK);
1570+ assert_eq!(body["total"], 2);
1571+ assert_eq!(body["items"].as_array().unwrap().len(), 1);
1572+ let (status, body) =
1573+ get(&app, &format!("/homework?due_after={now}&offset=1"), &cookie).await;
1574+ assert_eq!(status, StatusCode::OK);
1575+ assert_eq!(body["total"], 2);
1576+ assert_eq!(body["items"][0]["id"], open.get_id().key().to_string());
1577+ }
1578+
1579+ /// A bad filter is a 400 naming the field: negative due bounds, and an
1580+ /// instance key that is empty, not a uuid, or the nil uuid.
1581+ #[tokio::test]
1582+ async fn bad_filters_are_400_naming_the_field() {
1583+ let (app, cookie, _school) = app_for("mudur-hata", Role::Manager).await;
1584+ for (uri, field) in [
1585+ ("/homework?due_after=-1", "due_after"),
1586+ ("/homework?due_before=-5", "due_before"),
1587+ ("/homework?class_course=", "class_course"),
1588+ ("/homework?class_course=%20", "class_course"),
1589+ ("/homework?class_course=not-a-uuid", "class_course"),
1590+ (
1591+ "/homework?class_course=00000000-0000-0000-0000-000000000000",
1592+ "class_course",
1593+ ),
1594+ ] {
1595+ let (status, body) = get(&app, uri, &cookie).await;
1596+ assert_eq!(status, StatusCode::BAD_REQUEST, "{uri} must be a 400");
1597+ assert!(
1598+ body["error"]
1599+ .as_str()
1600+ .unwrap_or_default()
1601+ .contains(field),
1602+ "{uri} must name {field}: {body}"
1603+ );
1604+ }
1605+ }
1606+
1607+ /// The audience wall survives the filter: a student still sees only the
1608+ /// homework they are assigned, a teacher still sees their instances'
1609+ /// homework, and the manager sees every instance — all narrowed by the
1610+ /// same params.
1611+ #[tokio::test]
1612+ async fn audience_walls_survive_the_filter() {
1613+ let now = Timestamp::now().as_millis();
1614+ let (app, _, school) = app_for("ogretmen-seyirci", Role::Student).await;
1615+ // The same registry also holds the actors; mint them directly.
1616+ let ali = crate::service::user::create(&school, Username::try_new("ali-filter").unwrap(), None)
1617+ .await
1618+ .unwrap();
1619+ let veli = crate::service::user::create(&school, Username::try_new("veli-filter").unwrap(), None)
1620+ .await
1621+ .unwrap();
1622+ let teacher = crate::service::user::create(
1623+ &school,
1624+ Username::try_new("hocasi-filter").unwrap(),
1625+ None,
1626+ )
1627+ .await
1628+ .unwrap();
1629+ let teacher = crate::service::user::set_role(&school, teacher.get_id(), Role::Teacher)
1630+ .await
1631+ .unwrap()
1632+ .0;
1633+ let manager = crate::service::user::create(
1634+ &school,
1635+ Username::try_new("mudur-seyirci").unwrap(),
1636+ None,
1637+ )
1638+ .await
1639+ .unwrap();
1640+ let manager = crate::service::user::set_role(&school, manager.get_id(), Role::Manager)
1641+ .await
1642+ .unwrap()
1643+ .0;
1644+
1645+ let (instance, course) = crate::db::course::a_test_instance(&school).await;
1646+ let whole_open = seed_homework_on(&school, &instance, &course, now + DAY, "acik-genel", None).await;
1647+ let subset_open = seed_homework_on(
1648+ &school,
1649+ &instance,
1650+ &course,
1651+ now + DAY,
1652+ "acik-secili",
1653+ Some(vec![*ali.get_id()]),
1654+ )
1655+ .await;
1656+ let past = seed_homework_on(&school, &instance, &course, now - DAY, "gecmis-genel", None).await;
1657+ join_class(&school, &instance, ali.get_id()).await;
1658+ join_class(&school, &instance, veli.get_id()).await;
1659+ crate::db::class_course_teacher::assign(&school, &instance, teacher.get_id())
1660+ .await
1661+ .unwrap();
1662+
1663+ let ali_cookie = format!(
1664+ "session={DEMO_SCHOOL_ID}.{}",
1665+ session::create(&school, ali.get_id())
1666+ .await
1667+ .unwrap()
1668+ .token()
1669+ .as_str()
1670+ );
1671+ let veli_cookie = format!(
1672+ "session={DEMO_SCHOOL_ID}.{}",
1673+ session::create(&school, veli.get_id())
1674+ .await
1675+ .unwrap()
1676+ .token()
1677+ .as_str()
1678+ );
1679+ let teacher_cookie = format!(
1680+ "session={DEMO_SCHOOL_ID}.{}",
1681+ session::create(&school, teacher.get_id())
1682+ .await
1683+ .unwrap()
1684+ .token()
1685+ .as_str()
1686+ );
1687+ let manager_cookie = format!(
1688+ "session={DEMO_SCHOOL_ID}.{}",
1689+ session::create(&school, manager.get_id())
1690+ .await
1691+ .unwrap()
1692+ .token()
1693+ .as_str()
1694+ );
1695+
1696+ // Ali: open tab only, and the subset names him — narrowed to him.
1697+ let (status, body) = get(&app, &format!("/homework?due_after={now}"), &ali_cookie).await;
1698+ assert_eq!(status, StatusCode::OK);
1699+ assert_eq!(body["total"], 2);
1700+ let ids: Vec<String> = body["items"]
1701+ .as_array()
1702+ .unwrap()
1703+ .iter()
1704+ .map(|row| row["id"].as_str().unwrap().to_string())
1705+ .collect();
1706+ assert_eq!(
1707+ ids,
1708+ vec![
1709+ subset_open.get_id().key(),
1710+ whole_open.get_id().key()
1711+ ]
1712+ );
1713+ let subset = body["items"]
1714+ .as_array()
1715+ .unwrap()
1716+ .iter()
1717+ .find(|row| row["id"] == subset_open.get_id().key())
1718+ .unwrap();
1719+ assert_eq!(
1720+ subset["assigned"],
1721+ serde_json::json!([ali.get_id().key().to_string()]),
1722+ "a student's subset roster is narrowed to themselves"
1723+ );
1724+
1725+ // Veli shares the class but not the subset: the open tab hides it.
1726+ let (status, body) = get(&app, &format!("/homework?due_after={now}"), &veli_cookie).await;
1727+ assert_eq!(status, StatusCode::OK);
1728+ assert_eq!(body["total"], 1);
1729+ assert_eq!(body["items"][0]["id"], whole_open.get_id().key().to_string());
1730+
1731+ // The teacher manages the instance: every open row of it, roster and
1732+ // all — the past row stays behind the filter, not the audience.
1733+ let (status, body) =
1734+ get(&app, &format!("/homework?due_after={now}"), &teacher_cookie).await;
1735+ assert_eq!(status, StatusCode::OK);
1736+ assert_eq!(body["total"], 2);
1737+ assert!(body["items"].as_array().unwrap().iter().any(|row| row["id"]
1738+ == subset_open.get_id().key()
1739+ && row["assigned"]
1740+ .as_array()
1741+ .unwrap()
1742+ .len()
1743+ == 1));
1744+
1745+ // The manager sees every instance's homework, narrowed by the params.
1746+ let (status, body) = get(&app, &format!("/homework?due_before={now}"), &manager_cookie).await;
1747+ assert_eq!(status, StatusCode::OK);
1748+ assert_eq!(body["total"], 1);
1749+ assert_eq!(body["items"][0]["id"], past.get_id().key().to_string());
1750+ }
1751+}
src/web/instances.rsmodified+92 -6
@@ -22,7 +22,7 @@ use axum::Json;
2222 use axum::extract::{Path, Query};
2323 use axum::http::StatusCode;
2424 use serde::{Deserialize, Serialize};
25-use utoipa::ToSchema;
25+use utoipa::{IntoParams, ToSchema};
2626 use utoipa_axum::router::OpenApiRouter;
2727 use utoipa_axum::routes;
2828
@@ -1080,19 +1080,59 @@ async fn create_session_in_instance(
10801080 ))
10811081 }
10821082
1083+/// The optional `?starts_after=&starts_before=` window on the session list:
1084+/// half-open on `starts_at`, both bounds unix milliseconds. A negative value
1085+/// is a `400` naming the field.
1086+#[derive(Debug, Deserialize, IntoParams)]
1087+struct SessionWindow {
1088+ /// Keep sessions starting at or after this unix-millisecond instant
1089+ /// (inclusive).
1090+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
1091+ #[serde(default)]
1092+ starts_after: Option<i64>,
1093+ /// Keep sessions starting strictly before this unix-millisecond instant,
1094+ /// so `[month_start, next_month_start)` names a month exactly.
1095+ #[param(minimum = 0, example = 1_760_259_599_999_i64)]
1096+ #[serde(default)]
1097+ starts_before: Option<i64>,
1098+}
1099+
1100+impl SessionWindow {
1101+ fn validate(&self) -> Result<(), AppError> {
1102+ for (field, value) in [
1103+ ("starts_after", self.starts_after),
1104+ ("starts_before", self.starts_before),
1105+ ] {
1106+ if value.is_some_and(|value| value < 0) {
1107+ return Err(AppError::Validation(ValidationError::Invalid {
1108+ field,
1109+ reason: "must not be negative",
1110+ }));
1111+ }
1112+ }
1113+ Ok(())
1114+ }
1115+}
1116+
10831117 /// List one instance's lesson sessions, most recent first, paged via
10841118 /// `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's
10851119 /// enrolled students, its teachers, and managers/admins. Returns a
10861120 /// `{items, total, limit, offset}` envelope.
1121+///
1122+/// The optional `?starts_after=&starts_before=` window (unix milliseconds)
1123+/// narrows the list to the half-open `[starts_after, starts_before)` on
1124+/// `starts_at` — a calendar month is `[month_start, next_month_start)`. The
1125+/// window rides the same SQL `WHERE` as the page and the count; the order is
1126+/// unchanged. Absent, the response is the unfiltered list.
10871127 #[utoipa::path(
10881128 get,
10891129 path = "/{id}/sessions",
10901130 tag = "instances",
10911131 security(("session_cookie" = [])),
1092- params(("id" = String, Path, description = "Instance id"), PageParams),
1132+ params(("id" = String, Path, description = "Instance id"), SessionWindow, PageParams),
10931133 responses(
10941134 (status = 200, description = "A page of the instance's sessions (all of them when unpaged)", body = Page<SessionResponse>),
1095- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1135+ (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
10961136 (status = 401, description = "Not authenticated", body = ErrorResponse),
10971137 (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse),
10981138 (status = 404, description = "Instance not found", body = ErrorResponse),
@@ -1102,9 +1142,11 @@ async fn list_instance_sessions(
11021142 State(st): State<AppState>,
11031143 CurrentUser(user): CurrentUser,
11041144 Path(id): Path<String>,
1145+ Query(window): Query<SessionWindow>,
11051146 Query(page): Query<PageParams>,
11061147 ) -> Result<Json<Page<SessionResponse>>, AppError> {
11071148 let (limit, offset) = page.resolve()?;
1149+ window.validate()?;
11081150 // The instance must exist — a missing one is a 404, not an empty list.
11091151 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
11101152 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
@@ -1112,9 +1154,15 @@ async fn list_instance_sessions(
11121154 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its sessions",
11131155 ));
11141156 }
1115- let (rows, total) =
1116- service::course_session::list_for_class_course(&st.db, instance.get_id(), limit, offset)
1117- .await?;
1157+ let (rows, total) = service::course_session::list_windowed(
1158+ &st.db,
1159+ instance.get_id(),
1160+ window.starts_after,
1161+ window.starts_before,
1162+ limit,
1163+ offset,
1164+ )
1165+ .await?;
11181166 // Join teachers onto the page alone — the lookup shrinks with the window.
11191167 let people = person_map(rows.iter().map(|s| *s.get_teacher()), &st.db).await?;
11201168 let items = rows
@@ -1129,6 +1177,44 @@ mod tests {
11291177 use super::*;
11301178 use crate::domain::class_group::ClassGroupId;
11311179
1180+ /// A negative window bound is a `400` naming the field, whichever bound
1181+ /// it is; both absent validates clean.
1182+ #[test]
1183+ fn a_negative_session_window_bound_is_refused_naming_the_field() {
1184+ let clean = SessionWindow {
1185+ starts_after: None,
1186+ starts_before: None,
1187+ };
1188+ assert!(clean.validate().is_ok());
1189+
1190+ for (field, window) in [
1191+ (
1192+ "starts_after",
1193+ SessionWindow {
1194+ starts_after: Some(-1),
1195+ starts_before: None,
1196+ },
1197+ ),
1198+ (
1199+ "starts_before",
1200+ SessionWindow {
1201+ starts_after: None,
1202+ starts_before: Some(-1),
1203+ },
1204+ ),
1205+ ] {
1206+ let AppError::Validation(ValidationError::Invalid {
1207+ field: named,
1208+ reason,
1209+ }) = window.validate().unwrap_err()
1210+ else {
1211+ panic!("expected a validation error for {field}");
1212+ };
1213+ assert_eq!(named, field);
1214+ assert_eq!(reason, "must not be negative");
1215+ }
1216+ }
1217+
11321218 /// The read path behind `GET /instances/me` is `class_member` → the sections
11331219 /// → their instances. A student enrolled by a section sees exactly that
11341220 /// section's instances, and a second section teaching the same course is a
src/web/meals.rsmodified+54 -4
@@ -93,6 +93,40 @@ struct MenuRange {
9393 to: Option<String>,
9494 }
9595
96+/// Optional slot filter on `GET /meals/menus`. Its own extractor, so
97+/// `GET /meals/attendance/{user}` — which shares [`MenuRange`] for its date
98+/// bounds — gains no dead `slot` param.
99+#[derive(Debug, Deserialize, IntoParams)]
100+struct MenuSlotFilter {
101+ /// Keep only menus published for this meal slot, named exactly as the
102+ /// menu snapshotted it.
103+ #[param(example = "lunch")]
104+ slot: Option<String>,
105+}
106+
107+impl MenuSlotFilter {
108+ /// The slot text to bind, trimmed. Deliberately *not* checked against
109+ /// the school's current `meal_slots`: a menu snapshots its slot's name
110+ /// at publish, so a slot retired since must still find the menus
111+ /// published under it — an unknown name simply matches nothing (an
112+ /// empty page, not a `400`). An empty value, though, filters nothing
113+ /// and says nothing: refused, naming the field.
114+ fn resolve(self) -> Result<Option<String>, AppError> {
115+ let Some(raw) = self.slot else {
116+ return Ok(None);
117+ };
118+ let slot = raw.trim();
119+ if slot.is_empty() {
120+ return Err(ValidationError::Invalid {
121+ field: "slot",
122+ reason: "must name a meal slot and may not be empty",
123+ }
124+ .into());
125+ }
126+ Ok(Some(slot.to_string()))
127+ }
128+}
129+
96130 #[derive(Deserialize, ToSchema)]
97131 struct CreateDish {
98132 #[schema(example = "Mercimek çorbası", max_length = 100)]
@@ -283,15 +317,22 @@ async fn create_menu(
283317 /// `YYYY-MM-DD`, each bound held to the same real-calendar-day rule a menu's
284318 /// own date is). Paged via `?limit=&offset=` (omit `limit` for the full list);
285319 /// returns a `{items, total, limit, offset}` envelope.
320+///
321+/// Narrow to one meal slot with `?slot=` — matched exactly against the slot
322+/// text each menu snapshotted at publish, not against the school's current
323+/// `meal_slots`, so a slot retired since still finds its menus and an
324+/// unknown name is an empty page rather than an error. `?slot=` (empty) is a
325+/// `400`. The filter runs in SQL: `total` counts the filtered rows, and
326+/// `limit`/`offset` window inside them.
286327 #[utoipa::path(
287328 get,
288329 path = "/menus",
289330 tag = "meals",
290331 security(("session_cookie" = [])),
291- params(MenuRange, PageParams),
332+ params(MenuRange, MenuSlotFilter, PageParams),
292333 responses(
293334 (status = 200, description = "A page of menus (the full list when unpaged)", body = Page<MenuResponse>),
294- (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, or a malformed limit or offset", body = ErrorResponse),
335+ (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),
295336 (status = 401, description = "Not authenticated", body = ErrorResponse),
296337 ),
297338 )]
@@ -299,13 +340,22 @@ async fn list_menus(
299340 State(st): State<AppState>,
300341 CurrentUser(user): CurrentUser,
301342 Query(range): Query<MenuRange>,
343+ Query(filter): Query<MenuSlotFilter>,
302344 Query(page): Query<PageParams>,
303345 ) -> Result<Json<Page<MenuResponse>>, AppError> {
304346 let (limit, offset) = page.resolve()?;
305347 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
306348 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
307- let (menus, total) =
308- service::menu::list(&st.db, from.as_ref(), to.as_ref(), limit, offset).await?;
349+ let slot = filter.resolve()?;
350+ let (menus, total) = service::menu::list(
351+ &st.db,
352+ from.as_ref(),
353+ to.as_ref(),
354+ slot.as_deref(),
355+ limit,
356+ offset,
357+ )
358+ .await?;
309359 // The dish/people join runs over the page alone, so it shrinks with it.
310360 let items = menu_responses(&menus, user.get_id(), &st.db).await?;
311361 Ok(Json(Page::new(items, total, limit, offset)))
src/web/messages.rsmodified+19 -2
@@ -62,6 +62,11 @@ struct ListFilter {
6262 /// `?folder=inbox&read=false&limit=1` makes `total` the unread badge),
6363 /// `true` = read only. Omit for both.
6464 read: Option<bool>,
65+ /// Free-text search over each message's subject and body: a case- and
66+ /// diacritic-insensitive substring (`etut` finds `Etüt`). Literal text —
67+ /// `%` and `_` carry no special meaning. Blank means no search.
68+ #[param(example = "etüt")]
69+ q: Option<String>,
6570 }
6671
6772 /// A message as one party sees it. `folder` is the *caller's* copy's folder;
@@ -222,6 +227,10 @@ async fn send_message(
222227 /// flag; `total` counts the filtered folder, so
223228 /// `?folder=inbox&read=false&limit=1` is a cheap unread badge. Paged via
224229 /// `?limit=&offset=`.
230+///
231+/// `?q=` narrows further by free text: a case- and diacritic-insensitive
232+/// substring of each message's subject or body, composed with `folder` and
233+/// `read`; `total` counts the matches. Blank means no search.
225234 #[utoipa::path(
226235 get,
227236 path = "/",
@@ -246,8 +255,16 @@ async fn list(
246255 None => Folder::Inbox,
247256 };
248257
249- let (messages, total) =
250- message::list_folder(&st.db, user.get_id(), folder, filter.read, limit, offset).await?;
258+ let (messages, total) = message::list_folder(
259+ &st.db,
260+ user.get_id(),
261+ folder,
262+ filter.read,
263+ filter.q.as_deref(),
264+ limit,
265+ offset,
266+ )
267+ .await?;
251268 let people = load_people(&messages, &st.db).await?;
252269 let items = messages
253270 .iter()
src/web/page.rsmodified+99 -20
@@ -64,33 +64,47 @@ pub trait Scheduled {
6464 fn order_key(&self) -> String;
6565 }
6666
67-/// The optional `?starts_after=&ends_after=` schedule window on a list of
68-/// scheduled rows. Both are unix milliseconds and independent (AND-ed when
69-/// both are given). Omit both and the list is untouched — same order, same
70-/// total as an unfiltered call.
67+/// The optional `?starts_after=&ends_after=&starts_before=&ends_before=`
68+/// schedule window on a list of scheduled rows. All four are unix milliseconds
69+/// and independent (AND-ed when several are given). Omit all four and the list
70+/// is untouched — same order, same total as an unfiltered call.
7171 #[derive(Debug, Deserialize, IntoParams)]
7272 pub struct WindowParams {
7373 /// Keep only rows starting strictly after this unix-millisecond instant.
7474 /// Rows without a `starts_at` are dropped.
7575 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
76+ #[serde(default)]
7677 pub starts_after: Option<i64>,
7778 /// Keep only rows whose window has not finished by this unix-millisecond
7879 /// instant: `ends_at > value`, falling back to `starts_at > value` when
7980 /// `ends_at` is null. Rows with no schedule at all are dropped.
8081 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
82+ #[serde(default)]
8183 pub ends_after: Option<i64>,
84+ /// Keep only rows starting strictly before this unix-millisecond instant.
85+ /// Rows without a `starts_at` are dropped.
86+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
87+ #[serde(default)]
88+ pub starts_before: Option<i64>,
89+ /// Keep only rows whose window has already finished by this
90+ /// unix-millisecond instant: `ends_at < value`, falling back to
91+ /// `starts_at < value` when `ends_at` is null. Rows with no schedule at
92+ /// all are dropped.
93+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
94+ #[serde(default)]
95+ pub ends_before: Option<i64>,
8296 }
8397
8498 impl WindowParams {
85- /// Apply the window to an already-visibility-filtered list. With neither
86- /// parameter the list is returned untouched; with either, schedule-less
87- /// rows are dropped and the survivors are sorted ascending by `starts_at`
88- /// (falling back to `ends_at`), ties broken by id. A negative value is a
89- /// `400` naming the field.
90- pub fn apply<T: Scheduled>(&self, mut items: Vec<T>) -> Result<Vec<T>, AppError> {
99+ /// The `400` half of the window: a negative bound is refused naming its
100+ /// field. Endpoints that push the window into SQL call this before the
101+ /// read; [`Self::apply`] calls it before filtering.
102+ pub fn validate(&self) -> Result<(), AppError> {
91103 for (field, value) in [
92104 ("starts_after", self.starts_after),
93105 ("ends_after", self.ends_after),
106+ ("starts_before", self.starts_before),
107+ ("ends_before", self.ends_before),
94108 ] {
95109 if value.is_some_and(|value| value < 0) {
96110 return Err(AppError::Validation(ValidationError::Invalid {
@@ -99,16 +113,40 @@ impl WindowParams {
99113 }));
100114 }
101115 }
102- if self.starts_after.is_none() && self.ends_after.is_none() {
116+ Ok(())
117+ }
118+
119+ /// Apply the window to an already-visibility-filtered list. With no
120+ /// parameter the list is returned untouched; with any, schedule-less
121+ /// rows are dropped and the survivors are sorted ascending by `starts_at`
122+ /// (falling back to `ends_at`), ties broken by id. A negative value is a
123+ /// `400` naming the field.
124+ pub fn apply<T: Scheduled>(&self, mut items: Vec<T>) -> Result<Vec<T>, AppError> {
125+ self.validate()?;
126+ if self.starts_after.is_none()
127+ && self.ends_after.is_none()
128+ && self.starts_before.is_none()
129+ && self.ends_before.is_none()
130+ {
103131 return Ok(items);
104132 }
105133 items.retain(|item| {
106134 let starts = item.starts_at_ms();
107135 let ends = item.ends_at_ms();
136+ // The `*_after` bounds drop a `None` on their own (`None > Some`
137+ // is false), but `None < Some(_)` is *true* — `Option` orders
138+ // `None` first — so the `*_before` bounds must refuse a missing
139+ // end explicitly, the way SQL's `NULL < x` does.
108140 self.starts_after.is_none_or(|after| starts > Some(after))
141+ && self
142+ .starts_before
143+ .is_none_or(|before| starts.is_some_and(|start| start < before))
109144 && self
110145 .ends_after
111146 .is_none_or(|after| ends.or(starts) > Some(after))
147+ && self
148+ .ends_before
149+ .is_none_or(|before| ends.or(starts).is_some_and(|end| end < before))
112150 });
113151 // Every survivor has at least one end, so the fallback never yields
114152 // `None` — but sort defensively rather than unwrapping.
@@ -222,17 +260,24 @@ mod tests {
222260 .collect()
223261 }
224262
225- fn window(starts_after: Option<i64>, ends_after: Option<i64>) -> WindowParams {
263+ fn window(
264+ starts_after: Option<i64>,
265+ ends_after: Option<i64>,
266+ starts_before: Option<i64>,
267+ ends_before: Option<i64>,
268+ ) -> WindowParams {
226269 WindowParams {
227270 starts_after,
228271 ends_after,
272+ starts_before,
273+ ends_before,
229274 }
230275 }
231276
232277 #[test]
233278 fn window_absent_leaves_the_list_untouched() {
234279 assert_eq!(
235- keys(window(None, None)),
280+ keys(window(None, None, None, None)),
236281 ["none", "running", "later", "ending", "tie"]
237282 );
238283 }
@@ -243,26 +288,60 @@ mod tests {
243288 // starts_at fallback), `none` has neither and always drops. Ascending
244289 // by starts_at ?? ends_at, ties broken by key.
245290 assert_eq!(
246- keys(window(None, Some(15))),
291+ keys(window(None, Some(15), None, None)),
247292 ["running", "ending", "later", "tie"]
248293 );
249294 // At 25, `ending` (ends 20) is over; `running` (ends 40) is not.
250- assert_eq!(keys(window(None, Some(25))), ["running", "later", "tie"]);
295+ assert_eq!(
296+ keys(window(None, Some(25), None, None)),
297+ ["running", "later", "tie"]
298+ );
251299 }
252300
253301 #[test]
254302 fn starts_after_excludes_started_and_start_less_rows() {
255- assert_eq!(keys(window(Some(25), None)), ["later", "tie"]);
303+ assert_eq!(keys(window(Some(25), None, None, None)), ["later", "tie"]);
256304 // AND-ed with ends_after: `tie` ends at 50, while `later` has no end
257305 // and its starts_at fallback (30) is already behind 45.
258- assert_eq!(keys(window(Some(25), Some(45))), ["tie"]);
259- assert!(keys(window(Some(60), None)).is_empty());
306+ assert_eq!(
307+ keys(window(Some(25), Some(45), None, None)),
308+ ["tie"]
309+ );
310+ assert!(keys(window(Some(60), None, None, None)).is_empty());
311+ }
312+
313+ #[test]
314+ fn starts_before_excludes_not_yet_started_and_start_less_rows() {
315+ // Strictly before: a row starting exactly at the instant is out.
316+ assert_eq!(keys(window(None, None, Some(30), None)), ["running"]);
317+ // AND-ed with ends_after: `running` (ends 40) survives 35; `tie`
318+ // starts exactly at 30 and a `starts_before` is strict.
319+ assert_eq!(keys(window(None, Some(35), Some(30), None)), ["running"]);
320+ }
321+
322+ #[test]
323+ fn ends_before_keeps_only_finished_rows_dropping_the_unscheduled() {
324+ // At 45: `ending` (ends 20) is over, `later` on its starts_at
325+ // fallback (30) is over, `running` (ends 40) is over; `tie` (ends 50)
326+ // is not; `none` has no schedule and always drops.
327+ assert_eq!(keys(window(None, None, None, Some(45))), ["running", "ending", "later"]);
328+ // Exactly at the end is not before it.
329+ assert_eq!(keys(window(None, None, None, Some(40))), ["ending", "later"]);
260330 }
261331
262332 #[test]
263333 fn window_rejects_negative_values() {
264- assert!(window(Some(-1), None).apply(rows()).is_err());
265- assert!(window(None, Some(-1)).apply(rows()).is_err());
334+ assert!(window(Some(-1), None, None, None).apply(rows()).is_err());
335+ assert!(window(None, Some(-1), None, None).apply(rows()).is_err());
336+ assert!(window(None, None, Some(-1), None).apply(rows()).is_err());
337+ assert!(window(None, None, None, Some(-1)).apply(rows()).is_err());
338+ // The shared validate reports the field it refuses.
339+ let Err(AppError::Validation(ValidationError::Invalid { field, .. })) =
340+ window(None, None, Some(-1), None).apply(rows())
341+ else {
342+ panic!("expected a validation error");
343+ };
344+ assert_eq!(field, "starts_before");
266345 }
267346
268347 #[test]
src/web/pomodoro.rsmodified+126 -32
@@ -3,7 +3,7 @@ use axum::Json;
33 use axum::extract::{Path, Query};
44 use axum::http::StatusCode;
55 use serde::{Deserialize, Serialize};
6-use utoipa::ToSchema;
6+use utoipa::{IntoParams, ToSchema};
77 use utoipa_axum::router::OpenApiRouter;
88 use utoipa_axum::routes;
99
@@ -11,13 +11,13 @@ use crate::constant::MAX_POMODORO_LABEL_LEN;
1111 use crate::domain::pomodoro::PomodoroSession;
1212 use crate::domain::role::Role;
1313 use crate::domain::user::{User, UserId};
14-use crate::error::{AppError, ErrorResponse};
14+use crate::error::{AppError, ErrorResponse, ValidationError};
1515 use crate::service::parent_link::ensure_can_observe;
1616 use crate::service::pomodoro;
1717 use crate::state::AppState;
1818 use crate::validate::validate_optional;
1919
20-use super::{CurrentUser, PageParams, paginate};
20+use super::{CurrentUser, PageParams};
2121
2222 pub fn routes() -> OpenApiRouter<AppState> {
2323 OpenApiRouter::new()
@@ -84,7 +84,8 @@ impl PomodoroResponse {
8484 #[derive(Serialize, ToSchema)]
8585 struct PomodoroLog {
8686 items: Vec<PomodoroResponse>,
87- /// Total sessions in the full log, before `limit`/`offset` are applied.
87+ /// Total sessions in the log the filter selects, before `limit`/`offset`
88+ /// are applied.
8889 #[schema(example = 256)]
8990 total: i64,
9091 /// Echo of the applied `limit`; `null` when the response is unbounded.
@@ -93,33 +94,20 @@ struct PomodoroLog {
9394 /// Echo of the applied `offset`.
9495 #[schema(example = 0)]
9596 offset: i64,
96- /// Sum of `duration_ms` over every *finished* session — the whole log,
97- /// not just this page. A running session counts nothing until finished.
97+ /// Sum of `duration_ms` over every *finished* session the filter selects —
98+ /// the whole log, not just this page. A running session counts nothing
99+ /// until finished.
98100 total_focus_ms: i64,
99101 }
100102
101103 impl PomodoroLog {
102- fn new(sessions: &[PomodoroSession], limit: Option<i64>, offset: i64) -> Self {
103- let total_focus_ms = sessions
104- .iter()
105- .filter_map(|session| {
106- session.get_finished_at().map(|done| {
107- done.as_millis()
108- .saturating_sub(session.get_started_at().as_millis())
109- })
110- })
111- .sum();
104+ fn new(page: pomodoro::PomodoroLogPage, limit: Option<i64>, offset: i64) -> Self {
112105 Self {
113- // Paged in the web layer: `total_focus_ms` folds the whole log, so the
114- // rows the page comes from are already all in hand.
115- items: paginate(sessions, limit, offset)
116- .iter()
117- .map(PomodoroResponse::new)
118- .collect(),
119- total: sessions.len() as i64,
106+ items: page.items.iter().map(PomodoroResponse::new).collect(),
107+ total: page.total,
120108 limit,
121109 offset,
122- total_focus_ms,
110+ total_focus_ms: page.total_focus_ms,
123111 }
124112 }
125113 }
@@ -209,19 +197,57 @@ async fn finish(
209197 Ok(Json(PomodoroResponse::new(&session)))
210198 }
211199
200+/// The optional `?from=&to=` window over the log. Both bounds are UTC unix
201+/// milliseconds and half-open — `from` inclusive, `to` exclusive, so
202+/// adjacent windows tile without overlap — and independent: each present
203+/// bound narrows from its own end. Absent, the log is untouched.
204+#[derive(Debug, Deserialize, IntoParams)]
205+struct HistoryFilter {
206+ /// Keep sessions that started at or after this instant.
207+ #[param(example = 1_760_000_000_000i64)]
208+ from: Option<i64>,
209+ /// Keep sessions that started before this instant.
210+ #[param(example = 1_760_008_640_000i64)]
211+ to: Option<i64>,
212+}
213+
214+impl HistoryFilter {
215+ /// The validated bounds, or `(None, None)` for the whole log. A negative
216+ /// bound is a `400` naming the field: the server stamps every instant
217+ /// itself, so nothing predates the epoch and a negative value is a
218+ /// malformed request, not an era to page through.
219+ fn resolve(&self) -> Result<(Option<i64>, Option<i64>), AppError> {
220+ let bound = |value: Option<i64>, field: &'static str| match value {
221+ Some(ms) if ms < 0 => Err(AppError::Validation(ValidationError::Invalid {
222+ field,
223+ reason: "must not be negative",
224+ })),
225+ other => Ok(other),
226+ };
227+ Ok((bound(self.from, "from")?, bound(self.to, "to")?))
228+ }
229+}
230+
212231 /// The caller's own pomodoro log, newest first — the running session (if any)
213232 /// included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of
214233 /// finished-session durations. Paged via `?limit=&offset=` (omit `limit` for
215234 /// the whole log).
235+///
236+/// `from`/`to` (unix milliseconds) narrow the log to sessions that started in
237+/// the half-open window `[from, to)` — both optional, AND-ed when both are
238+/// given, negative values a `400`. The window bounds the page, `total` and
239+/// `total_focus_ms` alike: the focus total is the sum over the same filtered
240+/// set the page reads, and with neither bound the response is the
241+/// whole-history log, unchanged.
216242 #[utoipa::path(
217243 get,
218244 path = "/me",
219245 tag = "pomodoro",
220246 security(("session_cookie" = [])),
221- params(PageParams),
247+ params(PageParams, HistoryFilter),
222248 responses(
223249 (status = 200, description = "A page of the caller's pomodoro log with the unpaged focus total", body = PomodoroLog),
224- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
250+ (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse),
225251 (status = 401, description = "Not authenticated", body = ErrorResponse),
226252 ),
227253 )]
@@ -229,24 +255,31 @@ async fn my_pomodoro(
229255 State(st): State<AppState>,
230256 CurrentUser(user): CurrentUser,
231257 Query(page): Query<PageParams>,
258+ Query(filter): Query<HistoryFilter>,
232259 ) -> Result<Json<PomodoroLog>, AppError> {
233260 let (limit, offset) = page.resolve()?;
234- let sessions = pomodoro::list_for_user(&st.db, user.get_id()).await?;
235- Ok(Json(PomodoroLog::new(&sessions, limit, offset)))
261+ let (from, to) = filter.resolve()?;
262+ let log = pomodoro::page_for_user(&st.db, user.get_id(), from, to, limit, offset).await?;
263+ Ok(Json(PomodoroLog::new(log, limit, offset)))
236264 }
237265
238266 /// A student's pomodoro log, newest first, with `total_focus_ms` — the same
239267 /// shape as `/me`. Requires teacher+ (study oversight), or a parent tied to
240268 /// the target student. Paged via `?limit=&offset=`.
269+///
270+/// Like `/me`, the optional `from`/`to` window (unix milliseconds, the
271+/// half-open `[from, to)`) narrows the log — page, `total` and
272+/// `total_focus_ms` together — and leaves the observation rules untouched: a
273+/// caller who may not read the log cannot read a window of it either.
241274 #[utoipa::path(
242275 get,
243276 path = "/{user}",
244277 tag = "pomodoro",
245278 security(("session_cookie" = [])),
246- params(("user" = String, Path, description = "User id"), PageParams),
279+ params(("user" = String, Path, description = "User id"), PageParams, HistoryFilter),
247280 responses(
248281 (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog),
249- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
282+ (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse),
250283 (status = 401, description = "Not authenticated", body = ErrorResponse),
251284 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
252285 (status = 404, description = "User not found", body = ErrorResponse),
@@ -257,14 +290,75 @@ async fn user_pomodoro(
257290 CurrentUser(caller): CurrentUser,
258291 Path(user): Path<String>,
259292 Query(page): Query<PageParams>,
293+ Query(filter): Query<HistoryFilter>,
260294 ) -> Result<Json<PomodoroLog>, AppError> {
261295 let (limit, offset) = page.resolve()?;
296+ let (from, to) = filter.resolve()?;
262297 let target = UserId::from_key(&user);
263298 ensure_can_observe(&caller, &target, &st.db).await?;
264299 // User must exist — a missing user is a 404, not an empty log.
265300 crate::service::user::read(&st.db, &target)
266301 .await?
267302 .ok_or(AppError::NotFound)?;
268- let sessions = pomodoro::list_for_user(&st.db, &target).await?;
269- Ok(Json(PomodoroLog::new(&sessions, limit, offset)))
303+ let log = pomodoro::page_for_user(&st.db, &target, from, to, limit, offset).await?;
304+ Ok(Json(PomodoroLog::new(log, limit, offset)))
305+}
306+
307+#[cfg(test)]
308+mod tests {
309+ use super::*;
310+ use axum::http::Uri;
311+
312+ #[test]
313+ fn an_absent_window_leaves_the_log_untouched() {
314+ let filter = HistoryFilter {
315+ from: None,
316+ to: None,
317+ };
318+ assert_eq!(filter.resolve().unwrap(), (None, None));
319+ }
320+
321+ #[test]
322+ fn a_negative_bound_is_a_400_naming_the_field() {
323+ let filter = HistoryFilter {
324+ from: Some(-1),
325+ to: None,
326+ };
327+ let AppError::Validation(ValidationError::Invalid { field, .. }) =
328+ filter.resolve().unwrap_err()
329+ else {
330+ panic!("a negative `from` must be a validation error");
331+ };
332+ assert_eq!(field, "from");
333+
334+ let filter = HistoryFilter {
335+ from: None,
336+ to: Some(-1),
337+ };
338+ let AppError::Validation(ValidationError::Invalid { field, .. }) =
339+ filter.resolve().unwrap_err()
340+ else {
341+ panic!("a negative `to` must be a validation error");
342+ };
343+ assert_eq!(field, "to");
344+ }
345+
346+ #[test]
347+ fn zero_is_a_legal_bound() {
348+ let filter = HistoryFilter {
349+ from: Some(0),
350+ to: Some(0),
351+ };
352+ assert_eq!(filter.resolve().unwrap(), (Some(0), Some(0)));
353+ }
354+
355+ #[test]
356+ fn a_present_but_empty_bound_is_a_400_naming_the_field() {
357+ // `?from=` carries no i64: the query extractor itself refuses, the
358+ // same 400 `?limit=` has always given for an empty value.
359+ let err = Query::<HistoryFilter>::try_from_uri(&Uri::from_static("/?from=&to=5"))
360+ .unwrap_err();
361+ assert_eq!(err.status(), StatusCode::BAD_REQUEST);
362+ assert!(err.body_text().contains("from"), "{}", err.body_text());
363+ }
270364 }
src/web/questions.rsmodified+17 -14
@@ -38,7 +38,7 @@ use crate::web::tenant_state::State;
3838
3939 use super::{
4040 CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm,
41- paginate, person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob,
41+ person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob,
4242 };
4343
4444 pub fn routes() -> OpenApiRouter<AppState> {
@@ -296,6 +296,11 @@ async fn ask_question(
296296 /// `approved` question; `pending` ones appear only to their asker and to
297297 /// teacher+ — so for a teacher, `?status=pending` is the approval queue.
298298 /// Paged via `?limit=&offset=`.
299+///
300+/// The visibility gate and the `status` filter share one SQL `WHERE`, so
301+/// `total` counts the filtered set — `?status=pending` never loads the whole
302+/// pool into a `Vec` first. A `status` other than `pending` or `approved`
303+/// is a 400.
299304 #[utoipa::path(
300305 get,
301306 path = "/",
@@ -316,8 +321,9 @@ async fn list_questions(
316321 Query(page): Query<PageParams>,
317322 ) -> Result<Json<Page<PoolQuestionResponse>>, AppError> {
318323 let (limit, offset) = page.resolve()?;
319- if let Some(ref status) = filter.status
320- && !POOL_QUESTION_STATUSES.contains(&status.as_str())
324+ let status = filter.status.as_deref().map(str::trim);
325+ if let Some(status) = status
326+ && !POOL_QUESTION_STATUSES.contains(&status)
321327 {
322328 return Err(AppError::Validation(ValidationError::Invalid {
323329 field: "status",
@@ -325,18 +331,15 @@ async fn list_questions(
325331 }));
326332 }
327333
328- let mut questions = if user.get_role().at_least(Role::Teacher) {
329- pool_question::list_all(&st.db).await?
330- } else {
331- pool_question::list_visible_to(&st.db, user.get_id()).await?
332- };
333- if let Some(ref status) = filter.status {
334- questions.retain(|question| question.get_status() == status);
335- }
334+ // Visibility stays exactly what the two reads encoded: teacher+ see the
335+ // approval queue and the pool, everyone else the pool plus their own
336+ // pending questions. Gate and status filter ride one SQL WHERE — `total`
337+ // is the filtered count, and the window is the database's.
338+ let viewer = (!user.get_role().at_least(Role::Teacher)).then_some(user.get_id());
339+ let (questions, total) =
340+ pool_question::list(&st.db, viewer, status, limit, offset).await?;
336341
337- let total = questions.len() as i64;
338- // Paged in the web layer: the status filter above is per-row Rust.
339- let items = question_responses(paginate(&questions, limit, offset), &st).await?;
342+ let items = question_responses(&questions, &st).await?;
340343 Ok(Json(Page::new(items, total, limit, offset)))
341344 }
342345
src/web/users.rsmodified+101 -3
@@ -365,19 +365,67 @@ async fn search_users(
365365 Ok(Json(Page::new(items, total, limit, offset)))
366366 }
367367
368+/// The admin directory's optional `roles` narrowing: a comma-separated list
369+/// of role names, e.g. `roles=manager,admin` for the two staff tabs in one
370+/// read. Absent (`None`) is every user — today's response, unchanged.
371+#[derive(Debug, Deserialize, IntoParams)]
372+struct ListUsersFilter {
373+ /// Keep only users whose role is in this comma-separated set: `student`,
374+ /// `parent`, `teacher`, `manager`, or `admin` (an OR, not an AND). Omit
375+ /// to list every role.
376+ roles: Option<String>,
377+}
378+
379+impl ListUsersFilter {
380+ /// Resolve `roles` into the filter set. Each token is trimmed, then
381+ /// parsed with [`Role::try_from_str`] — the same vocabulary
382+ /// `GET /users/search` parses `role` with. An empty value (`?roles=`), a
383+ /// blank token (`roles=manager,`), or an unknown name is a `400` naming
384+ /// `roles` — the same refusal shape every other closed set answers with,
385+ /// never a silently empty page.
386+ fn resolve(&self) -> Result<Option<Vec<Role>>, ValidationError> {
387+ let Some(raw) = self.roles.as_deref() else {
388+ return Ok(None);
389+ };
390+ raw.split(',')
391+ .map(|token| {
392+ Role::try_from_str(token.trim()).map_err(|err| match err {
393+ // The parser names its field `role`; this param is the
394+ // plural `roles`, so the refusal must name what the
395+ // request actually carried.
396+ ValidationError::Invalid { reason, .. } => ValidationError::Invalid {
397+ field: "roles",
398+ reason,
399+ },
400+ err => err,
401+ })
402+ })
403+ .collect::<Result<Vec<_>, _>>()
404+ .map(Some)
405+ }
406+}
407+
368408 /// List every user with their role, newest first. Admin only. Paged: pass
369409 /// `?limit=&offset=` to take a window (omit `limit` for the whole list); the
370410 /// response is a `{items, total, limit, offset}` envelope where `total` counts
371411 /// every user.
412+///
413+/// The optional `roles` parameter narrows the directory to a set of roles —
414+/// a comma-separated list (`roles=manager,admin` is the two staff tabs in
415+/// one read, an OR). Omitted, the response is the whole roster. The window
416+/// and `total` are taken after the narrowing, so `total` counts the filtered
417+/// set and paging stays inside it. Each name is the vocabulary
418+/// `GET /users/search` parses; an unknown name, a blank value, or a blank
419+/// token is a `400` naming `roles`.
372420 #[utoipa::path(
373421 get,
374422 path = "/",
375423 tag = "users",
376424 security(("session_cookie" = [])),
377- params(PageParams),
425+ params(PageParams, ListUsersFilter),
378426 responses(
379427 (status = 200, description = "A page of users (the full list when unpaged)", body = Page<UserResponse>),
380- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
428+ (status = 400, description = "Invalid limit or offset, or an unknown `roles` entry", body = ErrorResponse),
381429 (status = 401, description = "Not authenticated", body = ErrorResponse),
382430 (status = 403, description = "Requires admin role", body = ErrorResponse),
383431 ),
@@ -386,9 +434,12 @@ async fn list_users(
386434 State(st): State<AppState>,
387435 _admin: RequireAdmin,
388436 Query(page): Query<PageParams>,
437+ Query(filter): Query<ListUsersFilter>,
389438 ) -> Result<Json<Page<UserResponse>>, AppError> {
390439 let (limit, offset) = page.resolve()?;
391- let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?;
440+ let roles = filter.resolve()?;
441+ let (users, total) =
442+ crate::service::user::list_all(&st.db, roles.as_deref(), limit, offset).await?;
392443 let items = users.iter().map(UserResponse::new).collect();
393444 Ok(Json(Page::new(items, total, limit, offset)))
394445 }
@@ -1591,3 +1642,50 @@ async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppErro
15911642 remove_blob(&st.files_path, file).await;
15921643 Ok(StatusCode::NO_CONTENT)
15931644 }
1645+
1646+#[cfg(test)]
1647+mod tests {
1648+ use super::*;
1649+
1650+ fn filter(roles: Option<&str>) -> ListUsersFilter {
1651+ ListUsersFilter {
1652+ roles: roles.map(str::to_owned),
1653+ }
1654+ }
1655+
1656+ #[test]
1657+ fn absent_roles_is_every_user() {
1658+ assert_eq!(filter(None).resolve().unwrap(), None);
1659+ }
1660+
1661+ #[test]
1662+ fn roles_parse_into_the_role_set() {
1663+ // The manager tab is one OR set, not an intersection.
1664+ assert_eq!(
1665+ filter(Some("manager,admin")).resolve().unwrap(),
1666+ Some(vec![Role::Manager, Role::Admin])
1667+ );
1668+ assert_eq!(
1669+ filter(Some("student")).resolve().unwrap(),
1670+ Some(vec![Role::Student])
1671+ );
1672+ // A stray space rides the trim, like every other query value.
1673+ assert_eq!(
1674+ filter(Some(" teacher ")).resolve().unwrap(),
1675+ Some(vec![Role::Teacher])
1676+ );
1677+ }
1678+
1679+ #[test]
1680+ fn a_bad_roles_value_is_refused_naming_roles() {
1681+ // Empty value, unknown name, blank token, whitespace-only token, and
1682+ // the non-assignable service principal — all the same field naming.
1683+ for bad in ["", "nope", "manager,", "manager, ,admin", "ai"] {
1684+ let err = filter(Some(bad)).resolve().unwrap_err();
1685+ let ValidationError::Invalid { field, .. } = err else {
1686+ panic!("expected Invalid for {bad:?}, got {err}");
1687+ };
1688+ assert_eq!(field, "roles", "{bad:?} must name the roles field");
1689+ }
1690+ }
1691+}
tests/regress_meals.rsmodified+157 -1
@@ -23,12 +23,17 @@ use serde_json::json;
2323
2424 /// Publish a menu for `date`, uncapped unless told otherwise.
2525 async fn publish(app: &axum::Router, mgr: &str, date: &str) -> String {
26+ publish_slot(app, mgr, date, "lunch").await
27+}
28+
29+/// Publish a menu for `date` under an explicit slot name.
30+async fn publish_slot(app: &axum::Router, mgr: &str, date: &str, slot: &str) -> String {
2631 let res = send(
2732 app,
2833 "POST",
2934 "/meals/menus",
3035 Some(mgr),
31- Some(json!({ "date": date, "slot": "lunch" })),
36+ Some(json!({ "date": date, "slot": slot })),
3237 )
3338 .await;
3439 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() {
14121417 .await;
14131418 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
14141419 }
1420+
1421+/// `?slot=` on `GET /meals/menus` filters in SQL — the page *and* the count
1422+/// off one WHERE — so `total` is the filtered count and `limit`/`offset`
1423+/// window inside the filtered set, not the unfiltered one. The match is the
1424+/// slot text each menu snapshotted at publish: no menu carries it, the page
1425+/// is empty at `200`; an empty value is a `400` naming the field.
1426+#[tokio::test]
1427+async fn the_menu_list_slot_filter_narrows_rows_and_total_together() {
1428+ let (app, db) = app_and_db().await;
1429+ let admin = login_as(&app, &db, "mslot_admin", "admin").await;
1430+ let mgr = login_as(&app, &db, "mslot_mgr", "manager").await;
1431+ // Two slots, so a filter has something to exclude.
1432+ let res = send(
1433+ &app,
1434+ "PATCH",
1435+ "/settings",
1436+ Some(&admin),
1437+ Some(json!({ "meal_slots": [{ "name": "lunch" }, { "name": "dinner" }] })),
1438+ )
1439+ .await;
1440+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1441+
1442+ for (date, slot) in [
1443+ ("2099-03-01", "lunch"),
1444+ ("2099-03-02", "dinner"),
1445+ ("2099-03-03", "lunch"),
1446+ ("2099-03-04", "dinner"),
1447+ ] {
1448+ publish_slot(&app, &mgr, date, slot).await;
1449+ }
1450+
1451+ // Absent: every menu, exactly as before the filter existed.
1452+ let res = send(&app, "GET", "/meals/menus", Some(&mgr), None).await;
1453+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1454+ assert_eq!(res.body["total"].as_i64(), Some(4), "{}", res.body);
1455+
1456+ // Matched: only that slot's menus, and `total` is the filtered count —
1457+ // neither the page size nor the unfiltered total.
1458+ let res = send(&app, "GET", "/meals/menus?slot=dinner", Some(&mgr), None).await;
1459+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1460+ let items = res.body["items"].as_array().unwrap();
1461+ assert_eq!(items.len(), 2, "{}", res.body);
1462+ assert!(items.iter().all(|m| m["slot"] == "dinner"), "{}", res.body);
1463+ assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body);
1464+
1465+ // The window applies *after* the filter: one dinner per page, two pages,
1466+ // and `total` stays the filtered count on both.
1467+ let res = send(
1468+ &app,
1469+ "GET",
1470+ "/meals/menus?slot=dinner&limit=1&offset=1",
1471+ Some(&mgr),
1472+ None,
1473+ )
1474+ .await;
1475+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1476+ let items = res.body["items"].as_array().unwrap();
1477+ assert_eq!(items.len(), 1, "{}", res.body);
1478+ // Newest day first within the filtered set.
1479+ assert_eq!(items[0]["date"], "2099-03-02", "{}", res.body);
1480+ assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body);
1481+
1482+ // Composes with the date range: the lunch menus inside it only.
1483+ let res = send(
1484+ &app,
1485+ "GET",
1486+ "/meals/menus?slot=lunch&from=2099-03-02&to=2099-03-04",
1487+ Some(&mgr),
1488+ None,
1489+ )
1490+ .await;
1491+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1492+ assert_eq!(res.body["total"].as_i64(), Some(1), "{}", res.body);
1493+ assert_eq!(res.body["items"][0]["date"], "2099-03-03", "{}", res.body);
1494+
1495+ // The value is trimmed before matching.
1496+ let res = send(&app, "GET", "/meals/menus?slot=%20dinner%20", Some(&mgr), None).await;
1497+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1498+ assert_eq!(res.body["total"].as_i64(), Some(2), "{}", res.body);
1499+
1500+ // A well-formed name no menu carries: an empty page at `200`, not a 404.
1501+ let res = send(&app, "GET", "/meals/menus?slot=brunch", Some(&mgr), None).await;
1502+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1503+ assert_eq!(
1504+ res.body["items"].as_array().unwrap().len(),
1505+ 0,
1506+ "{}",
1507+ res.body
1508+ );
1509+ assert_eq!(res.body["total"].as_i64(), Some(0), "{}", res.body);
1510+
1511+ // Empty: refused, naming the field.
1512+ let res = send(&app, "GET", "/meals/menus?slot=", Some(&mgr), None).await;
1513+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
1514+ assert!(
1515+ res.body["error"].as_str().unwrap().contains("slot"),
1516+ "the refusal must name the field: {}",
1517+ res.body
1518+ );
1519+}
1520+
1521+/// The slot filter must *not* validate against the school's current
1522+/// `meal_slots`: a menu snapshots its slot's name at publish, so a slot
1523+/// retired since still has to find the menus published under it. The write
1524+/// path itself refuses to drop a slot that has menus (`409`), so a retired
1525+/// slot with menus exists only where a settings row written before that rule
1526+/// left one behind — the state this test writes by hand, like its
1527+/// `a_slot_whose_name_would_break_the_menu_url` sibling does.
1528+#[tokio::test]
1529+async fn a_retired_slot_still_finds_the_menus_published_under_it() {
1530+ let (app, db) = app_and_db().await;
1531+ let admin = login_as(&app, &db, "ret_adm", "admin").await;
1532+ let mgr = login_as(&app, &db, "ret_mgr", "manager").await;
1533+ let res = send(
1534+ &app,
1535+ "PATCH",
1536+ "/settings",
1537+ Some(&admin),
1538+ Some(json!({ "meal_slots": [{ "name": "brunch" }] })),
1539+ )
1540+ .await;
1541+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1542+ publish_slot(&app, &mgr, "2099-04-01", "brunch").await;
1543+
1544+ // The live route refuses the retirement — that guard is what makes the
1545+ // retired-but-published state reachable only through older rows.
1546+ let res = send(
1547+ &app,
1548+ "PATCH",
1549+ "/settings",
1550+ Some(&admin),
1551+ Some(json!({ "meal_slots": [{ "name": "lunch" }] })),
1552+ )
1553+ .await;
1554+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1555+
1556+ // …so the retirement lands the way history actually left one: a settings
1557+ // row written before the guard existed.
1558+ sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'")
1559+ .bind(sqlx::types::Json(json!([
1560+ { "name": "lunch", "serving_minute": null }
1561+ ])))
1562+ .execute(&db)
1563+ .await
1564+ .unwrap();
1565+
1566+ let res = send(&app, "GET", "/meals/menus?slot=brunch", Some(&mgr), None).await;
1567+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1568+ assert_eq!(res.body["total"].as_i64(), Some(1), "{}", res.body);
1569+ assert_eq!(res.body["items"][0]["slot"], "brunch", "{}", res.body);
1570+}