forge
Explore
Log in

Don't you dare go Hollow

πŸ”­ let /events and /exams ask for the next rows, not the newest

Browse files at this commit

b50d48b2c400a03dfb54399d8e8e8036c0511567Ahmet Kaan GümüşParent: 523a565
  • feat
    • πŸ”­ let /events and /exams ask for the next rows, not the newest
Show full message
feat: πŸ”­ let /events and /exams ask for the next rows, not the newest

`?limit=100` handed back the 100 most recently created rows, so an event
scheduled for tomorrow that was created before them never appeared. The
only correct call was to drop `limit` entirely β€” ~3.4 MB per poll β€” and
the frontend has been paying that on every right-nav tab open.

`?starts_after=` / `?ends_after=` (unix ms, both optional) filter on the
schedule instead, and either one flips the order to soonest-first, so
`limit` finally truncates the right end. `ends_after` keeps rows whose
window has not finished, falling back to `starts_at` when `ends_at` is
null; a row with no schedule at all drops out rather than sorting to an
end. Send neither and the list is untouched β€” same order, same total β€”
so nothing has to deploy in lockstep.

For exams the window lands after the visibility split and the draft
retain, so `total` still counts only what the caller may see.
README.mdmodified+15 -2
@@ -431,6 +431,19 @@ their existing shapes: the student exam-room reads
431 `/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and431 `/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and
432 `/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.432 `/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.
433 433
434+**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally
435+accept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and
436+independent (AND-ed when both are sent). `ends_after=T` keeps rows whose window
437+has not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`
438+is `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no
439+schedule at all (an event without times, an exam with no `mode` or in `open`
440+mode) is excluded by either parameter. Supplying either one flips the order to
441+**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),
442+so `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the
443+twenty newest-created β€” with neither parameter the list is byte-for-byte the
444+newest-first list it always was. `total` is the count after visibility *and*
445+window filtering, before paging; negative values are a `400` naming the field.
446+
434 | Method | Path | Auth | Description |447 | Method | Path | Auth | Description |
435 |--------|----------------------------------|---------|---------------------------------|448 |--------|----------------------------------|---------|---------------------------------|
436 | GET | `/health` | no | Liveness check |449 | GET | `/health` | no | Liveness check |
@@ -469,7 +482,7 @@ their existing shapes: the student exam-room reads
469 | PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |482 | PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |
470 | DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |483 | DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |
471 | POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |484 | POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |
472-| GET | `/events` | student | List all events Β· paged |485+| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |
473 | GET | `/events/{id}` | student | Get event |486 | GET | `/events/{id}` | student | Get event |
474 | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |487 | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |
475 | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |488 | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |
@@ -517,7 +530,7 @@ their existing shapes: the student exam-room reads
517 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |530 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
518 | 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 |531 | 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 |
519 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |532 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |
520-| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged |533+| 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) |
521 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |534 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
522 | 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) |535 | 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) |
523 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |536 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |
src/lib.rsmodified+2 -2
@@ -47,7 +47,7 @@ use crate::state::AppState;
47 (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`)"),47 (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`)"),
48 (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"),48 (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"),
49 (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"),49 (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"),
50- (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"),50+ (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"),
51 (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"),51 (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"),
52 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),52 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
53 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),53 (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;
55 (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)"),55 (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)"),
56 (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"),56 (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"),
57 (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"),57 (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"),
58- (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"),58+ (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"),
59 (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"),59 (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"),
60 (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+"),60 (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+"),
61 (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"),61 (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"),
src/web/events.rsmodified+26 -5
@@ -23,10 +23,24 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
23 use crate::state::AppState;23 use crate::state::AppState;
24 24
25 use super::{25 use super::{
26- CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range,26+ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, Scheduled, WindowParams,
27- paginate, person_map, set_or_clear,27+ check_not_past, check_time_range, paginate, person_map, set_or_clear,
28 };28 };
29 29
30+impl Scheduled for Event {
31+ fn starts_at_ms(&self) -> Option<i64> {
32+ self.get_starts_at().map(|at| at.as_millis())
33+ }
34+
35+ fn ends_at_ms(&self) -> Option<i64> {
36+ self.get_ends_at().map(|at| at.as_millis())
37+ }
38+
39+ fn order_key(&self) -> &str {
40+ self.get_id().key()
41+ }
42+}
43+
30 pub fn routes() -> OpenApiRouter<AppState> {44 pub fn routes() -> OpenApiRouter<AppState> {
31 OpenApiRouter::new()45 OpenApiRouter::new()
32 .routes(routes!(create_event, list_events))46 .routes(routes!(create_event, list_events))
@@ -259,25 +273,32 @@ async fn create_event(
259 273
260 /// List all events, newest first. Paged via `?limit=&offset=` (omit `limit`274 /// List all events, newest first. Paged via `?limit=&offset=` (omit `limit`
261 /// for every event); returns a `{items, total, limit, offset}` envelope.275 /// for every event); returns a `{items, total, limit, offset}` envelope.
276+///
277+/// The optional `?starts_after=&ends_after=` schedule window (unix
278+/// milliseconds) narrows the list to upcoming/unfinished events and flips the
279+/// order to ascending by schedule, so `?ends_after=<now>&limit=20` returns the
280+/// twenty *soonest* events rather than the twenty newest-created. Events with
281+/// no schedule are excluded by either parameter.
262 #[utoipa::path(282 #[utoipa::path(
263 get,283 get,
264 path = "/",284 path = "/",
265 tag = "events",285 tag = "events",
266 security(("session_cookie" = [])),286 security(("session_cookie" = [])),
267- params(PageParams),287+ params(WindowParams, PageParams),
268 responses(288 responses(
269 (status = 200, description = "A page of events (all of them when unpaged)", body = Page<EventResponse>),289 (status = 200, description = "A page of events (all of them when unpaged)", body = Page<EventResponse>),
270- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),290+ (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
271 (status = 401, description = "Not authenticated", body = ErrorResponse),291 (status = 401, description = "Not authenticated", body = ErrorResponse),
272 ),292 ),
273 )]293 )]
274 async fn list_events(294 async fn list_events(
275 State(st): State<AppState>,295 State(st): State<AppState>,
276 _user: CurrentUser,296 _user: CurrentUser,
297+ Query(window): Query<WindowParams>,
277 Query(page): Query<PageParams>,298 Query(page): Query<PageParams>,
278 ) -> Result<Json<Page<EventResponse>>, AppError> {299 ) -> Result<Json<Page<EventResponse>>, AppError> {
279 let (limit, offset) = page.resolve()?;300 let (limit, offset) = page.resolve()?;
280- let events = Event::list_all(&st.db).await?;301+ let events = window.apply(Event::list_all(&st.db).await?)?;
281 let total = events.len() as i64;302 let total = events.len() as i64;
282 let items = paginate(&events, limit, offset)303 let items = paginate(&events, limit, offset)
283 .iter()304 .iter()
src/web/exams.rsmodified+28 -5
@@ -40,11 +40,25 @@ use super::bank_questions::BankQuestionResponse;
40 use super::courses::{can_manage_course, can_view_course, visible_courses};40 use super::courses::{can_manage_course, can_view_course, visible_courses};
41 use super::subjects::subject_in_course;41 use super::subjects::subject_in_course;
42 use super::{42 use super::{
43- ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,43+ ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, Scheduled,
44- UploadFileForm, blob_path, check_not_past, image_content_type, paginate, person_map,44+ UploadFileForm, WindowParams, blob_path, check_not_past, image_content_type, paginate,
45- read_upload, remove_blob, set_or_clear,45+ person_map, read_upload, remove_blob, set_or_clear,
46 };46 };
47 47
48+impl Scheduled for Exam {
49+ fn starts_at_ms(&self) -> Option<i64> {
50+ self.get_starts_at().map(|at| at.as_millis())
51+ }
52+
53+ fn ends_at_ms(&self) -> Option<i64> {
54+ self.get_ends_at().map(|at| at.as_millis())
55+ }
56+
57+ fn order_key(&self) -> &str {
58+ self.get_id().key()
59+ }
60+}
61+
48 /// Serializes the exam subsystem's cross-record check-then-writes, which62 /// Serializes the exam subsystem's cross-record check-then-writes, which
49 /// `BEGIN…COMMIT` cannot (write skew) β€” same reasoning as `REGISTER_LOCK`.63 /// `BEGIN…COMMIT` cannot (write skew) β€” same reasoning as `REGISTER_LOCK`.
50 /// Read side: the answer saves (REST and the exam room), holding the sheet64 /// 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<Course, AppError> {
234 /// people's drafts (a draft shows only to its course's managers). Paged via248 /// people's drafts (a draft shows only to its course's managers). Paged via
235 /// `?limit=&offset=` (omit `limit` for the full list); returns a249 /// `?limit=&offset=` (omit `limit` for the full list); returns a
236 /// `{items, total, limit, offset}` envelope.250 /// `{items, total, limit, offset}` envelope.
251+///
252+/// The optional `?starts_after=&ends_after=` schedule window (unix
253+/// milliseconds) applies *after* the visibility and draft filtering, narrows
254+/// the list to upcoming/unfinished exams and flips the order to ascending by
255+/// schedule β€” so `?ends_after=<now>&limit=20` returns the twenty *soonest*
256+/// exams rather than the twenty newest-created. Exams without a window
257+/// (no `mode`, or `open`) are excluded by either parameter.
237 #[utoipa::path(258 #[utoipa::path(
238 get,259 get,
239 path = "/",260 path = "/",
240 tag = "exams",261 tag = "exams",
241 security(("session_cookie" = [])),262 security(("session_cookie" = [])),
242- params(PageParams),263+ params(WindowParams, PageParams),
243 responses(264 responses(
244 (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),265 (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),
245- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),266+ (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
246 (status = 401, description = "Not authenticated", body = ErrorResponse),267 (status = 401, description = "Not authenticated", body = ErrorResponse),
247 ),268 ),
248 )]269 )]
249 async fn list_exams(270 async fn list_exams(
250 State(st): State<AppState>,271 State(st): State<AppState>,
251 CurrentUser(user): CurrentUser,272 CurrentUser(user): CurrentUser,
273+ Query(window): Query<WindowParams>,
252 Query(page): Query<PageParams>,274 Query(page): Query<PageParams>,
253 ) -> Result<Json<Page<ExamResponse>>, AppError> {275 ) -> Result<Json<Page<ExamResponse>>, AppError> {
254 let (limit, offset) = page.resolve()?;276 let (limit, offset) = page.resolve()?;
@@ -268,6 +290,7 @@ async fn list_exams(
268 exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));290 exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
269 exams291 exams
270 };292 };
293+ let exams = window.apply(exams)?;
271 let total = exams.len() as i64;294 let total = exams.len() as i64;
272 let items = paginate(&exams, limit, offset)295 let items = paginate(&exams, limit, offset)
273 .iter()296 .iter()
src/web/mod.rsmodified+1 -1
@@ -36,7 +36,7 @@ pub use dto::{
36 UserResponse, course_people, person_map,36 UserResponse, course_people, person_map,
37 };37 };
38 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};38 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
39-pub use page::{Page, PageParams, paginate};39+pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
40 40
41 use std::path::{Path as FsPath, PathBuf};41 use std::path::{Path as FsPath, PathBuf};
42 42
src/web/page.rsmodified+143 -0
@@ -55,6 +55,73 @@ impl PageParams {
55 }55 }
56 }56 }
57 57
58+/// A row that carries a schedule window, so [`WindowParams`] can filter and
59+/// order it. Both ends are optional unix milliseconds; `order_key` is the row
60+/// id key, used only to break ties so paging stays stable.
61+pub trait Scheduled {
62+ fn starts_at_ms(&self) -> Option<i64>;
63+ fn ends_at_ms(&self) -> Option<i64>;
64+ fn order_key(&self) -> &str;
65+}
66+
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.
71+#[derive(Debug, Deserialize, IntoParams)]
72+pub struct WindowParams {
73+ /// Keep only rows starting strictly after this unix-millisecond instant.
74+ /// Rows without a `starts_at` are dropped.
75+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
76+ pub starts_after: Option<i64>,
77+ /// Keep only rows whose window has not finished by this unix-millisecond
78+ /// instant: `ends_at > value`, falling back to `starts_at > value` when
79+ /// `ends_at` is null. Rows with no schedule at all are dropped.
80+ #[param(minimum = 0, example = 1_760_000_000_000_i64)]
81+ pub ends_after: Option<i64>,
82+}
83+
84+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> {
91+ for (field, value) in [
92+ ("starts_after", self.starts_after),
93+ ("ends_after", self.ends_after),
94+ ] {
95+ if value.is_some_and(|value| value < 0) {
96+ return Err(AppError::Validation(ValidationError::Invalid {
97+ field,
98+ reason: "must not be negative",
99+ }));
100+ }
101+ }
102+ if self.starts_after.is_none() && self.ends_after.is_none() {
103+ return Ok(items);
104+ }
105+ items.retain(|item| {
106+ let starts = item.starts_at_ms();
107+ let ends = item.ends_at_ms();
108+ self.starts_after.is_none_or(|after| starts > Some(after))
109+ && self
110+ .ends_after
111+ .is_none_or(|after| ends.or(starts) > Some(after))
112+ });
113+ // Every survivor has at least one end, so the fallback never yields
114+ // `None` β€” but sort defensively rather than unwrapping.
115+ items.sort_by(|a, b| {
116+ let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms());
117+ key(a)
118+ .cmp(&key(b))
119+ .then_with(|| a.order_key().cmp(b.order_key()))
120+ });
121+ Ok(items)
122+ }
123+}
124+
58 /// One page of a list: the `items`, the full `total` (row count before the125 /// One page of a list: the `items`, the full `total` (row count before the
59 /// window), and the `limit`/`offset` that produced it. `limit` is `null` when126 /// window), and the `limit`/`offset` that produced it. `limit` is `null` when
60 /// the caller asked for every row.127 /// the caller asked for every row.
@@ -122,6 +189,82 @@ mod tests {
122 assert!(params(None, Some(-1)).resolve().is_err());189 assert!(params(None, Some(-1)).resolve().is_err());
123 }190 }
124 191
192+ struct Row(&'static str, Option<i64>, Option<i64>);
193+
194+ impl Scheduled for Row {
195+ fn starts_at_ms(&self) -> Option<i64> {
196+ self.1
197+ }
198+ fn ends_at_ms(&self) -> Option<i64> {
199+ self.2
200+ }
201+ fn order_key(&self) -> &str {
202+ self.0
203+ }
204+ }
205+
206+ fn rows() -> Vec<Row> {
207+ vec![
208+ Row("none", None, None),
209+ Row("running", Some(10), Some(40)),
210+ Row("later", Some(30), None),
211+ Row("ending", None, Some(20)),
212+ Row("tie", Some(30), Some(50)),
213+ ]
214+ }
215+
216+ fn keys(window: WindowParams) -> Vec<&'static str> {
217+ window
218+ .apply(rows())
219+ .unwrap()
220+ .iter()
221+ .map(|row| row.0)
222+ .collect()
223+ }
224+
225+ fn window(starts_after: Option<i64>, ends_after: Option<i64>) -> WindowParams {
226+ WindowParams {
227+ starts_after,
228+ ends_after,
229+ }
230+ }
231+
232+ #[test]
233+ fn window_absent_leaves_the_list_untouched() {
234+ assert_eq!(
235+ keys(window(None, None)),
236+ ["none", "running", "later", "ending", "tie"]
237+ );
238+ }
239+
240+ #[test]
241+ fn ends_after_keeps_unfinished_rows_and_falls_back_to_starts_at() {
242+ // `ending` has no start (kept on ends_at), `later` no end (kept on the
243+ // starts_at fallback), `none` has neither and always drops. Ascending
244+ // by starts_at ?? ends_at, ties broken by key.
245+ assert_eq!(
246+ keys(window(None, Some(15))),
247+ ["running", "ending", "later", "tie"]
248+ );
249+ // At 25, `ending` (ends 20) is over; `running` (ends 40) is not.
250+ assert_eq!(keys(window(None, Some(25))), ["running", "later", "tie"]);
251+ }
252+
253+ #[test]
254+ fn starts_after_excludes_started_and_start_less_rows() {
255+ assert_eq!(keys(window(Some(25), None)), ["later", "tie"]);
256+ // AND-ed with ends_after: `tie` ends at 50, while `later` has no end
257+ // 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());
260+ }
261+
262+ #[test]
263+ 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());
266+ }
267+
125 #[test]268 #[test]
126 fn paginate_windows_and_clamps() {269 fn paginate_windows_and_clamps() {
127 let items: Vec<i64> = (0..10).collect();270 let items: Vec<i64> = (0..10).collect();
tests/integration.rsmodified+169 -0
@@ -19735,3 +19735,172 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() {
19735 assert_eq!(res.body["capacity"], 9);19735 assert_eq!(res.body["capacity"], 9);
19736 assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0);19736 assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0);
19737 }19737 }
19738+
19739+// --- schedule-window list filters ----------------------------------------
19740+
19741+/// Titles of a list envelope, in response order.
19742+fn titles(body: &serde_json::Value) -> Vec<String> {
19743+ common::items(body)
19744+ .iter()
19745+ .map(|item| item["title"].as_str().unwrap().to_string())
19746+ .collect()
19747+}
19748+
19749+#[tokio::test]
19750+async fn events_schedule_window_filters_and_orders() {
19751+ let (app, db) = app_and_db().await;
19752+ let ali = login_as(&app, &db, "ali", "teacher").await;
19753+ let now = Timestamp::now().as_millis();
19754+
19755+ // Four events, created oldest-id first: one with no schedule at all, one
19756+ // already running (inside the 60s backdating grace), one starting later
19757+ // with no end, and one that only carries an end.
19758+ for body in [
19759+ json!({ "title": "no-schedule", "description": "" }),
19760+ json!({ "title": "running", "starts_at": now - 30_000, "ends_at": now + 600_000 }),
19761+ json!({ "title": "later", "starts_at": now + 900_000 }),
19762+ json!({ "title": "ending", "ends_at": now + 300_000 }),
19763+ ] {
19764+ let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await;
19765+ assert_eq!(res.status, StatusCode::CREATED);
19766+ }
19767+
19768+ // No window params: unchanged behaviour β€” every row, newest-created first.
19769+ let all = send(&app, "GET", "/events", Some(&ali), None).await;
19770+ assert_eq!(common::total(&all.body), 4);
19771+ assert_eq!(
19772+ titles(&all.body),
19773+ ["ending", "later", "running", "no-schedule"]
19774+ );
19775+
19776+ // ends_after: keeps unfinished rows (running on ends_at, later on the
19777+ // starts_at fallback), drops the schedule-less one, ascending by schedule.
19778+ let res = send(
19779+ &app,
19780+ "GET",
19781+ &format!("/events?ends_after={now}"),
19782+ Some(&ali),
19783+ None,
19784+ )
19785+ .await;
19786+ assert_eq!(common::total(&res.body), 3);
19787+ assert_eq!(titles(&res.body), ["running", "ending", "later"]);
19788+
19789+ // Past the running event's end: only the pure-end row and the fallback row.
19790+ let res = send(
19791+ &app,
19792+ "GET",
19793+ &format!("/events?ends_after={}", now + 700_000),
19794+ Some(&ali),
19795+ None,
19796+ )
19797+ .await;
19798+ assert_eq!(titles(&res.body), ["later"]);
19799+
19800+ // starts_after excludes the already-started row and every start-less row.
19801+ let res = send(
19802+ &app,
19803+ "GET",
19804+ &format!("/events?starts_after={now}"),
19805+ Some(&ali),
19806+ None,
19807+ )
19808+ .await;
19809+ assert_eq!(common::total(&res.body), 1);
19810+ assert_eq!(titles(&res.body), ["later"]);
19811+
19812+ // total is the filtered, pre-pagination count; the page is the soonest.
19813+ let res = send(
19814+ &app,
19815+ "GET",
19816+ &format!("/events?ends_after={now}&limit=1"),
19817+ Some(&ali),
19818+ None,
19819+ )
19820+ .await;
19821+ assert_eq!(common::total(&res.body), 3);
19822+ assert_eq!(titles(&res.body), ["running"]);
19823+
19824+ // Invalid values are a 400 naming the field.
19825+ for query in ["starts_after=-1", "ends_after=-1", "ends_after=soon"] {
19826+ let res = send(&app, "GET", &format!("/events?{query}"), Some(&ali), None).await;
19827+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{query}");
19828+ }
19829+}
19830+
19831+#[tokio::test]
19832+async fn exams_schedule_window_applies_after_visibility_and_drafts() {
19833+ let (app, db) = app_and_db().await;
19834+ let ali = login_as(&app, &db, "ali", "teacher").await;
19835+ let ayse = login_as(&app, &db, "ayse", "student").await;
19836+ let now = Timestamp::now().as_millis();
19837+
19838+ let course = create_course(&app, &ali, "math").await;
19839+ let other = create_course(&app, &ali, "hidden").await;
19840+ enroll(&app, &ali, &course, &me_id(&app, &ayse).await).await;
19841+
19842+ // Windowed exams in the student's course, plus a draft, an open-mode exam
19843+ // (no window at all), and one in a course they cannot see.
19844+ for (course, body) in [
19845+ (
19846+ &course,
19847+ json!({ "title": "soon", "kind": "quiz", "mode": "sync",
19848+ "starts_at": now + 600_000, "ends_at": now + 900_000 }),
19849+ ),
19850+ (
19851+ &course,
19852+ json!({ "title": "late", "kind": "quiz", "mode": "sync",
19853+ "starts_at": now + 1_800_000, "ends_at": now + 2_400_000 }),
19854+ ),
19855+ (
19856+ &course,
19857+ json!({ "title": "draft", "kind": "quiz", "mode": "sync", "draft": true,
19858+ "starts_at": now + 60_000, "ends_at": now + 120_000 }),
19859+ ),
19860+ (
19861+ &course,
19862+ json!({ "title": "open", "kind": "quiz", "mode": "open" }),
19863+ ),
19864+ (
19865+ &other,
19866+ json!({ "title": "unseen", "kind": "quiz", "mode": "sync",
19867+ "starts_at": now + 60_000, "ends_at": now + 120_000 }),
19868+ ),
19869+ ] {
19870+ let res = create_exam_with(&app, &ali, course, body).await;
19871+ assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body);
19872+ }
19873+
19874+ // Unfiltered: the student sees their course's non-draft exams only.
19875+ let all = send(&app, "GET", "/exams", Some(&ayse), None).await;
19876+ assert_eq!(common::total(&all.body), 3);
19877+ assert_eq!(titles(&all.body), ["open", "late", "soon"]);
19878+
19879+ // Windowed: the draft and the other course stay invisible (the window runs
19880+ // after visibility), the window-less open exam drops out, soonest first.
19881+ let res = send(
19882+ &app,
19883+ "GET",
19884+ &format!("/exams?ends_after={now}"),
19885+ Some(&ayse),
19886+ None,
19887+ )
19888+ .await;
19889+ assert_eq!(common::total(&res.body), 2);
19890+ assert_eq!(titles(&res.body), ["soon", "late"]);
19891+
19892+ // The teacher's own draft is windowed like any other exam of theirs.
19893+ let res = send(
19894+ &app,
19895+ "GET",
19896+ &format!("/exams?starts_after={now}&limit=2"),
19897+ Some(&ali),
19898+ None,
19899+ )
19900+ .await;
19901+ assert_eq!(common::total(&res.body), 4);
19902+ assert_eq!(titles(&res.body), ["draft", "unseen"]);
19903+
19904+ let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await;
19905+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
19906+}