forge
Explore
Log in

Don't you dare go Hollow

Manager-assigned course teachers

Browse files at this commit

5ff771b632757a16cbf1c8791ae917022f45bedeAhmet Kaan GümüşParent: bdde827
  • feat
    • manager-assigned course teachers
Show full message
✨ feat(courses): manager-assigned course teachers

A course used to have exactly one manager: its creator. A teacher taking
over someone else's class needed manager+, which is the wrong bar for
ordinary staffing.

Courses now carry a `teachers` list alongside the (still immutable)
`creator`. Manager+ assigns and unassigns via POST/DELETE
/courses/{id}/teachers; the assignee must already hold teacher+, since
every gate behind the assignment re-checks that bar anyway.

The rights split in two:

- can_manage_course: creator, assigned teacher, or manager+. Everything
  inside the course — edit, enroll, exams, sessions, subjects, grading,
  roll call. Every existing gate routes through this one helper, so
  assignment reaches all of them at once.
- owns_course: creator or manager+ only. Deleting the course and changing
  who teaches it. An assigned teacher runs a course; they don't own it,
  and can't delete it out from under the person who made it.

Staffing is deliberately manager-only: a course's own creator cannot hand
management rights to their peers.

Stale data: rows written before the field decode as unassigned (a serde
default on the field) and the boot backfill fills them to []. DDL and
backfill stay in separate batches — sharing one silently strips keys on
SurrealDB 3. Verified against the real volume, not just the in-memory
tests: a legacy-shaped row backfilled, rendered, and took an assignment.

