diff --git a/README.md b/README.md index fd5b444..a8af348 100644 --- a/README.md +++ b/README.md @@ -431,6 +431,19 @@ their existing shapes: the student exam-room reads `/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and `/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`. +**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally +accept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and +independent (AND-ed when both are sent). `ends_after=T` keeps rows whose window +has not finished — `ends_at > T`, falling back to `starts_at > T` when `ends_at` +is `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no +schedule at all (an event without times, an exam with no `mode` or in `open` +mode) is excluded by either parameter. Supplying either one flips the order to +**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id), +so `?ends_after=&limit=20` gives the twenty *soonest* rows instead of the +twenty newest-created — with neither parameter the list is byte-for-byte the +newest-first list it always was. `total` is the count after visibility *and* +window filtering, before paging; negative values are a `400` naming the field. + | Method | Path | Auth | Description | |--------|----------------------------------|---------|---------------------------------| | GET | `/health` | no | Liveness check | @@ -469,7 +482,7 @@ their existing shapes: the student exam-room reads | PATCH | `/messages/{id}` | student | `{read?, folder?}` — read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) | | DELETE | `/messages/{id}` | student | Permanently delete **own copy** — only from the trash (`409` elsewhere); the row vanishes once both sides deleted | | POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` — `audience` defaults to school-wide | -| GET | `/events` | student | List all events · paged | +| GET | `/events` | student | List all events · paged · `?starts_after=&ends_after=` window (soonest first) | | GET | `/events/{id}` | student | Get event | | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale | | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) | @@ -517,7 +530,7 @@ their existing shapes: the student exam-room reads | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written | | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged | -| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged | +| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged · `?starts_after=&ends_after=` window (soonest first) | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) | | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) | diff --git a/src/lib.rs b/src/lib.rs index 115e09c..adef32a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,7 +47,7 @@ use crate::state::AppState; (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), - (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"), + (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), @@ -55,7 +55,7 @@ use crate::state::AppState; (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), + (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), diff --git a/src/web/events.rs b/src/web/events.rs index 140fb2e..457e5e7 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -23,10 +23,24 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range, - paginate, person_map, set_or_clear, + CurrentUser, Page, PageParams, PersonRef, RequireTeacher, Scheduled, WindowParams, + check_not_past, check_time_range, paginate, person_map, set_or_clear, }; +impl Scheduled for Event { + fn starts_at_ms(&self) -> Option { + self.get_starts_at().map(|at| at.as_millis()) + } + + fn ends_at_ms(&self) -> Option { + self.get_ends_at().map(|at| at.as_millis()) + } + + fn order_key(&self) -> &str { + self.get_id().key() + } +} + pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(create_event, list_events)) @@ -259,25 +273,32 @@ async fn create_event( /// List all events, newest first. Paged via `?limit=&offset=` (omit `limit` /// for every event); returns a `{items, total, limit, offset}` envelope. +/// +/// The optional `?starts_after=&ends_after=` schedule window (unix +/// milliseconds) narrows the list to upcoming/unfinished events and flips the +/// order to ascending by schedule, so `?ends_after=&limit=20` returns the +/// twenty *soonest* events rather than the twenty newest-created. Events with +/// no schedule are excluded by either parameter. #[utoipa::path( get, path = "/", tag = "events", security(("session_cookie" = [])), - params(PageParams), + params(WindowParams, PageParams), responses( (status = 200, description = "A page of events (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_events( State(st): State, _user: CurrentUser, + Query(window): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let events = Event::list_all(&st.db).await?; + let events = window.apply(Event::list_all(&st.db).await?)?; let total = events.len() as i64; let items = paginate(&events, limit, offset) .iter() diff --git a/src/web/exams.rs b/src/web/exams.rs index c6e91f5..efec2b4 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -40,11 +40,25 @@ use super::bank_questions::BankQuestionResponse; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::subjects::subject_in_course; use super::{ - ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, - UploadFileForm, blob_path, check_not_past, image_content_type, paginate, person_map, - read_upload, remove_blob, set_or_clear, + ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, Scheduled, + UploadFileForm, WindowParams, blob_path, check_not_past, image_content_type, paginate, + person_map, read_upload, remove_blob, set_or_clear, }; +impl Scheduled for Exam { + fn starts_at_ms(&self) -> Option { + self.get_starts_at().map(|at| at.as_millis()) + } + + fn ends_at_ms(&self) -> Option { + self.get_ends_at().map(|at| at.as_millis()) + } + + fn order_key(&self) -> &str { + self.get_id().key() + } +} + /// Serializes the exam subsystem's cross-record check-then-writes, which /// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`. /// Read side: the answer saves (REST and the exam room), holding the sheet @@ -234,21 +248,29 @@ async fn course_of(exam: &Exam, db: &Database) -> Result { /// people's drafts (a draft shows only to its course's managers). Paged via /// `?limit=&offset=` (omit `limit` for the full list); returns a /// `{items, total, limit, offset}` envelope. +/// +/// The optional `?starts_after=&ends_after=` schedule window (unix +/// milliseconds) applies *after* the visibility and draft filtering, narrows +/// the list to upcoming/unfinished exams and flips the order to ascending by +/// schedule — so `?ends_after=&limit=20` returns the twenty *soonest* +/// exams rather than the twenty newest-created. Exams without a window +/// (no `mode`, or `open`) are excluded by either parameter. #[utoipa::path( get, path = "/", tag = "exams", security(("session_cookie" = [])), - params(PageParams), + params(WindowParams, PageParams), responses( (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_exams( State(st): State, CurrentUser(user): CurrentUser, + Query(window): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; @@ -268,6 +290,7 @@ async fn list_exams( exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key())); exams }; + let exams = window.apply(exams)?; let total = exams.len() as i64; let items = paginate(&exams, limit, offset) .iter() diff --git a/src/web/mod.rs b/src/web/mod.rs index b47b404..6fed325 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -36,7 +36,7 @@ pub use dto::{ UserResponse, course_people, person_map, }; pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; -pub use page::{Page, PageParams, paginate}; +pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; use std::path::{Path as FsPath, PathBuf}; diff --git a/src/web/page.rs b/src/web/page.rs index b786b25..2769ad5 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -55,6 +55,73 @@ impl PageParams { } } +/// A row that carries a schedule window, so [`WindowParams`] can filter and +/// order it. Both ends are optional unix milliseconds; `order_key` is the row +/// id key, used only to break ties so paging stays stable. +pub trait Scheduled { + fn starts_at_ms(&self) -> Option; + fn ends_at_ms(&self) -> Option; + fn order_key(&self) -> &str; +} + +/// The optional `?starts_after=&ends_after=` schedule window on a list of +/// scheduled rows. Both are unix milliseconds and independent (AND-ed when +/// both are given). Omit both and the list is untouched — same order, same +/// total as an unfiltered call. +#[derive(Debug, Deserialize, IntoParams)] +pub struct WindowParams { + /// Keep only rows starting strictly after this unix-millisecond instant. + /// Rows without a `starts_at` are dropped. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + pub starts_after: Option, + /// Keep only rows whose window has not finished by this unix-millisecond + /// instant: `ends_at > value`, falling back to `starts_at > value` when + /// `ends_at` is null. Rows with no schedule at all are dropped. + #[param(minimum = 0, example = 1_760_000_000_000_i64)] + pub ends_after: Option, +} + +impl WindowParams { + /// Apply the window to an already-visibility-filtered list. With neither + /// parameter the list is returned untouched; with either, schedule-less + /// rows are dropped and the survivors are sorted ascending by `starts_at` + /// (falling back to `ends_at`), ties broken by id. A negative value is a + /// `400` naming the field. + pub fn apply(&self, mut items: Vec) -> Result, AppError> { + for (field, value) in [ + ("starts_after", self.starts_after), + ("ends_after", self.ends_after), + ] { + if value.is_some_and(|value| value < 0) { + return Err(AppError::Validation(ValidationError::Invalid { + field, + reason: "must not be negative", + })); + } + } + if self.starts_after.is_none() && self.ends_after.is_none() { + return Ok(items); + } + items.retain(|item| { + let starts = item.starts_at_ms(); + let ends = item.ends_at_ms(); + self.starts_after.is_none_or(|after| starts > Some(after)) + && self + .ends_after + .is_none_or(|after| ends.or(starts) > Some(after)) + }); + // Every survivor has at least one end, so the fallback never yields + // `None` — but sort defensively rather than unwrapping. + items.sort_by(|a, b| { + let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms()); + key(a) + .cmp(&key(b)) + .then_with(|| a.order_key().cmp(b.order_key())) + }); + Ok(items) + } +} + /// One page of a list: the `items`, the full `total` (row count before the /// window), and the `limit`/`offset` that produced it. `limit` is `null` when /// the caller asked for every row. @@ -122,6 +189,82 @@ mod tests { assert!(params(None, Some(-1)).resolve().is_err()); } + struct Row(&'static str, Option, Option); + + impl Scheduled for Row { + fn starts_at_ms(&self) -> Option { + self.1 + } + fn ends_at_ms(&self) -> Option { + self.2 + } + fn order_key(&self) -> &str { + self.0 + } + } + + fn rows() -> Vec { + vec![ + Row("none", None, None), + Row("running", Some(10), Some(40)), + Row("later", Some(30), None), + Row("ending", None, Some(20)), + Row("tie", Some(30), Some(50)), + ] + } + + fn keys(window: WindowParams) -> Vec<&'static str> { + window + .apply(rows()) + .unwrap() + .iter() + .map(|row| row.0) + .collect() + } + + fn window(starts_after: Option, ends_after: Option) -> WindowParams { + WindowParams { + starts_after, + ends_after, + } + } + + #[test] + fn window_absent_leaves_the_list_untouched() { + assert_eq!( + keys(window(None, None)), + ["none", "running", "later", "ending", "tie"] + ); + } + + #[test] + fn ends_after_keeps_unfinished_rows_and_falls_back_to_starts_at() { + // `ending` has no start (kept on ends_at), `later` no end (kept on the + // starts_at fallback), `none` has neither and always drops. Ascending + // by starts_at ?? ends_at, ties broken by key. + assert_eq!( + keys(window(None, Some(15))), + ["running", "ending", "later", "tie"] + ); + // At 25, `ending` (ends 20) is over; `running` (ends 40) is not. + assert_eq!(keys(window(None, Some(25))), ["running", "later", "tie"]); + } + + #[test] + fn starts_after_excludes_started_and_start_less_rows() { + assert_eq!(keys(window(Some(25), None)), ["later", "tie"]); + // AND-ed with ends_after: `tie` ends at 50, while `later` has no end + // and its starts_at fallback (30) is already behind 45. + assert_eq!(keys(window(Some(25), Some(45))), ["tie"]); + assert!(keys(window(Some(60), None)).is_empty()); + } + + #[test] + fn window_rejects_negative_values() { + assert!(window(Some(-1), None).apply(rows()).is_err()); + assert!(window(None, Some(-1)).apply(rows()).is_err()); + } + #[test] fn paginate_windows_and_clamps() { let items: Vec = (0..10).collect(); diff --git a/tests/integration.rs b/tests/integration.rs index dda66b4..50132de 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -19735,3 +19735,172 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { assert_eq!(res.body["capacity"], 9); assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0); } + +// --- schedule-window list filters ---------------------------------------- + +/// Titles of a list envelope, in response order. +fn titles(body: &serde_json::Value) -> Vec { + common::items(body) + .iter() + .map(|item| item["title"].as_str().unwrap().to_string()) + .collect() +} + +#[tokio::test] +async fn events_schedule_window_filters_and_orders() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let now = Timestamp::now().as_millis(); + + // Four events, created oldest-id first: one with no schedule at all, one + // already running (inside the 60s backdating grace), one starting later + // with no end, and one that only carries an end. + for body in [ + json!({ "title": "no-schedule", "description": "" }), + json!({ "title": "running", "starts_at": now - 30_000, "ends_at": now + 600_000 }), + json!({ "title": "later", "starts_at": now + 900_000 }), + json!({ "title": "ending", "ends_at": now + 300_000 }), + ] { + let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; + assert_eq!(res.status, StatusCode::CREATED); + } + + // No window params: unchanged behaviour — every row, newest-created first. + let all = send(&app, "GET", "/events", Some(&ali), None).await; + assert_eq!(common::total(&all.body), 4); + assert_eq!( + titles(&all.body), + ["ending", "later", "running", "no-schedule"] + ); + + // ends_after: keeps unfinished rows (running on ends_at, later on the + // starts_at fallback), drops the schedule-less one, ascending by schedule. + let res = send( + &app, + "GET", + &format!("/events?ends_after={now}"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&res.body), 3); + assert_eq!(titles(&res.body), ["running", "ending", "later"]); + + // Past the running event's end: only the pure-end row and the fallback row. + let res = send( + &app, + "GET", + &format!("/events?ends_after={}", now + 700_000), + Some(&ali), + None, + ) + .await; + assert_eq!(titles(&res.body), ["later"]); + + // starts_after excludes the already-started row and every start-less row. + let res = send( + &app, + "GET", + &format!("/events?starts_after={now}"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1); + assert_eq!(titles(&res.body), ["later"]); + + // total is the filtered, pre-pagination count; the page is the soonest. + let res = send( + &app, + "GET", + &format!("/events?ends_after={now}&limit=1"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&res.body), 3); + assert_eq!(titles(&res.body), ["running"]); + + // Invalid values are a 400 naming the field. + for query in ["starts_after=-1", "ends_after=-1", "ends_after=soon"] { + let res = send(&app, "GET", &format!("/events?{query}"), Some(&ali), None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{query}"); + } +} + +#[tokio::test] +async fn exams_schedule_window_applies_after_visibility_and_drafts() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let ayse = login_as(&app, &db, "ayse", "student").await; + let now = Timestamp::now().as_millis(); + + let course = create_course(&app, &ali, "math").await; + let other = create_course(&app, &ali, "hidden").await; + enroll(&app, &ali, &course, &me_id(&app, &ayse).await).await; + + // Windowed exams in the student's course, plus a draft, an open-mode exam + // (no window at all), and one in a course they cannot see. + for (course, body) in [ + ( + &course, + json!({ "title": "soon", "kind": "quiz", "mode": "sync", + "starts_at": now + 600_000, "ends_at": now + 900_000 }), + ), + ( + &course, + json!({ "title": "late", "kind": "quiz", "mode": "sync", + "starts_at": now + 1_800_000, "ends_at": now + 2_400_000 }), + ), + ( + &course, + json!({ "title": "draft", "kind": "quiz", "mode": "sync", "draft": true, + "starts_at": now + 60_000, "ends_at": now + 120_000 }), + ), + ( + &course, + json!({ "title": "open", "kind": "quiz", "mode": "open" }), + ), + ( + &other, + json!({ "title": "unseen", "kind": "quiz", "mode": "sync", + "starts_at": now + 60_000, "ends_at": now + 120_000 }), + ), + ] { + let res = create_exam_with(&app, &ali, course, body).await; + assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); + } + + // Unfiltered: the student sees their course's non-draft exams only. + let all = send(&app, "GET", "/exams", Some(&ayse), None).await; + assert_eq!(common::total(&all.body), 3); + assert_eq!(titles(&all.body), ["open", "late", "soon"]); + + // Windowed: the draft and the other course stay invisible (the window runs + // after visibility), the window-less open exam drops out, soonest first. + let res = send( + &app, + "GET", + &format!("/exams?ends_after={now}"), + Some(&ayse), + None, + ) + .await; + assert_eq!(common::total(&res.body), 2); + assert_eq!(titles(&res.body), ["soon", "late"]); + + // The teacher's own draft is windowed like any other exam of theirs. + let res = send( + &app, + "GET", + &format!("/exams?starts_after={now}&limit=2"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&res.body), 4); + assert_eq!(titles(&res.body), ["draft", "unseen"]); + + let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); +}