A demotion below teacher sweeps the user off every course they were
assigned to, mirroring how promotion drops enrollments.
README.mdmodified+38 -14
@@ -29,7 +29,11 @@ full — lays out its **subjects** (curriculum topics —
2929 every exam question must be tagged with one of its course's subjects, so
3030 results can later be read per topic), enrolls students, adds
3131 exams inside it, and grades — enrolling, sitting exams, roll call, and marks are
32-all student-only, staff never take part; students read a per-course weighted average and
32+all student-only, staff never take part. A course is run by whoever created it
33+plus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):
34+an assigned teacher manages everything inside the course — exams, sessions,
35+subjects, roster, grading — but can't delete it or change who else teaches it,
36+and a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and
3337 an overall average from their mark report — each exam weighted by its **kind**
3438 (midterms can count double, orals once: weights are set per kind in settings,
3539 not per exam). Exams run **sync** (one
@@ -251,9 +255,9 @@ course enrollments.
251255 | Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** — never for another staff member. Unregistering mirrors the same rule |
252256 | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |
253257 | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |
254-| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, or `manager`+ |
258+| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |
255259 | List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |
256-| Create / edit / delete a course session | teacher | Course-management rights (course creator, or `manager`+) |
260+| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |
257261 | Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |
258262 | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark |
259263 | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |
@@ -265,14 +269,16 @@ course enrollments.
265269 | Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion — moderation never edits, so teacher+ cannot rewrite a solution |
266270 | Read **own** attendance report | student | |
267271 | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |
268-| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all); exam **drafts** show only to the course's managers |
272+| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |
269273 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |
270274 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |
271275 | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |
272276 | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key |
273277 | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights |
274-| Create courses | teacher | The creator manages the course |
275-| Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions won't delete (`409`) |
278+| Create courses | teacher | The creator manages the course, and owns it for good |
279+| Assign / unassign a course's teachers | manager | Staffing is the office's call — a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |
280+| Delete a course | teacher | Only the **creator**, or a `manager`+ — an assigned teacher runs the course but doesn't own it |
281+| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions won't delete (`409`) |
276282 | View a course's roster, an exam's result list / statistics | teacher | Course-management rights |
277283 | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |
278284 | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |
@@ -327,13 +333,29 @@ roster reaches it, new enrolls are refused with `409` (members already on the
327333 roster are unaffected, even if the cap is later lowered below them; `null`
328334 lifts the cap).
329335
336+**Who runs a course.** Its **creator** owns it for good — only they (or a
337+manager+) may delete it. On top of that, a manager can **assign** any
338+`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,
339+idempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.
340+An assigned teacher gets full **course-management rights** — edit the course,
341+enroll and unenroll students, add exams, sessions and subjects, grade, take
342+roll call — but *not* the two owner powers: they cannot delete the course, and
343+they cannot change who else teaches it. Staffing is deliberately the office's
344+call, so a course's own creator cannot hand rights to their peers; only
345+manager+ may touch the list. Every course response carries its `teachers`
346+array alongside `creator`, and a user demoted below `teacher` is swept off
347+every course they were assigned to (the mirror of promotion dropping
348+enrollments).
349+
330350 Course data is walled per course. A course, its exams, its sessions, and its
331351 subjects are
332-**visible** only to its enrolled users, its creator, and manager+ — a student
352+**visible** only to its enrolled users, its creator, its assigned teachers,
353+and manager+ — a student
333354 sees just the classes they were added to, and the `/courses` / `/exams`
334355 catalogs are filtered accordingly. Teacher-level reads *inside* a course
335356 (roster, results, statistics, the question list, answer sheets, the live
336-monitor) additionally need **course-management rights** (creator or manager+):
357+monitor) additionally need **course-management rights** (creator, an assigned
358+teacher, or manager+):
337359 one teacher cannot look into another teacher's course, and the per-user
338360 marks/attendance reports narrow to the courses the caller manages.
339361
@@ -400,16 +422,18 @@ their existing shapes: the student exam-room reads
400422 | POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` — `kind` is `course` (default), `study` (etüt), or `club` (kulüp); `capacity` caps the roster (creator manages it) |
401423 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
402424 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
403-| GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) |
404-| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (creator, or manager+ for any) |
405-| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) |
425+| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |
426+| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |
427+| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+ — **not** an assigned teacher) |
428+| POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) |
429+| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |
406430 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |
407431 | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged |
408432 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |
409433 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) |
410-| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged |
434+| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) · paged |
411435 | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` — add a curriculum subject (course manager) |
412-| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, or manager+) · paged |
436+| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) · paged |
413437 | GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |
414438 | PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |
415439 | DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions reference it |
@@ -420,7 +444,7 @@ their existing shapes: the student exam-room reads
420444 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |
421445 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
422446 | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |
423-| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+; drafts appear to course managers only) · paged |
447+| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |
424448 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged |
425449 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
426450 | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) |
src/database.rsmodified+6 -0
@@ -126,6 +126,8 @@ const MIGRATION: &str = "
126126
127127 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
128128 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
129+ DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT [];
130+ DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>;
129131 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
130132 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
131133 DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
@@ -291,6 +293,10 @@ const BACKFILL: &str = "
291293
292294 UPDATE course SET kind = 'course' WHERE kind = NONE;
293295
296+ -- Courses predate assignable teachers (2026-07-21): every existing course
297+ -- was run by its creator alone, so it starts with nobody else assigned.
298+ UPDATE course SET teachers = [] WHERE teachers = NONE;
299+
294300 -- Exams predate the draft flag (2026-07-19): everything already out there
295301 -- was live for its course, so it stays published.
296302 UPDATE exam SET draft = false WHERE draft = NONE;
src/domain/course.rsmodified+94 -3
@@ -88,10 +88,17 @@ impl CourseKind {
8888 /// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster
8989 /// at enroll time (`None` = unlimited); rows written before the field existed
9090 /// decode as uncapped.
91+///
92+/// `creator` owns the course for good — only they (or a manager+) may delete
93+/// it. `teachers` are the staff a manager assigned to run it: full management
94+/// rights inside the course, no power to delete it or change the assignment
95+/// list. Rows written before the field existed decode with nobody assigned.
9196 #[derive(Debug, Clone, SurrealValue)]
9297 pub struct Course {
9398 id: CourseId,
9499 creator: UserId,
100+ #[surreal(default)]
101+ teachers: Vec<UserId>,
95102 title: CourseTitle,
96103 description: CourseDescription,
97104 kind: CourseKind,
@@ -133,6 +140,17 @@ impl Course {
133140 &self.creator == user
134141 }
135142
143+ /// The staff assigned to run this course, in assignment order.
144+ pub fn get_teachers(&self) -> &[UserId] {
145+ &self.teachers
146+ }
147+
148+ /// Whether `user` was assigned to teach this course. Says nothing about
149+ /// the creator — they own it whether or not they also appear here.
150+ pub fn is_assigned(&self, user: &UserId) -> bool {
151+ self.teachers.contains(user)
152+ }
153+
136154 pub async fn create(
137155 creator: &UserId,
138156 title: CourseTitle,
@@ -145,6 +163,7 @@ impl Course {
145163 let course = Course {
146164 id: CourseId::generate(),
147165 creator: creator.clone(),
166+ teachers: Vec::new(),
148167 title,
149168 description,
150169 kind,
@@ -182,10 +201,11 @@ impl Course {
182201 Ok(result.take::<Vec<Course>>(0)?)
183202 }
184203
185- /// The courses `user` created — a teacher's slice of the catalog.
186- pub async fn list_created(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> {
204+ /// The courses `user` runs — the ones they created plus the ones a manager
205+ /// assigned them to. A teacher's slice of the catalog.
206+ pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> {
187207 let mut result = db
188- .query("SELECT * FROM course WHERE creator = $usr ORDER BY id DESC")
208+ .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC")
189209 .bind(("usr", user.record()))
190210 .await?
191211 .check()?;
@@ -225,6 +245,46 @@ impl Course {
225245 updated.ok_or(AppError::NotFound)
226246 }
227247
248+ /// Assign `teacher` to run this course, or return the course untouched if
249+ /// they already run it — assignment is idempotent, like enrollment.
250+ pub async fn assign_teacher(
251+ mut self,
252+ teacher: &UserId,
253+ db: &Database,
254+ ) -> Result<Course, AppError> {
255+ if self.is_assigned(teacher) {
256+ return Ok(self);
257+ }
258+ self.teachers.push(teacher.clone());
259+ let updated: Option<Course> = db.update(self.id.record()).content(self).await?;
260+ updated.ok_or(AppError::NotFound)
261+ }
262+
263+ /// Drop `teacher` from this course. `None` when they weren't assigned, so
264+ /// the web layer can answer 404 instead of pretending it removed someone.
265+ pub async fn unassign_teacher(
266+ mut self,
267+ teacher: &UserId,
268+ db: &Database,
269+ ) -> Result<Option<Course>, AppError> {
270+ if !self.is_assigned(teacher) {
271+ return Ok(None);
272+ }
273+ self.teachers.retain(|assigned| assigned != teacher);
274+ let updated: Option<Course> = db.update(self.id.record()).content(self).await?;
275+ updated.map(Some).ok_or(AppError::NotFound)
276+ }
277+
278+ /// Strip `user` from every course they were assigned to — the sweep for a
279+ /// user demoted below `teacher`, who may no longer run anything.
280+ pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> {
281+ db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers")
282+ .bind(("usr", user.record()))
283+ .await?
284+ .check()?;
285+ Ok(())
286+ }
287+
228288 /// Delete the course and cascade-remove everything inside it: results,
229289 /// attempts, and question images of its exams, its enrollments, its
230290 /// sessions with their roll call, its subjects, and the exams themselves.
@@ -289,6 +349,7 @@ mod tests {
289349 let course = Course {
290350 id: CourseId::generate(),
291351 creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"),
352+ teachers: Vec::new(),
292353 title: CourseTitle::try_new("chess").unwrap(),
293354 description: CourseDescription::try_new("").unwrap(),
294355 kind: CourseKind::try_new("club").unwrap(),
@@ -302,4 +363,34 @@ mod tests {
302363 let decoded = Course::from_value(Value::Object(object)).unwrap();
303364 assert_eq!(decoded.get_capacity(), None);
304365 }
366+
367+ /// Every course row written before teacher assignment existed has no
368+ /// `teachers` key. The boot backfill fills them in, but a row read before
369+ /// that lands must still decode — as a course nobody was assigned to,
370+ /// never as a decode error that 500s the catalog.
371+ #[tokio::test]
372+ async fn course_decodes_without_teachers_key() {
373+ use surrealdb::types::Value;
374+
375+ let assigned = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
376+ let course = Course {
377+ id: CourseId::generate(),
378+ creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"),
379+ teachers: vec![assigned.clone()],
380+ title: CourseTitle::try_new("chess").unwrap(),
381+ description: CourseDescription::try_new("").unwrap(),
382+ kind: CourseKind::try_new("club").unwrap(),
383+ term: None,
384+ capacity: None,
385+ };
386+ assert!(course.is_assigned(&assigned));
387+
388+ let Value::Object(mut object) = course.into_value() else {
389+ panic!("course must encode as an object");
390+ };
391+ object.remove("teachers");
392+ let decoded = Course::from_value(Value::Object(object)).unwrap();
393+ assert!(decoded.get_teachers().is_empty());
394+ assert!(!decoded.is_assigned(&assigned));
395+ }
305396 }
src/lib.rsmodified+3 -3
@@ -34,7 +34,7 @@ use crate::state::AppState;
3434 info(
3535 title = "Hezarfen Backend API",
3636 version = env!("CARGO_PKG_VERSION"),
37- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, and pomodoro reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
37+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, and pomodoro reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
3838 ),
3939 modifiers(&SecurityAddon),
4040 tags(
@@ -44,7 +44,7 @@ use crate::state::AppState;
4444 (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`)"),
4545 (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`/`trash`. `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"),
4646 (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"),
47- (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"),
47+ (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"),
4848 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
4949 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
5050 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
@@ -53,7 +53,7 @@ use crate::state::AppState;
5353 (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. 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"),
5454 (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"),
5555 (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). Read: any authenticated user; edit: manager+"),
56- (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, manager+); edit follows course management rights"),
56+ (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"),
5757 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),
5858 ),
5959 )]
src/web/attendance.rsmodified+2 -2
@@ -17,7 +17,7 @@ use crate::error::{AppError, ErrorResponse};
1717 use crate::state::AppState;
1818
1919 use super::courses::can_manage_course;
20-use super::{CourseResponse, CurrentUser, ensure_can_observe, person_map};
20+use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};
2121
2222 pub fn routes() -> OpenApiRouter<AppState> {
2323 OpenApiRouter::new()
@@ -119,7 +119,7 @@ async fn build_report(
119119 let courses = Course::list_by_ids(&course_ids, db).await?;
120120 let course_by_key: HashMap<&str, &Course> =
121121 courses.iter().map(|c| (c.get_id().key(), c)).collect();
122- let people = person_map(courses.iter().map(|c| c.get_creator().clone()), db).await?;
122+ let people = person_map(courses.iter().flat_map(course_people), db).await?;
123123
124124 let mut blocks = Vec::with_capacity(course_ids.len());
125125 let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len());
src/web/courses.rsmodified+154 -39
@@ -28,9 +28,9 @@ use crate::state::AppState;
2828 use super::sessions::resolve_session_teacher;
2929 use super::terms::resolve_term;
3030 use super::{
31- CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,
32- SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map,
33- remove_blob, set_or_clear,
31+ CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireManager,
32+ RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range,
33+ course_people, paginate, person_map, remove_blob, set_or_clear,
3434 };
3535
3636 pub fn routes() -> OpenApiRouter<AppState> {
@@ -38,6 +38,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
3838 .routes(routes!(create_course, list_courses))
3939 .routes(routes!(my_courses))
4040 .routes(routes!(get_course, update_course, delete_course))
41+ .routes(routes!(assign_teacher))
42+ .routes(routes!(unassign_teacher))
4143 .routes(routes!(enroll, list_roster))
4244 .routes(routes!(unenroll))
4345 .routes(routes!(create_exam_in_course, list_course_exams))
@@ -89,6 +91,14 @@ struct EnrollUser {
8991 user_id: String,
9092 }
9193
94+#[derive(Deserialize, ToSchema)]
95+struct AssignTeacher {
96+ /// The staff member to put in charge of the course. Must hold the
97+ /// `teacher` role or higher.
98+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
99+ user_id: String,
100+}
101+
92102 #[derive(Deserialize, ToSchema)]
93103 struct CreateExamInCourse {
94104 #[schema(example = "Midterm")]
@@ -150,10 +160,23 @@ impl EnrollmentResponse {
150160 }
151161 }
152162
153-/// Who may write inside a specific course (edit/delete it, enroll, add exams,
154-/// grade): its creator, or anyone `manager` and above. Callers have already
155-/// cleared the `teacher` bar via `RequireTeacher`.
163+/// Who may write inside a specific course (edit it, enroll, add exams,
164+/// sessions, subjects, grade): its creator, a teacher a manager assigned to
165+/// it, or anyone `manager` and above. Callers have already cleared the
166+/// `teacher` bar via `RequireTeacher`.
167+///
168+/// Deleting the course and changing its teacher list sit *above* this bar —
169+/// see [`owns_course`].
156170 pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool {
171+ course.is_creator(user.get_id())
172+ || course.is_assigned(user.get_id())
173+ || user.get_role().at_least(Role::Manager)
174+}
175+
176+/// Who may destroy a course: its creator, or anyone `manager` and above. An
177+/// assigned teacher runs the course but does not own it — they cannot delete
178+/// it out from under the person who made it.
179+fn owns_course(course: &Course, user: &User) -> bool {
157180 course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager)
158181 }
159182
@@ -181,7 +204,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
181204 if user.get_role().at_least(Role::Manager) {
182205 return Course::list_all(db).await;
183206 }
184- let mut courses = Course::list_created(user.get_id(), db).await?;
207+ let mut courses = Course::list_for_teacher(user.get_id(), db).await?;
185208 for course in Course::list_enrolled(user.get_id(), db).await? {
186209 if !courses
187210 .iter()
@@ -283,7 +306,7 @@ async fn list_courses(
283306 let total = courses.len() as i64;
284307 let window = paginate(&courses, limit, offset);
285308 // Join creators onto the page alone — the lookup shrinks with the window.
286- let people = person_map(window.iter().map(|c| c.get_creator().clone()), &st.db).await?;
309+ let people = person_map(window.iter().flat_map(course_people), &st.db).await?;
287310 let items = window
288311 .iter()
289312 .map(|course| CourseResponse::new(course, &people))
@@ -315,7 +338,7 @@ async fn my_courses(
315338 let courses = Course::list_enrolled(user.get_id(), &st.db).await?;
316339 let total = courses.len() as i64;
317340 let window = paginate(&courses, limit, offset);
318- let people = person_map(window.iter().map(|c| c.get_creator().clone()), &st.db).await?;
341+ let people = person_map(window.iter().flat_map(course_people), &st.db).await?;
319342 let items = window
320343 .iter()
321344 .map(|course| CourseResponse::new(course, &people))
@@ -334,7 +357,7 @@ async fn my_courses(
334357 responses(
335358 (status = 200, description = "The course", body = CourseResponse),
336359 (status = 401, description = "Not authenticated", body = ErrorResponse),
337- (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
360+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
338361 (status = 404, description = "Not found", body = ErrorResponse),
339362 ),
340363 )]
@@ -348,15 +371,16 @@ async fn get_course(
348371 .ok_or(AppError::NotFound)?;
349372 if !can_view_course(&course, &user, &st.db).await? {
350373 return Err(AppError::Forbidden(
351- "only enrolled users, the course creator, or a manager/admin can view this course",
374+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
352375 ));
353376 }
354- let people = person_map([course.get_creator().clone()], &st.db).await?;
377+ let people = person_map(course_people(&course), &st.db).await?;
355378 Ok(Json(CourseResponse::new(&course, &people)))
356379 }
357380
358-/// Update a course. Requires teacher+; the creator may edit their own course
359-/// and managers/admins may edit anyone's. Omitted fields keep their value.
381+/// Update a course. Requires teacher+ and course management rights — its
382+/// creator, a teacher assigned to it, or a manager/admin. Omitted fields keep
383+/// their value.
360384 #[utoipa::path(
361385 patch,
362386 path = "/{id}",
@@ -368,7 +392,7 @@ async fn get_course(
368392 (status = 200, description = "Updated course", body = CourseResponse),
369393 (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse),
370394 (status = 401, description = "Not authenticated", body = ErrorResponse),
371- (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
395+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
372396 (status = 404, description = "Not found", body = ErrorResponse),
373397 ),
374398 )]
@@ -383,7 +407,7 @@ async fn update_course(
383407 .ok_or(AppError::NotFound)?;
384408 if !can_manage_course(&course, &user) {
385409 return Err(AppError::Forbidden(
386- "only the course creator or a manager/admin can edit this course",
410+ "only the course creator, an assigned teacher, or a manager/admin can edit this course",
387411 ));
388412 }
389413
@@ -416,12 +440,12 @@ async fn update_course(
416440 let updated = course
417441 .update(title, description, kind, term, capacity, &st.db)
418442 .await?;
419- let people = person_map([updated.get_creator().clone()], &st.db).await?;
443+ let people = person_map(course_people(&updated), &st.db).await?;
420444 Ok(Json(CourseResponse::new(&updated, &people)))
421445 }
422446
423-/// Delete a course. Requires teacher+; the creator may delete their own course
424-/// and managers/admins may delete anyone's. Cascades the course's exams (with
447+/// Delete a course. Requires teacher+; only its creator or a manager/admin may
448+/// delete it — an assigned teacher runs the course but does not own it. Cascades the course's exams (with
425449 /// their results, questions, answers, and question images), its sessions and
426450 /// roll call, its subjects, and all enrollments.
427451 #[utoipa::path(
@@ -433,7 +457,7 @@ async fn update_course(
433457 responses(
434458 (status = 204, description = "Deleted"),
435459 (status = 401, description = "Not authenticated", body = ErrorResponse),
436- (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
460+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
437461 (status = 404, description = "Not found", body = ErrorResponse),
438462 ),
439463 )]
@@ -445,7 +469,7 @@ async fn delete_course(
445469 let course = Course::read(&CourseId::from_key(&id), &st.db)
446470 .await?
447471 .ok_or(AppError::NotFound)?;
448- if !can_manage_course(&course, &user) {
472+ if !owns_course(&course, &user) {
449473 return Err(AppError::Forbidden(
450474 "only the course creator or a manager/admin can delete this course",
451475 ));
@@ -460,6 +484,97 @@ async fn delete_course(
460484 Ok(StatusCode::NO_CONTENT)
461485 }
462486
487+// ---- assigned teachers ----------------------------------------------------
488+
489+/// Assign a teacher to a course (idempotent). Manager+ only — staffing is the
490+/// office's call, so a course's own creator cannot hand management rights to
491+/// their peers. The assignee must already hold the `teacher` role or higher;
492+/// assigning gives them full management of the course (exams, sessions,
493+/// subjects, roster, grading) but not the power to delete it or change this
494+/// list. The course's assigned teachers are returned on every course response.
495+#[utoipa::path(
496+ post,
497+ path = "/{id}/teachers",
498+ tag = "courses",
499+ security(("session_cookie" = [])),
500+ params(("id" = String, Path, description = "Course id")),
501+ request_body = AssignTeacher,
502+ responses(
503+ (status = 200, description = "Assigned (or already assigned)", body = CourseResponse),
504+ (status = 400, description = "Unknown user, or user is not a teacher or higher", body = ErrorResponse),
505+ (status = 401, description = "Not authenticated", body = ErrorResponse),
506+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
507+ (status = 404, description = "Course not found", body = ErrorResponse),
508+ ),
509+)]
510+async fn assign_teacher(
511+ State(st): State<AppState>,
512+ RequireManager(_manager): RequireManager,
513+ Path(id): Path<String>,
514+ Json(req): Json<AssignTeacher>,
515+) -> Result<Json<CourseResponse>, AppError> {
516+ let course = Course::read(&CourseId::from_key(&id), &st.db)
517+ .await?
518+ .ok_or(AppError::NotFound)?;
519+
520+ let target = UserId::from_key(&req.user_id);
521+ let Some(target_user) = User::read(&target, &st.db).await? else {
522+ return Err(AppError::Validation(ValidationError::Invalid {
523+ field: "user_id",
524+ reason: "target user does not exist",
525+ }));
526+ };
527+ // Assignment hands out course-management rights, which every gate behind
528+ // it re-checks against the `teacher` bar — assigning anyone below it would
529+ // write a row that can never be used.
530+ if !target_user.get_role().at_least(Role::Teacher) {
531+ return Err(AppError::Validation(ValidationError::Invalid {
532+ field: "user_id",
533+ reason: "assigned teacher must hold the teacher role or higher",
534+ }));
535+ }
536+
537+ let updated = course.assign_teacher(&target, &st.db).await?;
538+ let people = person_map(course_people(&updated), &st.db).await?;
539+ Ok(Json(CourseResponse::new(&updated, &people)))
540+}
541+
542+/// Unassign a teacher from a course. Manager+ only. The course itself, its
543+/// exams, sessions, and roster are untouched — the teacher just loses their
544+/// management rights over it. A user who was never assigned is a 404.
545+#[utoipa::path(
546+ delete,
547+ path = "/{id}/teachers/{user}",
548+ tag = "courses",
549+ security(("session_cookie" = [])),
550+ params(
551+ ("id" = String, Path, description = "Course id"),
552+ ("user" = String, Path, description = "User id"),
553+ ),
554+ responses(
555+ (status = 204, description = "Unassigned"),
556+ (status = 401, description = "Not authenticated", body = ErrorResponse),
557+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
558+ (status = 404, description = "Course not found, or that user was not assigned to it", body = ErrorResponse),
559+ ),
560+)]
561+async fn unassign_teacher(
562+ State(st): State<AppState>,
563+ RequireManager(_manager): RequireManager,
564+ Path((id, target)): Path<(String, String)>,
565+) -> Result<StatusCode, AppError> {
566+ let course = Course::read(&CourseId::from_key(&id), &st.db)
567+ .await?
568+ .ok_or(AppError::NotFound)?;
569+ let removed = course
570+ .unassign_teacher(&UserId::from_key(&target), &st.db)
571+ .await?;
572+ if removed.is_none() {
573+ return Err(AppError::NotFound);
574+ }
575+ Ok(StatusCode::NO_CONTENT)
576+}
577+
463578 // ---- enrollments ----------------------------------------------------------
464579
465580 /// Enroll a user into a course (idempotent upsert). Requires teacher+ and
@@ -478,7 +593,7 @@ async fn delete_course(
478593 (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse),
479594 (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse),
480595 (status = 401, description = "Not authenticated", body = ErrorResponse),
481- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
596+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
482597 (status = 404, description = "Course not found", body = ErrorResponse),
483598 (status = 409, description = "The course is full", body = ErrorResponse),
484599 ),
@@ -494,7 +609,7 @@ async fn enroll(
494609 .ok_or(AppError::NotFound)?;
495610 if !can_manage_course(&course, &user) {
496611 return Err(AppError::Forbidden(
497- "only the course creator or a manager/admin can enroll users",
612+ "only the course creator, an assigned teacher, or a manager/admin can enroll users",
498613 ));
499614 }
500615
@@ -535,7 +650,7 @@ async fn enroll(
535650 (status = 200, description = "A page of enrollments (the whole roster when unpaged)", body = Page<EnrollmentResponse>),
536651 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
537652 (status = 401, description = "Not authenticated", body = ErrorResponse),
538- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
653+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
539654 (status = 404, description = "Course not found", body = ErrorResponse),
540655 ),
541656 )]
@@ -552,7 +667,7 @@ async fn list_roster(
552667 .ok_or(AppError::NotFound)?;
553668 if !can_manage_course(&course, &user) {
554669 return Err(AppError::Forbidden(
555- "only the course creator or a manager/admin can list the roster",
670+ "only the course creator, an assigned teacher, or a manager/admin can list the roster",
556671 ));
557672 }
558673 let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?;
@@ -587,7 +702,7 @@ async fn list_roster(
587702 responses(
588703 (status = 204, description = "Unenrolled"),
589704 (status = 401, description = "Not authenticated", body = ErrorResponse),
590- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
705+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
591706 (status = 404, description = "Not found", body = ErrorResponse),
592707 ),
593708 )]
@@ -601,7 +716,7 @@ async fn unenroll(
601716 .ok_or(AppError::NotFound)?;
602717 if !can_manage_course(&course, &user) {
603718 return Err(AppError::Forbidden(
604- "only the course creator or a manager/admin can unenroll users",
719+ "only the course creator, an assigned teacher, or a manager/admin can unenroll users",
605720 ));
606721 }
607722 let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?;
@@ -634,7 +749,7 @@ async fn unenroll(
634749 (status = 201, description = "Exam created", body = ExamResponse),
635750 (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or times in the past)", body = ErrorResponse),
636751 (status = 401, description = "Not authenticated", body = ErrorResponse),
637- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
752+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
638753 (status = 404, description = "Course not found", body = ErrorResponse),
639754 ),
640755 )]
@@ -649,7 +764,7 @@ async fn create_exam_in_course(
649764 .ok_or(AppError::NotFound)?;
650765 if !can_manage_course(&course, &user) {
651766 return Err(AppError::Forbidden(
652- "only the course creator or a manager/admin can add exams to this course",
767+ "only the course creator, an assigned teacher, or a manager/admin can add exams to this course",
653768 ));
654769 }
655770
@@ -701,7 +816,7 @@ async fn create_exam_in_course(
701816 (status = 200, description = "A page of the course's exams (all of them when unpaged)", body = Page<ExamResponse>),
702817 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
703818 (status = 401, description = "Not authenticated", body = ErrorResponse),
704- (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
819+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
705820 (status = 404, description = "Course not found", body = ErrorResponse),
706821 ),
707822 )]
@@ -718,7 +833,7 @@ async fn list_course_exams(
718833 .ok_or(AppError::NotFound)?;
719834 if !can_view_course(&course, &user, &st.db).await? {
720835 return Err(AppError::Forbidden(
721- "only enrolled users, the course creator, or a manager/admin can view this course",
836+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
722837 ));
723838 }
724839 let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?;
@@ -759,7 +874,7 @@ struct CreateSubject {
759874 (status = 201, description = "Subject created", body = SubjectResponse),
760875 (status = 400, description = "Invalid name or description", body = ErrorResponse),
761876 (status = 401, description = "Not authenticated", body = ErrorResponse),
762- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
877+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
763878 (status = 404, description = "Course not found", body = ErrorResponse),
764879 ),
765880 )]
@@ -774,7 +889,7 @@ async fn create_subject_in_course(
774889 .ok_or(AppError::NotFound)?;
775890 if !can_manage_course(&course, &user) {
776891 return Err(AppError::Forbidden(
777- "only the course creator or a manager/admin can add subjects to this course",
892+ "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course",
778893 ));
779894 }
780895
@@ -798,7 +913,7 @@ async fn create_subject_in_course(
798913 (status = 200, description = "A page of the course's subjects (all of them when unpaged)", body = Page<SubjectResponse>),
799914 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
800915 (status = 401, description = "Not authenticated", body = ErrorResponse),
801- (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
916+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
802917 (status = 404, description = "Course not found", body = ErrorResponse),
803918 ),
804919 )]
@@ -815,7 +930,7 @@ async fn list_course_subjects(
815930 .ok_or(AppError::NotFound)?;
816931 if !can_view_course(&course, &user, &st.db).await? {
817932 return Err(AppError::Forbidden(
818- "only enrolled users, the course creator, or a manager/admin can view this course",
933+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
819934 ));
820935 }
821936 let subjects = Subject::list_for_course(course.get_id(), &st.db).await?;
@@ -858,7 +973,7 @@ struct CreateSessionInCourse {
858973 (status = 201, description = "Session created", body = SessionResponse),
859974 (status = 400, description = "Invalid fields, time range, times in the past, or teacher", body = ErrorResponse),
860975 (status = 401, description = "Not authenticated", body = ErrorResponse),
861- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
976+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
862977 (status = 404, description = "Course not found", body = ErrorResponse),
863978 ),
864979 )]
@@ -873,7 +988,7 @@ async fn create_session_in_course(
873988 .ok_or(AppError::NotFound)?;
874989 if !can_manage_course(&course, &user) {
875990 return Err(AppError::Forbidden(
876- "only the course creator or a manager/admin can add sessions to this course",
991+ "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course",
877992 ));
878993 }
879994
@@ -915,7 +1030,7 @@ async fn create_session_in_course(
9151030 (status = 200, description = "A page of the course's sessions (all of them when unpaged)", body = Page<SessionResponse>),
9161031 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
9171032 (status = 401, description = "Not authenticated", body = ErrorResponse),
918- (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
1033+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
9191034 (status = 404, description = "Course not found", body = ErrorResponse),
9201035 ),
9211036 )]
@@ -932,7 +1047,7 @@ async fn list_course_sessions(
9321047 .ok_or(AppError::NotFound)?;
9331048 if !can_view_course(&course, &user, &st.db).await? {
9341049 return Err(AppError::Forbidden(
935- "only enrolled users, the course creator, or a manager/admin can view this course",
1050+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
9361051 ));
9371052 }
9381053 let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?;
src/web/dto.rsmodified+18 -1
@@ -160,8 +160,13 @@ impl UserResponse {
160160 pub struct CourseResponse {
161161 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
162162 pub id: String,
163- /// Who created (and owns) the course.
163+ /// Who created (and owns) the course. Only they and managers/admins may
164+ /// delete it or change who teaches it.
164165 pub creator: PersonRef,
166+ /// The staff a manager assigned to run this course. They manage everything
167+ /// inside it — exams, sessions, subjects, the roster, grading — but cannot
168+ /// delete the course or change this list. Empty when nobody was assigned.
169+ pub teachers: Vec<PersonRef>,
165170 #[schema(example = "Algebra")]
166171 pub title: String,
167172 pub description: String,
@@ -178,11 +183,23 @@ pub struct CourseResponse {
178183 pub capacity: Option<i64>,
179184 }
180185
186+/// Every person a [`CourseResponse`] names: the creator plus the teachers
187+/// assigned to run it. Feed this into `person_map` so the response can resolve
188+/// all of them — a name the map is missing renders as an unknown person.
189+pub fn course_people(course: &Course) -> impl Iterator<Item = UserId> + '_ {
190+ std::iter::once(course.get_creator().clone()).chain(course.get_teachers().iter().cloned())
191+}
192+
181193 impl CourseResponse {
182194 pub fn new(course: &Course, people: &HashMap<String, PersonRef>) -> Self {
183195 Self {
184196 id: course.get_id().key().to_string(),
185197 creator: PersonRef::resolve(people, course.get_creator()),
198+ teachers: course
199+ .get_teachers()
200+ .iter()
201+ .map(|teacher| PersonRef::resolve(people, teacher))
202+ .collect(),
186203 title: course.get_title().as_str().to_string(),
187204 description: course.get_description().as_str().to_string(),
188205 kind: course.get_kind().as_str().to_string(),
src/web/exams.rsmodified+32 -32
@@ -280,7 +280,7 @@ async fn get_exam(
280280 let course = course_of(&exam, &st.db).await?;
281281 if !can_view_course(&course, &user, &st.db).await? {
282282 return Err(AppError::Forbidden(
283- "only enrolled users, the course creator, or a manager/admin can view this exam",
283+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this exam",
284284 ));
285285 }
286286 // A draft doesn't exist for anyone but its course's managers — 404, not
@@ -312,7 +312,7 @@ async fn get_exam(
312312 (status = 200, description = "Updated exam", body = ExamResponse),
313313 (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or newly set times in the past)", body = ErrorResponse),
314314 (status = 401, description = "Not authenticated", body = ErrorResponse),
315- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
315+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
316316 (status = 404, description = "Not found", body = ErrorResponse),
317317 (status = 409, description = "Mode change after attempts started, or re-drafting an exam that has attempts or results", body = ErrorResponse),
318318 ),
@@ -334,7 +334,7 @@ async fn update_exam(
334334 let course = course_of(&exam, &st.db).await?;
335335 if !can_manage_course(&course, &user) {
336336 return Err(AppError::Forbidden(
337- "only the course creator or a manager/admin can edit this exam",
337+ "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
338338 ));
339339 }
340340
@@ -449,7 +449,7 @@ async fn update_exam(
449449 responses(
450450 (status = 204, description = "Deleted"),
451451 (status = 401, description = "Not authenticated", body = ErrorResponse),
452- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
452+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
453453 (status = 404, description = "Not found", body = ErrorResponse),
454454 ),
455455 )]
@@ -464,7 +464,7 @@ async fn delete_exam(
464464 let course = course_of(&exam, &st.db).await?;
465465 if !can_manage_course(&course, &user) {
466466 return Err(AppError::Forbidden(
467- "only the course creator or a manager/admin can delete this exam",
467+ "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
468468 ));
469469 }
470470 // Rows go first (the delete cascades them), blobs after — a crash in
@@ -495,7 +495,7 @@ async fn delete_exam(
495495 (status = 200, description = "Result recorded", body = ExamResultResponse),
496496 (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),
497497 (status = 401, description = "Not authenticated", body = ErrorResponse),
498- (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
498+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
499499 (status = 404, description = "Exam not found", body = ErrorResponse),
500500 (status = 409, description = "The exam is a draft", body = ErrorResponse),
501501 ),
@@ -519,7 +519,7 @@ async fn grade(
519519 let course = course_of(&exam, &st.db).await?;
520520 if !can_manage_course(&course, &teacher) {
521521 return Err(AppError::Forbidden(
522- "only the course creator or a manager/admin can grade this exam",
522+ "only the course creator, an assigned teacher, or a manager/admin can grade this exam",
523523 ));
524524 }
525525 if exam.is_draft() {
@@ -584,7 +584,7 @@ async fn grade(
584584 (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
585585 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
586586 (status = 401, description = "Not authenticated", body = ErrorResponse),
587- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
587+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
588588 (status = 404, description = "Exam not found", body = ErrorResponse),
589589 ),
590590 )]
@@ -602,7 +602,7 @@ async fn list_results(
602602 let course = course_of(&exam, &st.db).await?;
603603 if !can_manage_course(&course, &user) {
604604 return Err(AppError::Forbidden(
605- "only the course creator or a manager/admin can list results",
605+ "only the course creator, an assigned teacher, or a manager/admin can list results",
606606 ));
607607 }
608608 let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
@@ -666,7 +666,7 @@ async fn my_result(
666666 responses(
667667 (status = 204, description = "Removed"),
668668 (status = 401, description = "Not authenticated", body = ErrorResponse),
669- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
669+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
670670 (status = 404, description = "Not found", body = ErrorResponse),
671671 ),
672672 )]
@@ -681,7 +681,7 @@ async fn remove_result(
681681 let course = course_of(&exam, &st.db).await?;
682682 if !can_manage_course(&course, &user) {
683683 return Err(AppError::Forbidden(
684- "only the course creator or a manager/admin can remove results",
684+ "only the course creator, an assigned teacher, or a manager/admin can remove results",
685685 ));
686686 }
687687 let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?;
@@ -702,7 +702,7 @@ async fn remove_result(
702702 responses(
703703 (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),
704704 (status = 401, description = "Not authenticated", body = ErrorResponse),
705- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
705+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
706706 (status = 404, description = "Exam not found", body = ErrorResponse),
707707 ),
708708 )]
@@ -718,7 +718,7 @@ async fn exam_statistics(
718718 let course = course_of(&exam, &st.db).await?;
719719 if !can_manage_course(&course, &user) {
720720 return Err(AppError::Forbidden(
721- "only the course creator or a manager/admin can view statistics",
721+ "only the course creator, an assigned teacher, or a manager/admin can view statistics",
722722 ));
723723 }
724724 let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
@@ -1226,7 +1226,7 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, A
12261226 responses(
12271227 (status = 200, description = "Live snapshot", body = ExamLiveResponse),
12281228 (status = 401, description = "Not authenticated", body = ErrorResponse),
1229- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1229+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
12301230 (status = 404, description = "Exam not found", body = ErrorResponse),
12311231 ),
12321232 )]
@@ -1241,7 +1241,7 @@ async fn exam_live(
12411241 let course = course_of(&exam, &st.db).await?;
12421242 if !can_manage_course(&course, &user) {
12431243 return Err(AppError::Forbidden(
1244- "only the course creator or a manager/admin can monitor this exam",
1244+ "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",
12451245 ));
12461246 }
12471247 Ok(Json(live_snapshot(&exam, &st.db).await?))
@@ -1263,7 +1263,7 @@ async fn exam_live(
12631263 responses(
12641264 (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"),
12651265 (status = 401, description = "Not authenticated", body = ErrorResponse),
1266- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1266+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
12671267 (status = 404, description = "Exam not found", body = ErrorResponse),
12681268 ),
12691269 )]
@@ -1280,7 +1280,7 @@ async fn exam_live_stream(
12801280 let course = course_of(&exam, &st.db).await?;
12811281 if !can_manage_course(&course, &user) {
12821282 return Err(AppError::Forbidden(
1283- "only the course creator or a manager/admin can monitor this exam",
1283+ "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",
12841284 ));
12851285 }
12861286
@@ -1507,7 +1507,7 @@ async fn question_of_exam(
15071507 (status = 201, description = "Question created", body = QuestionResponse),
15081508 (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
15091509 (status = 401, description = "Not authenticated", body = ErrorResponse),
1510- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1510+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
15111511 (status = 404, description = "Exam not found", body = ErrorResponse),
15121512 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
15131513 ),
@@ -1524,7 +1524,7 @@ async fn create_question(
15241524 let course = course_of(&exam, &st.db).await?;
15251525 if !can_manage_course(&course, &user) {
15261526 return Err(AppError::Forbidden(
1527- "only the course creator or a manager/admin can author questions",
1527+ "only the course creator, an assigned teacher, or a manager/admin can author questions",
15281528 ));
15291529 }
15301530 // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
@@ -1560,7 +1560,7 @@ async fn create_question(
15601560 (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page<QuestionResponse>),
15611561 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
15621562 (status = 401, description = "Not authenticated", body = ErrorResponse),
1563- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1563+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
15641564 (status = 404, description = "Exam not found", body = ErrorResponse),
15651565 ),
15661566 )]
@@ -1577,7 +1577,7 @@ async fn list_questions(
15771577 let course = course_of(&exam, &st.db).await?;
15781578 if !can_manage_course(&course, &user) {
15791579 return Err(AppError::Forbidden(
1580- "only the course creator or a manager/admin can read the question list",
1580+ "only the course creator, an assigned teacher, or a manager/admin can read the question list",
15811581 ));
15821582 }
15831583 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
@@ -1616,7 +1616,7 @@ async fn list_questions(
16161616 (status = 200, description = "Updated question", body = QuestionResponse),
16171617 (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
16181618 (status = 401, description = "Not authenticated", body = ErrorResponse),
1619- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1619+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
16201620 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
16211621 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
16221622 ),
@@ -1633,7 +1633,7 @@ async fn update_question(
16331633 let course = course_of(&exam, &st.db).await?;
16341634 if !can_manage_course(&course, &user) {
16351635 return Err(AppError::Forbidden(
1636- "only the course creator or a manager/admin can edit questions",
1636+ "only the course creator, an assigned teacher, or a manager/admin can edit questions",
16371637 ));
16381638 }
16391639 // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
@@ -1700,7 +1700,7 @@ async fn update_question(
17001700 responses(
17011701 (status = 204, description = "Deleted"),
17021702 (status = 401, description = "Not authenticated", body = ErrorResponse),
1703- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1703+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
17041704 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
17051705 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
17061706 ),
@@ -1716,7 +1716,7 @@ async fn delete_question(
17161716 let course = course_of(&exam, &st.db).await?;
17171717 if !can_manage_course(&course, &user) {
17181718 return Err(AppError::Forbidden(
1719- "only the course creator or a manager/admin can delete questions",
1719+ "only the course creator, an assigned teacher, or a manager/admin can delete questions",
17201720 ));
17211721 }
17221722 // Writer lease of [`EXAM_LOCK`]: freeze gate + delete are one unit — a
@@ -1752,7 +1752,7 @@ async fn image_managed_exam(st: &AppState, user: &User, id: &str) -> Result<Exam
17521752 let course = course_of(&exam, &st.db).await?;
17531753 if !can_manage_course(&course, user) {
17541754 return Err(AppError::Forbidden(
1755- "only the course creator or a manager/admin can manage question images",
1755+ "only the course creator, an assigned teacher, or a manager/admin can manage question images",
17561756 ));
17571757 }
17581758 Ok(exam)
@@ -1842,7 +1842,7 @@ async fn serve_image(st: &AppState, image: &QuestionImage) -> Result<Response, A
18421842 (status = 201, description = "Image stored", body = ImageMetaResponse),
18431843 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
18441844 (status = 401, description = "Not authenticated", body = ErrorResponse),
1845- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1845+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
18461846 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
18471847 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
18481848 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
@@ -1918,7 +1918,7 @@ async fn get_question_image(
19181918 responses(
19191919 (status = 204, description = "Deleted"),
19201920 (status = 401, description = "Not authenticated", body = ErrorResponse),
1921- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1921+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
19221922 (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
19231923 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
19241924 ),
@@ -1960,7 +1960,7 @@ async fn delete_question_image(
19601960 (status = 201, description = "Image stored", body = ImageMetaResponse),
19611961 (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an index past the choices", body = ErrorResponse),
19621962 (status = 401, description = "Not authenticated", body = ErrorResponse),
1963- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1963+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
19641964 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
19651965 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
19661966 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
@@ -2052,7 +2052,7 @@ async fn get_choice_image(
20522052 responses(
20532053 (status = 204, description = "Deleted"),
20542054 (status = 401, description = "Not authenticated", body = ErrorResponse),
2055- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
2055+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
20562056 (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
20572057 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
20582058 ),
@@ -2398,7 +2398,7 @@ async fn save_answer(
23982398 responses(
23992399 (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse),
24002400 (status = 401, description = "Not authenticated", body = ErrorResponse),
2401- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
2401+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
24022402 (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse),
24032403 ),
24042404 )]
@@ -2413,7 +2413,7 @@ async fn attempt_answers(
24132413 let course = course_of(&exam, &st.db).await?;
24142414 if !can_manage_course(&course, &user) {
24152415 return Err(AppError::Forbidden(
2416- "only the course creator or a manager/admin can read answer sheets",
2416+ "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",
24172417 ));
24182418 }
24192419 let target = UserId::from_key(&target);
src/web/marks.rsmodified+2 -2
@@ -18,7 +18,7 @@ use crate::error::{AppError, ErrorResponse};
1818 use crate::state::AppState;
1919
2020 use super::courses::can_manage_course;
21-use super::{CourseResponse, CurrentUser, ensure_can_observe, person_map};
21+use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};
2222
2323 pub fn routes() -> OpenApiRouter<AppState> {
2424 OpenApiRouter::new()
@@ -102,7 +102,7 @@ async fn build_report(
102102
103103 // One settings read weighs and labels the whole report.
104104 let school = Settings::load(db).await?;
105- let people = person_map(courses.iter().map(|c| c.get_creator().clone()), db).await?;
105+ let people = person_map(courses.iter().flat_map(course_people), db).await?;
106106
107107 let mut blocks = Vec::with_capacity(courses.len());
108108 for course in &courses {
src/web/mod.rsmodified+8 -6
@@ -27,7 +27,7 @@ mod page;
2727
2828 pub use dto::{
2929 CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse,
30- person_map,
30+ course_people, person_map,
3131 };
3232 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
3333 pub use page::{Page, PageParams, paginate};
@@ -168,11 +168,13 @@ pub(crate) async fn serve_inline_blob(
168168 file: &str,
169169 content_type: &FileContentType,
170170 ) -> Result<Response, AppError> {
171- let bytes = tokio::fs::read(blob_path(files_path, file)).await.map_err(|err| {
172- // The row exists but its blob doesn't — server-side damage (a lost
173- // volume path), not a client 404.
174- AppError::Internal(format!("missing blob for image {file}: {err}"))
175- })?;
171+ let bytes = tokio::fs::read(blob_path(files_path, file))
172+ .await
173+ .map_err(|err| {
174+ // The row exists but its blob doesn't — server-side damage (a lost
175+ // volume path), not a client 404.
176+ AppError::Internal(format!("missing blob for image {file}: {err}"))
177+ })?;
176178 let content_type = HeaderValue::from_str(content_type.as_str())
177179 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
178180 Ok((
src/web/sessions.rsmodified+6 -6
@@ -134,7 +134,7 @@ fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool
134134 // ---- sessions -------------------------------------------------------------
135135
136136 /// Fetch a single session by id. Visible to its course's enrolled users, the
137-/// session's teacher, the course creator, and managers/admins.
137+/// session's teacher, the course's own teachers, and managers/admins.
138138 #[utoipa::path(
139139 get,
140140 path = "/{id}",
@@ -156,7 +156,7 @@ async fn get_session(
156156 let (session, course) = session_with_course(&id, &st.db).await?;
157157 if !session.is_teacher(user.get_id()) && !can_view_course(&course, &user, &st.db).await? {
158158 return Err(AppError::Forbidden(
159- "only enrolled users, the session teacher, the course creator, or a manager/admin can view this session",
159+ "only enrolled users, the session teacher, the course's teachers, or a manager/admin can view this session",
160160 ));
161161 }
162162 let people = person_map([session.get_teacher().clone()], &st.db).await?;
@@ -176,7 +176,7 @@ async fn get_session(
176176 (status = 200, description = "Updated session", body = SessionResponse),
177177 (status = 400, description = "Invalid fields, time range, newly set times in the past, or teacher", body = ErrorResponse),
178178 (status = 401, description = "Not authenticated", body = ErrorResponse),
179- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
179+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
180180 (status = 404, description = "Not found", body = ErrorResponse),
181181 ),
182182 )]
@@ -189,7 +189,7 @@ async fn update_session(
189189 let (session, course) = session_with_course(&id, &st.db).await?;
190190 if !can_manage_course(&course, &user) {
191191 return Err(AppError::Forbidden(
192- "only the course creator or a manager/admin can edit this session",
192+ "only the course creator, an assigned teacher, or a manager/admin can edit this session",
193193 ));
194194 }
195195
@@ -244,7 +244,7 @@ async fn update_session(
244244 responses(
245245 (status = 204, description = "Deleted"),
246246 (status = 401, description = "Not authenticated", body = ErrorResponse),
247- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
247+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
248248 (status = 404, description = "Not found", body = ErrorResponse),
249249 ),
250250 )]
@@ -256,7 +256,7 @@ async fn delete_session(
256256 let (session, course) = session_with_course(&id, &st.db).await?;
257257 if !can_manage_course(&course, &user) {
258258 return Err(AppError::Forbidden(
259- "only the course creator or a manager/admin can delete this session",
259+ "only the course creator, an assigned teacher, or a manager/admin can delete this session",
260260 ));
261261 }
262262 session.delete(&st.db).await?;
src/web/subjects.rsmodified+8 -7
@@ -65,7 +65,8 @@ async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course
6565 }
6666
6767 /// Fetch a single subject by id. Visible to whoever can view its course: the
68-/// course's enrolled users, its creator, and managers/admins.
68+/// course's enrolled users, its creator, its assigned teachers, and
69+/// managers/admins.
6970 #[utoipa::path(
7071 get,
7172 path = "/{id}",
@@ -75,7 +76,7 @@ async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course
7576 responses(
7677 (status = 200, description = "The subject", body = SubjectResponse),
7778 (status = 401, description = "Not authenticated", body = ErrorResponse),
78- (status = 403, description = "Not enrolled, not the course creator, and not a manager/admin", body = ErrorResponse),
79+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
7980 (status = 404, description = "Not found", body = ErrorResponse),
8081 ),
8182 )]
@@ -87,7 +88,7 @@ async fn get_subject(
8788 let (subject, course) = subject_with_course(&id, &st.db).await?;
8889 if !can_view_course(&course, &user, &st.db).await? {
8990 return Err(AppError::Forbidden(
90- "only enrolled users, the course creator, or a manager/admin can view this subject",
91+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this subject",
9192 ));
9293 }
9394 Ok(Json(SubjectResponse::new(&subject)))
@@ -107,7 +108,7 @@ async fn get_subject(
107108 (status = 200, description = "Updated subject", body = SubjectResponse),
108109 (status = 400, description = "Invalid name or description", body = ErrorResponse),
109110 (status = 401, description = "Not authenticated", body = ErrorResponse),
110- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
111+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
111112 (status = 404, description = "Not found", body = ErrorResponse),
112113 ),
113114 )]
@@ -120,7 +121,7 @@ async fn update_subject(
120121 let (subject, course) = subject_with_course(&id, &st.db).await?;
121122 if !can_manage_course(&course, &user) {
122123 return Err(AppError::Forbidden(
123- "only the course creator or a manager/admin can edit this subject",
124+ "only the course creator, an assigned teacher, or a manager/admin can edit this subject",
124125 ));
125126 }
126127
@@ -149,7 +150,7 @@ async fn update_subject(
149150 responses(
150151 (status = 204, description = "Deleted"),
151152 (status = 401, description = "Not authenticated", body = ErrorResponse),
152- (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
153+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
153154 (status = 404, description = "Not found", body = ErrorResponse),
154155 (status = 409, description = "Exam questions still reference this subject", body = ErrorResponse),
155156 ),
@@ -162,7 +163,7 @@ async fn delete_subject(
162163 let (subject, course) = subject_with_course(&id, &st.db).await?;
163164 if !can_manage_course(&course, &user) {
164165 return Err(AppError::Forbidden(
165- "only the course creator or a manager/admin can delete this subject",
166+ "only the course creator, an assigned teacher, or a manager/admin can delete this subject",
166167 ));
167168 }
168169 // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete
src/web/users.rsmodified+9 -1
@@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter;
77 use utoipa_axum::routes;
88
99 use crate::database::Database;
10+use crate::domain::course::Course;
1011 use crate::domain::enrollment::Enrollment;
1112 use crate::domain::parent_link::ParentLink;
1213 use crate::domain::preferences::{Language, Theme};
@@ -366,7 +367,8 @@ async fn update_user_preferences(
366367 /// guard keeps a sole admin from accidentally locking everyone out of role
367368 /// management (recover such a lockout with the SurrealQL in the README).
368369 /// Setting any non-`student` role also drops the user's course enrollments —
369-/// only students enroll, so a promoted user leaves every roster.
370+/// only students enroll, so a promoted user leaves every roster. Demoting below
371+/// `teacher` drops their course teaching assignments for the mirror reason.
370372 #[utoipa::path(
371373 patch,
372374 path = "/{id}/role",
@@ -410,6 +412,12 @@ async fn set_role(
410412 if role != Role::Parent {
411413 ParentLink::delete_where_parent(&target, &st.db).await?;
412414 }
415+ // Course staffing gets the same sweep: only teacher+ may be assigned to
416+ // run a course, so a demotion drops every assignment instead of leaving
417+ // rows that grant nothing and still list a demoted user as its teacher.
418+ if !role.at_least(Role::Teacher) {
419+ Course::unassign_everywhere(&target, &st.db).await?;
420+ }
413421 Ok(Json(UserResponse::new(&updated)))
414422 }
415423
tests/integration.rsmodified+323 -14
@@ -2174,6 +2174,247 @@ async fn courses_are_owner_scoped_and_creator_guarded() {
21742174 );
21752175 }
21762176
2177+/// A manager can put a second teacher in charge of someone else's course. The
2178+/// assignee then manages everything inside it, but the course stays its
2179+/// creator's to delete — and a demotion takes the assignment away.
2180+#[tokio::test]
2181+async fn assigned_teacher_manages_course_without_owning_it() {
2182+ let (app, db) = app_and_db().await;
2183+ let ali = login_as(&app, &db, "ali", "teacher").await;
2184+ let veli = login_as(&app, &db, "veli", "teacher").await;
2185+ let boss = login_as(&app, &db, "boss", "manager").await;
2186+ let rektor = login_as(&app, &db, "rektor", "admin").await;
2187+ let veli_id = id_of(&send(&app, "GET", "/auth/me", Some(&veli), None).await.body);
2188+
2189+ let course_id = id_of(
2190+ &send(
2191+ &app,
2192+ "POST",
2193+ "/courses",
2194+ Some(&ali),
2195+ Some(json!({ "title": "algebra" })),
2196+ )
2197+ .await
2198+ .body,
2199+ );
2200+ let teachers = format!("/courses/{course_id}/teachers");
2201+
2202+ // Before assignment veli is just another teacher: no read, no write.
2203+ assert_eq!(
2204+ send(
2205+ &app,
2206+ "GET",
2207+ &format!("/courses/{course_id}"),
2208+ Some(&veli),
2209+ None
2210+ )
2211+ .await
2212+ .status,
2213+ StatusCode::FORBIDDEN
2214+ );
2215+
2216+ // Staffing is the office's call — the course's own creator cannot do it.
2217+ assert_eq!(
2218+ send(
2219+ &app,
2220+ "POST",
2221+ &teachers,
2222+ Some(&ali),
2223+ Some(json!({ "user_id": veli_id }))
2224+ )
2225+ .await
2226+ .status,
2227+ StatusCode::FORBIDDEN
2228+ );
2229+
2230+ // Only teacher+ can be assigned.
2231+ let student = login_as(&app, &db, "zeynep", "student").await;
2232+ let student_id = id_of(
2233+ &send(&app, "GET", "/auth/me", Some(&student), None)
2234+ .await
2235+ .body,
2236+ );
2237+ assert_eq!(
2238+ send(
2239+ &app,
2240+ "POST",
2241+ &teachers,
2242+ Some(&boss),
2243+ Some(json!({ "user_id": student_id }))
2244+ )
2245+ .await
2246+ .status,
2247+ StatusCode::BAD_REQUEST
2248+ );
2249+
2250+ // The manager assigns veli; the course echoes its staff back.
2251+ let res = send(
2252+ &app,
2253+ "POST",
2254+ &teachers,
2255+ Some(&boss),
2256+ Some(json!({ "user_id": veli_id })),
2257+ )
2258+ .await;
2259+ assert_eq!(res.status, StatusCode::OK);
2260+ assert_eq!(res.body["creator"]["username"], "ali");
2261+ assert_eq!(res.body["teachers"][0]["username"], "veli");
2262+
2263+ // Assigning twice is idempotent — no duplicate row in the list.
2264+ let again = send(
2265+ &app,
2266+ "POST",
2267+ &teachers,
2268+ Some(&boss),
2269+ Some(json!({ "user_id": veli_id })),
2270+ )
2271+ .await;
2272+ assert_eq!(again.status, StatusCode::OK);
2273+ assert_eq!(again.body["teachers"].as_array().unwrap().len(), 1);
2274+
2275+ // Veli now runs the course: it shows in their catalog, and they can edit
2276+ // it and enroll students.
2277+ let catalog = send(&app, "GET", "/courses", Some(&veli), None).await.body;
2278+ assert_eq!(common::items(&catalog).len(), 1);
2279+ assert_eq!(
2280+ send(
2281+ &app,
2282+ "PATCH",
2283+ &format!("/courses/{course_id}"),
2284+ Some(&veli),
2285+ Some(json!({"description":"letters"}))
2286+ )
2287+ .await
2288+ .status,
2289+ StatusCode::OK
2290+ );
2291+ assert_eq!(
2292+ send(
2293+ &app,
2294+ "POST",
2295+ &format!("/courses/{course_id}/enrollments"),
2296+ Some(&veli),
2297+ Some(json!({ "user_id": student_id }))
2298+ )
2299+ .await
2300+ .status,
2301+ StatusCode::OK
2302+ );
2303+
2304+ // But the course is not theirs to delete, nor to re-staff.
2305+ assert_eq!(
2306+ send(
2307+ &app,
2308+ "DELETE",
2309+ &format!("/courses/{course_id}"),
2310+ Some(&veli),
2311+ None
2312+ )
2313+ .await
2314+ .status,
2315+ StatusCode::FORBIDDEN
2316+ );
2317+ assert_eq!(
2318+ send(
2319+ &app,
2320+ "DELETE",
2321+ &format!("{teachers}/{veli_id}"),
2322+ Some(&veli),
2323+ None
2324+ )
2325+ .await
2326+ .status,
2327+ StatusCode::FORBIDDEN
2328+ );
2329+
2330+ // Demoting veli below teacher sweeps the assignment: the course drops off
2331+ // their catalog and the rights go with it.
2332+ assert_eq!(
2333+ send(
2334+ &app,
2335+ "PATCH",
2336+ &format!("/users/{veli_id}/role"),
2337+ Some(&rektor),
2338+ Some(json!({"role":"student"}))
2339+ )
2340+ .await
2341+ .status,
2342+ StatusCode::OK
2343+ );
2344+ let after = send(
2345+ &app,
2346+ "GET",
2347+ &format!("/courses/{course_id}"),
2348+ Some(&ali),
2349+ None,
2350+ )
2351+ .await;
2352+ assert_eq!(
2353+ after.body["teachers"].as_array().unwrap().len(),
2354+ 0,
2355+ "a demoted teacher is swept off the courses they were assigned to"
2356+ );
2357+
2358+ // Re-assign, then unassign by hand: the second removal is a 404.
2359+ send(
2360+ &app,
2361+ "PATCH",
2362+ &format!("/users/{veli_id}/role"),
2363+ Some(&rektor),
2364+ Some(json!({"role":"teacher"})),
2365+ )
2366+ .await;
2367+ assert_eq!(
2368+ send(
2369+ &app,
2370+ "POST",
2371+ &teachers,
2372+ Some(&boss),
2373+ Some(json!({ "user_id": veli_id }))
2374+ )
2375+ .await
2376+ .status,
2377+ StatusCode::OK
2378+ );
2379+ assert_eq!(
2380+ send(
2381+ &app,
2382+ "DELETE",
2383+ &format!("{teachers}/{veli_id}"),
2384+ Some(&boss),
2385+ None
2386+ )
2387+ .await
2388+ .status,
2389+ StatusCode::NO_CONTENT
2390+ );
2391+ assert_eq!(
2392+ send(
2393+ &app,
2394+ "DELETE",
2395+ &format!("{teachers}/{veli_id}"),
2396+ Some(&boss),
2397+ None
2398+ )
2399+ .await
2400+ .status,
2401+ StatusCode::NOT_FOUND
2402+ );
2403+ assert_eq!(
2404+ send(
2405+ &app,
2406+ "GET",
2407+ &format!("/courses/{course_id}"),
2408+ Some(&veli),
2409+ None
2410+ )
2411+ .await
2412+ .status,
2413+ StatusCode::FORBIDDEN,
2414+ "unassigning takes the course back out of their reach"
2415+ );
2416+}
2417+
21772418 #[tokio::test]
21782419 async fn course_input_validation() {
21792420 let (app, db) = app_and_db().await;
@@ -5032,7 +5273,11 @@ async fn db_down_refuses_before_touching_the_database() {
50325273 .await
50335274 .unwrap();
50345275 assert_eq!(ok.status(), StatusCode::CREATED);
5035- assert_eq!(count_rows(&db, "user").await, before + 1, "the write landed");
5276+ assert_eq!(
5277+ count_rows(&db, "user").await,
5278+ before + 1,
5279+ "the write landed"
5280+ );
50365281
50375282 // Socket reported down: refused with a retryable 503, and — the point of
50385283 // refusing at the edge rather than timing out — nothing was written.
@@ -11543,7 +11788,14 @@ async fn question_pool_lifecycle() {
1154311788
1154411789 // Only students ask: the teacher is refused.
1154511790 let ask = json!({ "title": "Integral", "body": "∫x·eˣ dx?" });
11546- let res = send(&app, "POST", "/questions", Some(&teacher), Some(ask.clone())).await;
11791+ let res = send(
11792+ &app,
11793+ "POST",
11794+ "/questions",
11795+ Some(&teacher),
11796+ Some(ask.clone()),
11797+ )
11798+ .await;
1154711799 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
1154811800
1154911801 let res = send(&app, "POST", "/questions", Some(&asker), Some(ask)).await;
@@ -11554,8 +11806,19 @@ async fn question_pool_lifecycle() {
1155411806 // Pending: the asker and the teacher see it; another student must not
1155511807 // even learn it exists — and it takes no solutions yet.
1155611808 for (cookie, visible) in [(&asker, true), (&teacher, true), (&stranger, false)] {
11557- let res = send(&app, "GET", &format!("/questions/{qid}"), Some(cookie), None).await;
11558- let expected = if visible { StatusCode::OK } else { StatusCode::NOT_FOUND };
11809+ let res = send(
11810+ &app,
11811+ "GET",
11812+ &format!("/questions/{qid}"),
11813+ Some(cookie),
11814+ None,
11815+ )
11816+ .await;
11817+ let expected = if visible {
11818+ StatusCode::OK
11819+ } else {
11820+ StatusCode::NOT_FOUND
11821+ };
1155911822 assert_eq!(res.status, expected, "{}", res.body);
1156011823 }
1156111824 let offer = json!({ "body": "Kısmi integrasyon." });
@@ -11571,7 +11834,14 @@ async fn question_pool_lifecycle() {
1157111834
1157211835 // The teacher's ?status=pending list is the approval queue; approval is
1157311836 // teacher-gated and one-way.
11574- let res = send(&app, "GET", "/questions?status=pending", Some(&teacher), None).await;
11837+ let res = send(
11838+ &app,
11839+ "GET",
11840+ "/questions?status=pending",
11841+ Some(&teacher),
11842+ None,
11843+ )
11844+ .await;
1157511845 assert_eq!(common::total(&res.body), 1);
1157611846 let res = send(
1157711847 &app,
@@ -11638,9 +11908,23 @@ async fn question_pool_lifecycle() {
1163811908 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
1163911909
1164011910 // Question delete (asker withdraws) cascades what's left.
11641- let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await;
11911+ let res = send(
11912+ &app,
11913+ "DELETE",
11914+ &format!("/questions/{qid}"),
11915+ Some(&asker),
11916+ None,
11917+ )
11918+ .await;
1164211919 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
11643- let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&teacher), None).await;
11920+ let res = send(
11921+ &app,
11922+ "GET",
11923+ &format!("/questions/{qid}"),
11924+ Some(&teacher),
11925+ None,
11926+ )
11927+ .await;
1164411928 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
1164511929 }
1164611930
@@ -11714,7 +11998,8 @@ async fn question_pool_image_upload_and_freeze() {
1171411998 assert_eq!(status, StatusCode::OK);
1171511999 assert_eq!(headers["content-type"], "image/png");
1171612000 assert_eq!(bytes, b"png-bytes");
11717- let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await;
12001+ let (status, _, _) =
12002+ common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await;
1171812003 assert_eq!(status, StatusCode::NOT_FOUND);
1171912004
1172012005 // Approval freezes the image with the text: replace and remove both 409.
@@ -11734,9 +12019,17 @@ async fn question_pool_image_upload_and_freeze() {
1173412019 assert_eq!(status, StatusCode::CONFLICT);
1173512020
1173612021 // But the approved bytes are now school-wide, and ride the question meta.
11737- let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await;
12022+ let (status, _, _) =
12023+ common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await;
1173812024 assert_eq!(status, StatusCode::OK);
11739- let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&stranger), None).await;
12025+ let res = send(
12026+ &app,
12027+ "GET",
12028+ &format!("/questions/{qid}"),
12029+ Some(&stranger),
12030+ None,
12031+ )
12032+ .await;
1174012033 assert_eq!(res.body["image"]["content_type"], "image/png");
1174112034 }
1174212035
@@ -11851,18 +12144,34 @@ async fn solution_images_edits_and_counts() {
1185112144 // Question rows tally their solutions, in the list and the single GET.
1185212145 let res = send(&app, "GET", "/questions?limit=5", Some(&asker), None).await;
1185312146 assert_eq!(res.body["items"][0]["solution_count"], 1);
11854- let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&asker), None).await;
12147+ let res = send(
12148+ &app,
12149+ "GET",
12150+ &format!("/questions/{qid}"),
12151+ Some(&asker),
12152+ None,
12153+ )
12154+ .await;
1185512155 assert_eq!(res.body["solution_count"], 1);
1185612156
1185712157 // The author drops the photo; a second removal finds nothing.
11858- let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await;
12158+ let (status, _, _) =
12159+ common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await;
1185912160 assert_eq!(status, StatusCode::NO_CONTENT);
1186012161 let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await;
1186112162 assert_eq!(status, StatusCode::NOT_FOUND);
11862- let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await;
12163+ let (status, _, _) =
12164+ common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await;
1186312165 assert_eq!(status, StatusCode::NOT_FOUND);
1186412166
1186512167 // And the question delete still sweeps everything under it.
11866- let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await;
12168+ let res = send(
12169+ &app,
12170+ "DELETE",
12171+ &format!("/questions/{qid}"),
12172+ Some(&asker),
12173+ None,
12174+ )
12175+ .await;
1186712176 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
1186812177 }