Student Q&A pool with moderated solutions
Browse files at this commit0df048b7abc1eef44bf7872b578ffa38575c2f18Parent: 60b4509- feat
- student Q&A pool with moderated solutions
11 changed files +2348 -51
- README.md +90 -2
- src/constant.rs +15 -3
- src/database.rs +25 -0
- src/domain/mod.rs +2 -0
- src/domain/pool_question.rs +457 -0
- src/domain/solution.rs +442 -0
- src/lib.rs +3 -1
- src/web/exams.rs +7 -43
- src/web/mod.rs +48 -2
- src/web/questions.rs +920 -0
- tests/integration.rs +339 -0
README.mdmodified+90 -2
| @@ -52,6 +52,15 @@ with a server-stamped **pomodoro log** (the timer runs in the frontend; the | |||
| 52 | backend records the focus stints, and teachers can read any student's log), | 52 | backend records the focus stints, and teachers can read any student's log), |
| 53 | and every user has an | 53 | and every user has an |
| 54 | **attendance report** (event + per-course lesson tallies with rates). | 54 | **attendance report** (event + per-course lesson tallies with rates). |
| 55 | +A school-wide **question pool** runs on moderation: a student asks a question | ||
| 56 | +(optionally attaching one photo of the problem — raster only, same | ||
| 57 | +`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes | ||
| 58 | +it — rejection is deletion, there is no rejected state), and every approved | ||
| 59 | +question is readable by the whole school with anyone free to offer | ||
| 60 | +**solutions** under it (parents stay out) — text plus an optional photo of | ||
| 61 | +the worked steps, both editable by the solution's author anytime; pending | ||
| 62 | +questions show only to their asker and to teacher+, and approval freezes the | ||
| 63 | +content so nothing unmoderated ever reaches the pool. | ||
| 55 | School-varying policy is data, not code: exam kinds (each with its weight in | 64 | School-varying policy is data, not code: exam kinds (each with its weight in |
| 56 | course averages), attendance statuses, grade-display bands, and the note-file | 65 | course averages), attendance statuses, grade-display bands, and the note-file |
| 57 | size limit live in an editable **settings** singleton, and academic **terms** | 66 | size limit live in an editable **settings** singleton, and academic **terms** |
| @@ -101,6 +110,12 @@ container so the published port works. Production knobs (`COOKIE_SECURE`, | |||
| 101 | means dev mirror mode without credentials; a cookie-using browser frontend | 110 | means dev mirror mode without credentials; a cookie-using browser frontend |
| 102 | must be allowlisted explicitly. Works with `docker compose` too. | 111 | must be allowlisted explicitly. Works with `docker compose` too. |
| 103 | 112 | ||
| 113 | +The backend keeps its database WebSocket alive with a periodic trivial query, | ||
| 114 | +and the SDK reconnects on its own if the socket drops anyway (a `podman | ||
| 115 | +restart hezarfen-surrealdb`, say). During that brief reconnect window requests | ||
| 116 | +answer `503` with `Retry-After: 1` instead of a `500` — the outage is | ||
| 117 | +transient, so clients just retry a moment later. | ||
| 118 | + | ||
| 104 | Without compose: | 119 | Without compose: |
| 105 | 120 | ||
| 106 | ```sh | 121 | ```sh |
| @@ -227,6 +242,9 @@ course enrollments. | |||
| 227 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | 242 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | |
| 228 | | Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | | 243 | | Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | |
| 229 | | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' | | 244 | | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' | |
| 245 | +| Ask into the school question pool | student | **Students only** (exact); born `pending` — visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending | | ||
| 246 | +| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any | | ||
| 247 | +| 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 | | ||
| 230 | | Read **own** attendance report | student | | | 248 | | Read **own** attendance report | student | | |
| 231 | | 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 | | 249 | | 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 | |
| 232 | | 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 | | 250 | | 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 | |
| @@ -413,6 +431,21 @@ their existing shapes: the student exam-room reads | |||
| 413 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | 431 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | |
| 414 | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager) | | 432 | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager) | |
| 415 | | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | | 433 | | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | |
| 434 | +| POST | `/questions` | student | `{title, body}` — ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ | | ||
| 435 | +| GET | `/questions` | student | `?status=pending\|approved` — the pool questions visible to the caller, each with its `solution_count` · paged | | ||
| 436 | +| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) | | ||
| 437 | +| POST | `/questions/{id}/approve` | teacher | Approve a pending question — publishes it school-wide; content frozen after (`409` if already approved) | | ||
| 438 | +| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it | | ||
| 439 | +| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≤ `max_file_bytes` | | ||
| 440 | +| GET | `/questions/{id}/image` | student | The photo bytes | | ||
| 441 | +| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) | | ||
| 442 | +| POST | `/questions/{id}/solutions` | student | `{body}` — offer a solution on an approved question (anyone in the school) | | ||
| 443 | +| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first — a discussion thread · paged | | ||
| 444 | +| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it | | ||
| 445 | +| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` — edit own solution (author only, teacher+ included out; solutions never freeze) | | ||
| 446 | +| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≤ `max_file_bytes` | | ||
| 447 | +| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) | | ||
| 448 | +| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) | | ||
| 416 | | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) | | 449 | | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) | |
| 417 | | GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | | 450 | | GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | |
| 418 | | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) | | 451 | | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) | |
| @@ -545,6 +578,42 @@ and physically removes the row once both sides have deleted theirs. Replying | |||
| 545 | is just sending a new message back — the frontend prefixes the subject if it | 578 | is just sending a new message back — the frontend prefixes the subject if it |
| 546 | wants an `Re:`. | 579 | wants an `Re:`. |
| 547 | 580 | ||
| 581 | +## Question pool | ||
| 582 | + | ||
| 583 | +Students get stuck; the pool is where the school unsticks them — with a | ||
| 584 | +moderation gate so nothing unreviewed goes school-wide. `POST /questions` | ||
| 585 | +(students only, exact role) creates the question `pending`: only the asker | ||
| 586 | +and teacher+ can see it (anyone else gets a `404`, not a `403` — a pending | ||
| 587 | +question's existence is nobody else's business), and `GET | ||
| 588 | +/questions?status=pending` is a teacher's approval queue. The asker may | ||
| 589 | +attach **one photo** of the problem (`POST /questions/{id}/image`, | ||
| 590 | +`multipart/form-data` with a `file` part — raster types only, no SVG, ≤ the | ||
| 591 | +school's `max_file_bytes`), replace it, or remove it — while pending only. | ||
| 592 | + | ||
| 593 | +`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes | ||
| 594 | +readable by every signed-in user above `parent`, and its content — title, | ||
| 595 | +body, photo — **freezes**, because an edit after approval would bypass the | ||
| 596 | +moderation that just happened. There is no rejected state and no edit | ||
| 597 | +endpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+ | ||
| 598 | +deletes. Approving twice is a `409`; the response records `approved_by`. | ||
| 599 | + | ||
| 600 | +Anyone in the school (student through admin — not parents) may then offer a | ||
| 601 | +**solution**: `POST /questions/{id}/solutions` with a text body, listed | ||
| 602 | +oldest-first like a discussion thread (`GET`, paged). Solutions are the | ||
| 603 | +unmoderated half of the pool, so nothing about them ever freezes: the author | ||
| 604 | +— and only the author, teacher+ included out — may edit the body (`PATCH | ||
| 605 | +/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked | ||
| 606 | +steps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules | ||
| 607 | +and `max_file_bytes` cap as the question's photo), replace it, or remove it, | ||
| 608 | +at any time; moderation stays delete-only — a teacher+ removes a bad | ||
| 609 | +solution, never rewrites someone else's words. A solution is deleted by its | ||
| 610 | +author or by teacher+, its photo blob going with it; deleting a question — | ||
| 611 | +asker withdrawing, or teacher+ moderating — takes its solutions and every | ||
| 612 | +photo blob (its own and its solutions') with it. Each question row reports | ||
| 613 | +its `solution_count`, and questions and solutions embed their people as | ||
| 614 | +person refs (`{id, username, display_name}`), so the UI never shows a raw | ||
| 615 | +ULID. | ||
| 616 | + | ||
| 548 | ## Per-school policy (settings & terms) | 617 | ## Per-school policy (settings & terms) |
| 549 | 618 | ||
| 550 | Every school runs differently; the parts that vary are data, not code. One | 619 | Every school runs differently; the parts that vary are data, not code. One |
| @@ -1017,13 +1086,32 @@ src/ | |||
| 1017 | exam_answer.rs ExamAnswerId · AnswerText · ExamAnswer (one row per question+user) · | 1086 | exam_answer.rs ExamAnswerId · AnswerText · ExamAnswer (one row per question+user) · |
| 1018 | auto_score (choice-question suggestion) | 1087 | auto_score (choice-question suggestion) |
| 1019 | exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user) | 1088 | exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user) |
| 1089 | + question_image.rs QuestionImageId · QuestionImage (question/choice picture | ||
| 1090 | + metadata; bytes on disk under FILES_PATH) | ||
| 1091 | + profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) | ||
| 1092 | + preferences.rs Theme · Language (own UI preferences) | ||
| 1093 | + message.rs MessageId · MessageSubject · MessageBody · MessageLabel · | ||
| 1094 | + Message (per-copy folders: inbox/sent/archive/trash) | ||
| 1095 | + parent_link.rs ParentLinkId · ParentLink (parent↔student tie = the parent's read grant) | ||
| 1096 | + registration.rs RegistrationId · Registration (a seat on a registration event's signup list) | ||
| 1097 | + subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum) | ||
| 1098 | + term.rs TermId · TermName · Term (school term window) | ||
| 1099 | + settings.rs ExamKindDef · GradeBand · Settings (per-school policy) | ||
| 1100 | + pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log) | ||
| 1101 | + pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody · | ||
| 1102 | + PoolQuestion (student-asked question; teacher-approved into | ||
| 1103 | + the school-wide pool; optional photo as metadata + disk blob) | ||
| 1104 | + solution.rs SolutionId · SolutionBody · Solution (discussion thread on an | ||
| 1105 | + approved pool question; dies with the question) | ||
| 1020 | web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + | 1106 | web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + |
| 1021 | auth extractors | 1107 | auth extractors |
| 1022 | extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin | 1108 | extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin |
| 1023 | dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas | 1109 | dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas |
| 1024 | exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish) | 1110 | exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish) |
| 1025 | - auth.rs users.rs notes.rs events.rs courses.rs sessions.rs exams.rs | 1111 | + page.rs PageParams · Page<T> (shared pagination) |
| 1026 | - marks.rs work.rs attendance.rs | 1112 | + auth.rs users.rs notes.rs messages.rs events.rs courses.rs subjects.rs |
| 1113 | + sessions.rs exams.rs questions.rs marks.rs work.rs pomodoro.rs | ||
| 1114 | + attendance.rs settings.rs terms.rs | ||
| 1027 | ``` | 1115 | ``` |
| 1028 | 1116 | ||
| 1029 | Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory | 1117 | Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory |
src/constant.rsmodified+15 -3
| @@ -61,12 +61,18 @@ pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024; | |||
| 61 | /// the file bytes themselves. | 61 | /// the file bytes themselves. |
| 62 | pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; | 62 | pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; |
| 63 | 63 | ||
| 64 | -/// The content types a question image may declare — raster formats only. SVG | 64 | +/// The content types an uploaded inline image (exam question images, pool |
| 65 | -/// is deliberately out: it can carry scripts, and these bytes are served for | 65 | +/// question photos) may declare — raster formats only. SVG is deliberately |
| 66 | -/// inline display to everyone sitting the exam. | 66 | +/// out: it can carry scripts, and these bytes are served for inline display |
| 67 | +/// to whole classes. | ||
| 67 | pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] = | 68 | pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] = |
| 68 | ["image/png", "image/jpeg", "image/webp", "image/gif"]; | 69 | ["image/png", "image/jpeg", "image/webp", "image/gif"]; |
| 69 | 70 | ||
| 71 | +/// Bounds for a pool question (the student-asked Q&A pool) and its solutions. | ||
| 72 | +pub const MAX_POOL_QUESTION_TITLE_LEN: usize = 200; | ||
| 73 | +pub const MAX_POOL_QUESTION_BODY_LEN: usize = 10_000; | ||
| 74 | +pub const MAX_SOLUTION_BODY_LEN: usize = 10_000; | ||
| 75 | + | ||
| 70 | pub const MAX_EVENT_TITLE_LEN: usize = 200; | 76 | pub const MAX_EVENT_TITLE_LEN: usize = 200; |
| 71 | pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; | 77 | pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; |
| 72 | 78 | ||
| @@ -141,6 +147,12 @@ pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; | |||
| 141 | /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). | 147 | /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). |
| 142 | pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; | 148 | pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; |
| 143 | 149 | ||
| 150 | +/// Cadence of the background keepalive query on the database WebSocket. The | ||
| 151 | +/// traffic keeps the connection from being dropped as idle; when it does drop, | ||
| 152 | +/// the ping also makes the SDK notice and reconnect long before the next real | ||
| 153 | +/// request would. | ||
| 154 | +pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 30; | ||
| 155 | + | ||
| 144 | /// Cadence of the `state` ticks on the student exam-room WebSocket | 156 | /// Cadence of the `state` ticks on the student exam-room WebSocket |
| 145 | /// (`GET /exams/{id}/attempt/ws`). | 157 | /// (`GET /exams/{id}/attempt/ws`). |
| 146 | pub const EXAM_WS_TICK_SECS: u64 = 2; | 158 | pub const EXAM_WS_TICK_SECS: u64 = 2; |
src/database.rsmodified+25 -0
| @@ -33,6 +33,8 @@ pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session"; | |||
| 33 | pub const SETTINGS_TABLE: &str = "settings"; | 33 | pub const SETTINGS_TABLE: &str = "settings"; |
| 34 | pub const TERM_TABLE: &str = "term"; | 34 | pub const TERM_TABLE: &str = "term"; |
| 35 | pub const SUBJECT_TABLE: &str = "subject"; | 35 | pub const SUBJECT_TABLE: &str = "subject"; |
| 36 | +pub const POOL_QUESTION_TABLE: &str = "pool_question"; | ||
| 37 | +pub const SOLUTION_TABLE: &str = "solution"; | ||
| 36 | 38 | ||
| 37 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. | 39 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 38 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the | 40 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the |
| @@ -246,6 +248,29 @@ const MIGRATION: &str = " | |||
| 246 | DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>; | 248 | DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>; |
| 247 | DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE; | 249 | DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE; |
| 248 | 250 | ||
| 251 | + DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; | ||
| 252 | + DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>; | ||
| 253 | + DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; | ||
| 254 | + DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; | ||
| 255 | + DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; | ||
| 256 | + DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; | ||
| 257 | + DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>; | ||
| 258 | + DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>; | ||
| 259 | + DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>; | ||
| 260 | + DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>; | ||
| 261 | + DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; | ||
| 262 | + DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; | ||
| 263 | + | ||
| 264 | + DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; | ||
| 265 | + DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>; | ||
| 266 | + DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>; | ||
| 267 | + DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; | ||
| 268 | + DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; | ||
| 269 | + DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>; | ||
| 270 | + DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>; | ||
| 271 | + DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>; | ||
| 272 | + DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; | ||
| 273 | + | ||
| 249 | DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; | 274 | DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; |
| 250 | DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>; | 275 | DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>; |
| 251 | DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; | 276 | DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; |
src/domain/mod.rsmodified+2 -0
| @@ -17,6 +17,7 @@ pub mod note; | |||
| 17 | pub mod note_file; | 17 | pub mod note_file; |
| 18 | pub mod parent_link; | 18 | pub mod parent_link; |
| 19 | pub mod pomodoro; | 19 | pub mod pomodoro; |
| 20 | +pub mod pool_question; | ||
| 20 | pub mod preferences; | 21 | pub mod preferences; |
| 21 | pub mod profile; | 22 | pub mod profile; |
| 22 | pub mod question_image; | 23 | pub mod question_image; |
| @@ -25,6 +26,7 @@ pub mod role; | |||
| 25 | pub mod session; | 26 | pub mod session; |
| 26 | pub mod session_attendance; | 27 | pub mod session_attendance; |
| 27 | pub mod settings; | 28 | pub mod settings; |
| 29 | +pub mod solution; | ||
| 28 | pub mod subject; | 30 | pub mod subject; |
| 29 | pub mod term; | 31 | pub mod term; |
| 30 | pub mod timestamp; | 32 | pub mod timestamp; |
src/domain/pool_question.rsadded+457 -0
| @@ -0,0 +1,457 @@ | |||
| 1 | +//! A student-asked question on its way into the school-wide question pool. | ||
| 2 | +//! Born `pending` (visible to its asker and to teacher+, who run the approval | ||
| 3 | +//! queue); a teacher+ approval flips it to `approved`, which publishes it to | ||
| 4 | +//! the whole school for everyone to read and offer solutions on. Approved | ||
| 5 | +//! content is frozen — edits after approval would bypass moderation — so the | ||
| 6 | +//! only post-approval change is deletion (asker or teacher+), which takes the | ||
| 7 | +//! question's solutions with it. An optional photo of the problem rides on | ||
| 8 | +//! the row as metadata (`image_*`); the bytes live on disk under | ||
| 9 | +//! [`crate::config::Config::files_path`] in a file named by `image_file` — a | ||
| 10 | +//! fresh server-generated ULID per upload. The web layer owns the blob I/O; | ||
| 11 | +//! this module owns the rows. | ||
| 12 | + | ||
| 13 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 14 | +use ulid::Ulid; | ||
| 15 | + | ||
| 16 | +use crate::constant::{MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN}; | ||
| 17 | +use crate::database::{Database, POOL_QUESTION_TABLE}; | ||
| 18 | +use crate::domain::note_file::FileContentType; | ||
| 19 | +use crate::domain::solution::Solution; | ||
| 20 | +use crate::domain::timestamp::Timestamp; | ||
| 21 | +use crate::domain::user::UserId; | ||
| 22 | +use crate::error::{AppError, ValidationError}; | ||
| 23 | +use crate::validate::validate_required; | ||
| 24 | + | ||
| 25 | +/// The two lifecycle states. `pending`: awaiting teacher+ approval, visible | ||
| 26 | +/// only to the asker and to teacher+. `approved`: in the pool, school-wide. | ||
| 27 | +/// Rejection is not a state — a teacher+ simply deletes the question. | ||
| 28 | +pub const STATUS_PENDING: &str = "pending"; | ||
| 29 | +pub const STATUS_APPROVED: &str = "approved"; | ||
| 30 | +pub const POOL_QUESTION_STATUSES: [&str; 2] = [STATUS_PENDING, STATUS_APPROVED]; | ||
| 31 | + | ||
| 32 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 33 | +pub struct PoolQuestionId(RecordId); | ||
| 34 | + | ||
| 35 | +impl PoolQuestionId { | ||
| 36 | + pub fn generate() -> Self { | ||
| 37 | + Self(RecordId::new(POOL_QUESTION_TABLE, Ulid::new().to_string())) | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + pub fn from_key(key: &str) -> Self { | ||
| 41 | + Self(RecordId::new(POOL_QUESTION_TABLE, key)) | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + pub fn record(&self) -> RecordId { | ||
| 45 | + self.0.clone() | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + pub fn key(&self) -> &str { | ||
| 49 | + match &self.0.key { | ||
| 50 | + RecordIdKey::String(key) => key, | ||
| 51 | + _ => "", | ||
| 52 | + } | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 57 | +pub struct PoolQuestionTitle(String); | ||
| 58 | + | ||
| 59 | +impl PoolQuestionTitle { | ||
| 60 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 61 | + validate_required("title", value, MAX_POOL_QUESTION_TITLE_LEN)?; | ||
| 62 | + Ok(Self(value.to_string())) | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + pub fn as_str(&self) -> &str { | ||
| 66 | + &self.0 | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 71 | +pub struct PoolQuestionBody(String); | ||
| 72 | + | ||
| 73 | +impl PoolQuestionBody { | ||
| 74 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 75 | + validate_required("body", value, MAX_POOL_QUESTION_BODY_LEN)?; | ||
| 76 | + Ok(Self(value.to_string())) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub fn as_str(&self) -> &str { | ||
| 80 | + &self.0 | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 85 | +pub struct PoolQuestion { | ||
| 86 | + id: PoolQuestionId, | ||
| 87 | + asker: UserId, | ||
| 88 | + title: PoolQuestionTitle, | ||
| 89 | + body: PoolQuestionBody, | ||
| 90 | + status: String, | ||
| 91 | + asked_at: Timestamp, | ||
| 92 | + approved_by: Option<UserId>, | ||
| 93 | + /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | ||
| 94 | + /// the question carries no image. | ||
| 95 | + image_file: Option<String>, | ||
| 96 | + image_content_type: Option<FileContentType>, | ||
| 97 | + image_size: Option<i64>, | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +impl PoolQuestion { | ||
| 101 | + pub fn new(asker: &UserId, title: PoolQuestionTitle, body: PoolQuestionBody) -> Self { | ||
| 102 | + Self { | ||
| 103 | + id: PoolQuestionId::generate(), | ||
| 104 | + asker: asker.clone(), | ||
| 105 | + title, | ||
| 106 | + body, | ||
| 107 | + status: STATUS_PENDING.to_string(), | ||
| 108 | + asked_at: Timestamp::now(), | ||
| 109 | + approved_by: None, | ||
| 110 | + image_file: None, | ||
| 111 | + image_content_type: None, | ||
| 112 | + image_size: None, | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + pub fn get_id(&self) -> &PoolQuestionId { | ||
| 117 | + &self.id | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + pub fn get_asker(&self) -> &UserId { | ||
| 121 | + &self.asker | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + pub fn get_title(&self) -> &PoolQuestionTitle { | ||
| 125 | + &self.title | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + pub fn get_body(&self) -> &PoolQuestionBody { | ||
| 129 | + &self.body | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + pub fn get_status(&self) -> &str { | ||
| 133 | + &self.status | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + pub fn is_approved(&self) -> bool { | ||
| 137 | + self.status == STATUS_APPROVED | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + pub fn get_asked_at(&self) -> Timestamp { | ||
| 141 | + self.asked_at | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + pub fn get_approved_by(&self) -> Option<&UserId> { | ||
| 145 | + self.approved_by.as_ref() | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + pub fn get_image_file(&self) -> Option<&str> { | ||
| 149 | + self.image_file.as_deref() | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + pub fn get_image_content_type(&self) -> Option<&FileContentType> { | ||
| 153 | + self.image_content_type.as_ref() | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + pub fn get_image_size(&self) -> Option<i64> { | ||
| 157 | + self.image_size | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + pub async fn insert(self, db: &Database) -> Result<PoolQuestion, AppError> { | ||
| 161 | + let created: Option<PoolQuestion> = db.create(self.id.record()).content(self).await?; | ||
| 162 | + created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) | ||
| 163 | + } | ||
| 164 | + | ||
| 165 | + pub async fn read(id: &PoolQuestionId, db: &Database) -> Result<Option<PoolQuestion>, AppError> { | ||
| 166 | + Ok(db.select(id.record()).await?) | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + /// Every question, newest first — the teacher+ view (approval queue and | ||
| 170 | + /// pool in one list). | ||
| 171 | + pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 172 | + let mut result = db | ||
| 173 | + .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") | ||
| 174 | + .await? | ||
| 175 | + .check()?; | ||
| 176 | + Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + /// The pool as a non-staff user sees it, newest first: every approved | ||
| 180 | + /// question, plus the caller's own pending ones. | ||
| 181 | + pub async fn list_visible_to( | ||
| 182 | + user: &UserId, | ||
| 183 | + db: &Database, | ||
| 184 | + ) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 185 | + let mut result = db | ||
| 186 | + .query( | ||
| 187 | + "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ | ||
| 188 | + ORDER BY asked_at DESC, id DESC", | ||
| 189 | + ) | ||
| 190 | + .bind(("approved", STATUS_APPROVED)) | ||
| 191 | + .bind(("usr", user.record())) | ||
| 192 | + .await? | ||
| 193 | + .check()?; | ||
| 194 | + Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + /// Publish a pending question into the pool, stamping who approved it. | ||
| 198 | + /// The `WHERE status = $pending` guard makes the transition atomic: of two | ||
| 199 | + /// racing approvals exactly one wins, and an approve can never land on a | ||
| 200 | + /// question deleted mid-flight. `None` = the question wasn't pending | ||
| 201 | + /// (already approved, or gone) — the caller sorts out which. | ||
| 202 | + pub async fn approve( | ||
| 203 | + id: &PoolQuestionId, | ||
| 204 | + approver: &UserId, | ||
| 205 | + db: &Database, | ||
| 206 | + ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 207 | + let mut result = db | ||
| 208 | + .query( | ||
| 209 | + "UPDATE $q SET status = $approved, approved_by = $by \ | ||
| 210 | + WHERE status = $pending RETURN AFTER", | ||
| 211 | + ) | ||
| 212 | + .bind(("q", id.record())) | ||
| 213 | + .bind(("approved", STATUS_APPROVED)) | ||
| 214 | + .bind(("by", approver.record())) | ||
| 215 | + .bind(("pending", STATUS_PENDING)) | ||
| 216 | + .await? | ||
| 217 | + .check()?; | ||
| 218 | + Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 219 | + } | ||
| 220 | + | ||
| 221 | + /// Point the question at a freshly written image blob. Guarded on | ||
| 222 | + /// `pending` for the same reason approval is: an image landing after | ||
| 223 | + /// approval would put unmoderated bytes in the pool, so an upload that | ||
| 224 | + /// loses the race gets `None` (and the caller takes the orphan blob back | ||
| 225 | + /// off disk). Returns the *before* row — its `image_file` is the replaced | ||
| 226 | + /// blob the caller must remove. | ||
| 227 | + pub async fn set_image( | ||
| 228 | + id: &PoolQuestionId, | ||
| 229 | + file: &str, | ||
| 230 | + content_type: &FileContentType, | ||
| 231 | + size: i64, | ||
| 232 | + db: &Database, | ||
| 233 | + ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 234 | + let mut result = db | ||
| 235 | + .query( | ||
| 236 | + "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ | ||
| 237 | + WHERE status = $pending RETURN BEFORE", | ||
| 238 | + ) | ||
| 239 | + .bind(("q", id.record())) | ||
| 240 | + .bind(("file", file.to_string())) | ||
| 241 | + .bind(("ct", content_type.clone())) | ||
| 242 | + .bind(("size", size)) | ||
| 243 | + .bind(("pending", STATUS_PENDING)) | ||
| 244 | + .await? | ||
| 245 | + .check()?; | ||
| 246 | + Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + /// Detach the question's image (pending only, like `set_image`). Returns | ||
| 250 | + /// the *before* row — its `image_file` is the blob the caller must remove. | ||
| 251 | + pub async fn clear_image( | ||
| 252 | + id: &PoolQuestionId, | ||
| 253 | + db: &Database, | ||
| 254 | + ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 255 | + let mut result = db | ||
| 256 | + .query( | ||
| 257 | + "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 258 | + WHERE status = $pending RETURN BEFORE", | ||
| 259 | + ) | ||
| 260 | + .bind(("q", id.record())) | ||
| 261 | + .bind(("pending", STATUS_PENDING)) | ||
| 262 | + .await? | ||
| 263 | + .check()?; | ||
| 264 | + Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 265 | + } | ||
| 266 | + | ||
| 267 | + /// Delete the question and its solutions in one transaction, returning | ||
| 268 | + /// the removed rows — the question's *and* the swept solutions' — so the | ||
| 269 | + /// caller can take every image blob off disk (solutions carry photos too, | ||
| 270 | + /// and a row-only sweep would strand theirs forever). | ||
| 271 | + pub async fn delete( | ||
| 272 | + id: &PoolQuestionId, | ||
| 273 | + db: &Database, | ||
| 274 | + ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | ||
| 275 | + let mut result = db | ||
| 276 | + .query( | ||
| 277 | + "BEGIN TRANSACTION; | ||
| 278 | + DELETE solution WHERE question = $q RETURN BEFORE; | ||
| 279 | + DELETE $q RETURN BEFORE; | ||
| 280 | + COMMIT TRANSACTION;", | ||
| 281 | + ) | ||
| 282 | + .bind(("q", id.record())) | ||
| 283 | + .await? | ||
| 284 | + .check()?; | ||
| 285 | + // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. | ||
| 286 | + let solutions = result.take::<Vec<Solution>>(1)?; | ||
| 287 | + Ok(result | ||
| 288 | + .take::<Vec<PoolQuestion>>(2)? | ||
| 289 | + .into_iter() | ||
| 290 | + .next() | ||
| 291 | + .map(|question| (question, solutions))) | ||
| 292 | + } | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +#[cfg(test)] | ||
| 296 | +mod tests { | ||
| 297 | + use super::*; | ||
| 298 | + use crate::database; | ||
| 299 | + use crate::domain::solution::{Solution, SolutionBody}; | ||
| 300 | + | ||
| 301 | + fn question(asker: &UserId) -> PoolQuestion { | ||
| 302 | + PoolQuestion::new( | ||
| 303 | + asker, | ||
| 304 | + PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), | ||
| 305 | + PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), | ||
| 306 | + ) | ||
| 307 | + } | ||
| 308 | + | ||
| 309 | + #[tokio::test] | ||
| 310 | + async fn approval_is_a_one_way_race_safe_transition() { | ||
| 311 | + let db = database::init_mem().await.unwrap(); | ||
| 312 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 313 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 314 | + | ||
| 315 | + let q = question(&asker).insert(&db).await.unwrap(); | ||
| 316 | + assert_eq!(q.get_status(), STATUS_PENDING); | ||
| 317 | + assert!(q.get_approved_by().is_none()); | ||
| 318 | + | ||
| 319 | + let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 320 | + .await | ||
| 321 | + .unwrap() | ||
| 322 | + .unwrap(); | ||
| 323 | + assert!(approved.is_approved()); | ||
| 324 | + assert_eq!(approved.get_approved_by(), Some(&teacher)); | ||
| 325 | + | ||
| 326 | + // A second approval finds nothing pending. | ||
| 327 | + assert!( | ||
| 328 | + PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 329 | + .await | ||
| 330 | + .unwrap() | ||
| 331 | + .is_none() | ||
| 332 | + ); | ||
| 333 | + // And a missing question approves to None, not an error. | ||
| 334 | + assert!( | ||
| 335 | + PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) | ||
| 336 | + .await | ||
| 337 | + .unwrap() | ||
| 338 | + .is_none() | ||
| 339 | + ); | ||
| 340 | + } | ||
| 341 | + | ||
| 342 | + #[tokio::test] | ||
| 343 | + async fn visibility_hides_others_pending_questions() { | ||
| 344 | + let db = database::init_mem().await.unwrap(); | ||
| 345 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 346 | + let other = UserId::from_key(&Ulid::new().to_string()); | ||
| 347 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 348 | + | ||
| 349 | + let pending = question(&asker).insert(&db).await.unwrap(); | ||
| 350 | + let published = question(&other).insert(&db).await.unwrap(); | ||
| 351 | + PoolQuestion::approve(published.get_id(), &teacher, &db) | ||
| 352 | + .await | ||
| 353 | + .unwrap() | ||
| 354 | + .unwrap(); | ||
| 355 | + | ||
| 356 | + // The asker sees their own pending question plus the pool; a stranger | ||
| 357 | + // sees only the pool; the teacher view (list_all) sees everything. | ||
| 358 | + assert_eq!(PoolQuestion::list_visible_to(&asker, &db).await.unwrap().len(), 2); | ||
| 359 | + let stranger_view = PoolQuestion::list_visible_to(&other, &db).await.unwrap(); | ||
| 360 | + assert_eq!(stranger_view.len(), 1); | ||
| 361 | + assert_eq!(stranger_view[0].get_id(), published.get_id()); | ||
| 362 | + assert_eq!(PoolQuestion::list_all(&db).await.unwrap().len(), 2); | ||
| 363 | + assert!( | ||
| 364 | + PoolQuestion::read(pending.get_id(), &db) | ||
| 365 | + .await | ||
| 366 | + .unwrap() | ||
| 367 | + .is_some() | ||
| 368 | + ); | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | + #[tokio::test] | ||
| 372 | + async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { | ||
| 373 | + let db = database::init_mem().await.unwrap(); | ||
| 374 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 375 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 376 | + let png = FileContentType::try_new("image/png").unwrap(); | ||
| 377 | + | ||
| 378 | + let q = question(&asker).insert(&db).await.unwrap(); | ||
| 379 | + let before = PoolQuestion::set_image(q.get_id(), "blob_a", &png, 3, &db) | ||
| 380 | + .await | ||
| 381 | + .unwrap() | ||
| 382 | + .unwrap(); | ||
| 383 | + assert!(before.get_image_file().is_none()); | ||
| 384 | + | ||
| 385 | + // A replace reports the old blob for cleanup. | ||
| 386 | + let before = PoolQuestion::set_image(q.get_id(), "blob_b", &png, 5, &db) | ||
| 387 | + .await | ||
| 388 | + .unwrap() | ||
| 389 | + .unwrap(); | ||
| 390 | + assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 391 | + let stored = PoolQuestion::read(q.get_id(), &db).await.unwrap().unwrap(); | ||
| 392 | + assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 393 | + assert_eq!(stored.get_image_size(), Some(5)); | ||
| 394 | + | ||
| 395 | + // Clearing reports the detached blob and empties the fields. | ||
| 396 | + let before = PoolQuestion::clear_image(q.get_id(), &db) | ||
| 397 | + .await | ||
| 398 | + .unwrap() | ||
| 399 | + .unwrap(); | ||
| 400 | + assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 401 | + assert!( | ||
| 402 | + PoolQuestion::read(q.get_id(), &db) | ||
| 403 | + .await | ||
| 404 | + .unwrap() | ||
| 405 | + .unwrap() | ||
| 406 | + .get_image_file() | ||
| 407 | + .is_none() | ||
| 408 | + ); | ||
| 409 | + | ||
| 410 | + // Once approved, the image is frozen with the rest of the content. | ||
| 411 | + PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 412 | + .await | ||
| 413 | + .unwrap() | ||
| 414 | + .unwrap(); | ||
| 415 | + assert!( | ||
| 416 | + PoolQuestion::set_image(q.get_id(), "blob_c", &png, 7, &db) | ||
| 417 | + .await | ||
| 418 | + .unwrap() | ||
| 419 | + .is_none() | ||
| 420 | + ); | ||
| 421 | + assert!( | ||
| 422 | + PoolQuestion::clear_image(q.get_id(), &db) | ||
| 423 | + .await | ||
| 424 | + .unwrap() | ||
| 425 | + .is_none() | ||
| 426 | + ); | ||
| 427 | + } | ||
| 428 | + | ||
| 429 | + #[tokio::test] | ||
| 430 | + async fn delete_cascades_solutions_and_returns_the_row() { | ||
| 431 | + let db = database::init_mem().await.unwrap(); | ||
| 432 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 433 | + let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 434 | + | ||
| 435 | + let q = question(&asker).insert(&db).await.unwrap(); | ||
| 436 | + let offered = Solution::new( | ||
| 437 | + q.get_id(), | ||
| 438 | + &helper, | ||
| 439 | + SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), | ||
| 440 | + ) | ||
| 441 | + .insert(&db) | ||
| 442 | + .await | ||
| 443 | + .unwrap(); | ||
| 444 | + | ||
| 445 | + // The swept solutions ride back with the question so the caller can | ||
| 446 | + // take their image blobs off disk. | ||
| 447 | + let (removed, swept) = PoolQuestion::delete(q.get_id(), &db).await.unwrap().unwrap(); | ||
| 448 | + assert_eq!(removed.get_id(), q.get_id()); | ||
| 449 | + assert_eq!(swept.len(), 1); | ||
| 450 | + assert_eq!(swept[0].get_id(), offered.get_id()); | ||
| 451 | + assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none()); | ||
| 452 | + assert!(Solution::list_for(q.get_id(), &db).await.unwrap().is_empty()); | ||
| 453 | + | ||
| 454 | + // Deleting the already-deleted is None, not an error. | ||
| 455 | + assert!(PoolQuestion::delete(q.get_id(), &db).await.unwrap().is_none()); | ||
| 456 | + } | ||
| 457 | +} | ||
src/domain/solution.rsadded+442 -0
| @@ -0,0 +1,442 @@ | |||
| 1 | +//! A solution offered on an approved pool question (see | ||
| 2 | +//! [`crate::domain::pool_question`]). Anyone in the school — student or staff | ||
| 3 | +//! — may offer one; rows list oldest first, reading as a discussion thread. | ||
| 4 | +//! Solutions die with their question (the question delete cascades here). | ||
| 5 | +//! Like a question, a solution may carry one photo (`image_*` metadata on the | ||
| 6 | +//! row, bytes on disk under a server-generated ULID) — but unlike a question | ||
| 7 | +//! it has no moderation state, so its author may edit the body and swap the | ||
| 8 | +//! photo at any time; there is nothing to freeze. | ||
| 9 | + | ||
| 10 | +use std::collections::HashMap; | ||
| 11 | + | ||
| 12 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 13 | +use ulid::Ulid; | ||
| 14 | + | ||
| 15 | +use crate::constant::MAX_SOLUTION_BODY_LEN; | ||
| 16 | +use crate::database::{Database, SOLUTION_TABLE}; | ||
| 17 | +use crate::domain::note_file::FileContentType; | ||
| 18 | +use crate::domain::pool_question::PoolQuestionId; | ||
| 19 | +use crate::domain::timestamp::Timestamp; | ||
| 20 | +use crate::domain::user::UserId; | ||
| 21 | +use crate::error::{AppError, ValidationError}; | ||
| 22 | +use crate::validate::validate_required; | ||
| 23 | + | ||
| 24 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 25 | +pub struct SolutionId(RecordId); | ||
| 26 | + | ||
| 27 | +impl SolutionId { | ||
| 28 | + pub fn generate() -> Self { | ||
| 29 | + Self(RecordId::new(SOLUTION_TABLE, Ulid::new().to_string())) | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + pub fn from_key(key: &str) -> Self { | ||
| 33 | + Self(RecordId::new(SOLUTION_TABLE, key)) | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + pub fn record(&self) -> RecordId { | ||
| 37 | + self.0.clone() | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + pub fn key(&self) -> &str { | ||
| 41 | + match &self.0.key { | ||
| 42 | + RecordIdKey::String(key) => key, | ||
| 43 | + _ => "", | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 49 | +pub struct SolutionBody(String); | ||
| 50 | + | ||
| 51 | +impl SolutionBody { | ||
| 52 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 53 | + validate_required("body", value, MAX_SOLUTION_BODY_LEN)?; | ||
| 54 | + Ok(Self(value.to_string())) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub fn as_str(&self) -> &str { | ||
| 58 | + &self.0 | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 63 | +pub struct Solution { | ||
| 64 | + id: SolutionId, | ||
| 65 | + question: PoolQuestionId, | ||
| 66 | + author: UserId, | ||
| 67 | + body: SolutionBody, | ||
| 68 | + offered_at: Timestamp, | ||
| 69 | + /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | ||
| 70 | + /// the solution carries no image. | ||
| 71 | + image_file: Option<String>, | ||
| 72 | + image_content_type: Option<FileContentType>, | ||
| 73 | + image_size: Option<i64>, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// One `GROUP BY question` row of [`Solution::counts_for`]. | ||
| 77 | +#[derive(SurrealValue)] | ||
| 78 | +struct SolutionCount { | ||
| 79 | + question: PoolQuestionId, | ||
| 80 | + n: i64, | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +impl Solution { | ||
| 84 | + pub fn new(question: &PoolQuestionId, author: &UserId, body: SolutionBody) -> Self { | ||
| 85 | + Self { | ||
| 86 | + id: SolutionId::generate(), | ||
| 87 | + question: question.clone(), | ||
| 88 | + author: author.clone(), | ||
| 89 | + body, | ||
| 90 | + offered_at: Timestamp::now(), | ||
| 91 | + image_file: None, | ||
| 92 | + image_content_type: None, | ||
| 93 | + image_size: None, | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + pub fn get_id(&self) -> &SolutionId { | ||
| 98 | + &self.id | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + pub fn get_question(&self) -> &PoolQuestionId { | ||
| 102 | + &self.question | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + pub fn get_author(&self) -> &UserId { | ||
| 106 | + &self.author | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub fn get_body(&self) -> &SolutionBody { | ||
| 110 | + &self.body | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + pub fn get_offered_at(&self) -> Timestamp { | ||
| 114 | + self.offered_at | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + pub fn get_image_file(&self) -> Option<&str> { | ||
| 118 | + self.image_file.as_deref() | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + pub fn get_image_content_type(&self) -> Option<&FileContentType> { | ||
| 122 | + self.image_content_type.as_ref() | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + pub fn get_image_size(&self) -> Option<i64> { | ||
| 126 | + self.image_size | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { | ||
| 130 | + let created: Option<Solution> = db.create(self.id.record()).content(self).await?; | ||
| 131 | + created.ok_or_else(|| AppError::Internal("failed to create solution".into())) | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + /// Read a solution only if it belongs to `question` — keeps the nested | ||
| 135 | + /// route honest (a solution id under someone else's question 404s). | ||
| 136 | + pub async fn read_for( | ||
| 137 | + id: &SolutionId, | ||
| 138 | + question: &PoolQuestionId, | ||
| 139 | + db: &Database, | ||
| 140 | + ) -> Result<Option<Solution>, AppError> { | ||
| 141 | + let solution: Option<Solution> = db.select(id.record()).await?; | ||
| 142 | + Ok(solution.filter(|solution| &solution.question == question)) | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + /// The question's solutions, oldest first — a discussion reads downward. | ||
| 146 | + /// The id tiebreak keeps same-millisecond offers in a stable order (ULID | ||
| 147 | + /// keys sort chronologically). | ||
| 148 | + pub async fn list_for( | ||
| 149 | + question: &PoolQuestionId, | ||
| 150 | + db: &Database, | ||
| 151 | + ) -> Result<Vec<Solution>, AppError> { | ||
| 152 | + let mut result = db | ||
| 153 | + .query("SELECT * FROM solution WHERE question = $q ORDER BY offered_at ASC, id ASC") | ||
| 154 | + .bind(("q", question.record())) | ||
| 155 | + .await? | ||
| 156 | + .check()?; | ||
| 157 | + Ok(result.take::<Vec<Solution>>(0)?) | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + /// Per-question solution tallies for a page of questions, in one grouped | ||
| 161 | + /// query — a per-row `count()` would cost a query per question. Keys are | ||
| 162 | + /// question record keys; a question with no solutions has no entry, so | ||
| 163 | + /// the caller reads misses as zero. | ||
| 164 | + pub async fn counts_for( | ||
| 165 | + questions: &[PoolQuestionId], | ||
| 166 | + db: &Database, | ||
| 167 | + ) -> Result<HashMap<String, i64>, AppError> { | ||
| 168 | + if questions.is_empty() { | ||
| 169 | + return Ok(HashMap::new()); | ||
| 170 | + } | ||
| 171 | + let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect(); | ||
| 172 | + let mut result = db | ||
| 173 | + .query("SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question") | ||
| 174 | + .bind(("qs", ids)) | ||
| 175 | + .await? | ||
| 176 | + .check()?; | ||
| 177 | + Ok(result | ||
| 178 | + .take::<Vec<SolutionCount>>(0)? | ||
| 179 | + .into_iter() | ||
| 180 | + .map(|row| (row.question.key().to_string(), row.n)) | ||
| 181 | + .collect()) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// Replace the body. Unconditional (solutions have no moderation state to | ||
| 185 | + /// guard, unlike a question's `pending` gate) — `None` only means the row | ||
| 186 | + /// was deleted mid-flight. Authorship is the web layer's check. | ||
| 187 | + pub async fn set_body( | ||
| 188 | + id: &SolutionId, | ||
| 189 | + body: &SolutionBody, | ||
| 190 | + db: &Database, | ||
| 191 | + ) -> Result<Option<Solution>, AppError> { | ||
| 192 | + let mut result = db | ||
| 193 | + .query("UPDATE $s SET body = $b RETURN AFTER") | ||
| 194 | + .bind(("s", id.record())) | ||
| 195 | + .bind(("b", body.clone())) | ||
| 196 | + .await? | ||
| 197 | + .check()?; | ||
| 198 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /// Point the solution at a freshly written image blob. Unconditional for | ||
| 202 | + /// the same reason as [`Self::set_body`]. Returns the *before* row — its | ||
| 203 | + /// `image_file` is the replaced blob the caller must remove; `None` means | ||
| 204 | + /// the row was deleted mid-flight (the fresh blob is the caller's orphan | ||
| 205 | + /// to take back off disk). | ||
| 206 | + pub async fn set_image( | ||
| 207 | + id: &SolutionId, | ||
| 208 | + file: &str, | ||
| 209 | + content_type: &FileContentType, | ||
| 210 | + size: i64, | ||
| 211 | + db: &Database, | ||
| 212 | + ) -> Result<Option<Solution>, AppError> { | ||
| 213 | + let mut result = db | ||
| 214 | + .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") | ||
| 215 | + .bind(("s", id.record())) | ||
| 216 | + .bind(("file", file.to_string())) | ||
| 217 | + .bind(("ct", content_type.clone())) | ||
| 218 | + .bind(("size", size)) | ||
| 219 | + .await? | ||
| 220 | + .check()?; | ||
| 221 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + /// Detach the solution's image. Returns the *before* row — its | ||
| 225 | + /// `image_file` is the blob the caller must remove. | ||
| 226 | + pub async fn clear_image( | ||
| 227 | + id: &SolutionId, | ||
| 228 | + db: &Database, | ||
| 229 | + ) -> Result<Option<Solution>, AppError> { | ||
| 230 | + let mut result = db | ||
| 231 | + .query( | ||
| 232 | + "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 233 | + RETURN BEFORE", | ||
| 234 | + ) | ||
| 235 | + .bind(("s", id.record())) | ||
| 236 | + .await? | ||
| 237 | + .check()?; | ||
| 238 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + pub async fn delete(self, db: &Database) -> Result<Solution, AppError> { | ||
| 242 | + let deleted: Option<Solution> = db.delete(self.id.record()).await?; | ||
| 243 | + deleted.ok_or(AppError::NotFound) | ||
| 244 | + } | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +#[cfg(test)] | ||
| 248 | +mod tests { | ||
| 249 | + use super::*; | ||
| 250 | + | ||
| 251 | + #[tokio::test] | ||
| 252 | + async fn rows_scope_to_their_question_and_list_oldest_first() { | ||
| 253 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 254 | + let question_a = PoolQuestionId::generate(); | ||
| 255 | + let question_b = PoolQuestionId::generate(); | ||
| 256 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 257 | + | ||
| 258 | + let first = Solution::new( | ||
| 259 | + &question_a, | ||
| 260 | + &author, | ||
| 261 | + SolutionBody::try_new("Önce türevi al.").unwrap(), | ||
| 262 | + ) | ||
| 263 | + .insert(&db) | ||
| 264 | + .await | ||
| 265 | + .unwrap(); | ||
| 266 | + let second = Solution::new( | ||
| 267 | + &question_a, | ||
| 268 | + &author, | ||
| 269 | + SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), | ||
| 270 | + ) | ||
| 271 | + .insert(&db) | ||
| 272 | + .await | ||
| 273 | + .unwrap(); | ||
| 274 | + | ||
| 275 | + let listed = Solution::list_for(&question_a, &db).await.unwrap(); | ||
| 276 | + assert_eq!(listed.len(), 2); | ||
| 277 | + assert_eq!(listed[0].get_id(), first.get_id()); | ||
| 278 | + assert_eq!(listed[1].get_id(), second.get_id()); | ||
| 279 | + assert!(Solution::list_for(&question_b, &db).await.unwrap().is_empty()); | ||
| 280 | + | ||
| 281 | + // Readable under its own question, invisible under another. | ||
| 282 | + assert!( | ||
| 283 | + Solution::read_for(first.get_id(), &question_a, &db) | ||
| 284 | + .await | ||
| 285 | + .unwrap() | ||
| 286 | + .is_some() | ||
| 287 | + ); | ||
| 288 | + assert!( | ||
| 289 | + Solution::read_for(first.get_id(), &question_b, &db) | ||
| 290 | + .await | ||
| 291 | + .unwrap() | ||
| 292 | + .is_none() | ||
| 293 | + ); | ||
| 294 | + | ||
| 295 | + first.delete(&db).await.unwrap(); | ||
| 296 | + assert_eq!(Solution::list_for(&question_a, &db).await.unwrap().len(), 1); | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + #[tokio::test] | ||
| 300 | + async fn image_set_replace_clear_report_the_replaced_blob() { | ||
| 301 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 302 | + let question = PoolQuestionId::generate(); | ||
| 303 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 304 | + let png = FileContentType::try_new("image/png").unwrap(); | ||
| 305 | + | ||
| 306 | + let solution = Solution::new( | ||
| 307 | + &question, | ||
| 308 | + &author, | ||
| 309 | + SolutionBody::try_new("Grafiği çiz.").unwrap(), | ||
| 310 | + ) | ||
| 311 | + .insert(&db) | ||
| 312 | + .await | ||
| 313 | + .unwrap(); | ||
| 314 | + | ||
| 315 | + let before = Solution::set_image(solution.get_id(), "blob_a", &png, 3, &db) | ||
| 316 | + .await | ||
| 317 | + .unwrap() | ||
| 318 | + .unwrap(); | ||
| 319 | + assert!(before.get_image_file().is_none()); | ||
| 320 | + | ||
| 321 | + // A replace reports the old blob for cleanup. | ||
| 322 | + let before = Solution::set_image(solution.get_id(), "blob_b", &png, 5, &db) | ||
| 323 | + .await | ||
| 324 | + .unwrap() | ||
| 325 | + .unwrap(); | ||
| 326 | + assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 327 | + let stored = Solution::read_for(solution.get_id(), &question, &db) | ||
| 328 | + .await | ||
| 329 | + .unwrap() | ||
| 330 | + .unwrap(); | ||
| 331 | + assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 332 | + assert_eq!(stored.get_image_size(), Some(5)); | ||
| 333 | + | ||
| 334 | + // Clearing reports the detached blob and empties the fields. | ||
| 335 | + let before = Solution::clear_image(solution.get_id(), &db) | ||
| 336 | + .await | ||
| 337 | + .unwrap() | ||
| 338 | + .unwrap(); | ||
| 339 | + assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 340 | + assert!( | ||
| 341 | + Solution::read_for(solution.get_id(), &question, &db) | ||
| 342 | + .await | ||
| 343 | + .unwrap() | ||
| 344 | + .unwrap() | ||
| 345 | + .get_image_file() | ||
| 346 | + .is_none() | ||
| 347 | + ); | ||
| 348 | + | ||
| 349 | + // A row deleted mid-flight surfaces as None, not an error. | ||
| 350 | + solution.clone().delete(&db).await.unwrap(); | ||
| 351 | + assert!( | ||
| 352 | + Solution::set_image(solution.get_id(), "blob_c", &png, 7, &db) | ||
| 353 | + .await | ||
| 354 | + .unwrap() | ||
| 355 | + .is_none() | ||
| 356 | + ); | ||
| 357 | + assert!( | ||
| 358 | + Solution::clear_image(solution.get_id(), &db) | ||
| 359 | + .await | ||
| 360 | + .unwrap() | ||
| 361 | + .is_none() | ||
| 362 | + ); | ||
| 363 | + } | ||
| 364 | + | ||
| 365 | + #[tokio::test] | ||
| 366 | + async fn set_body_edits_in_place() { | ||
| 367 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 368 | + let question = PoolQuestionId::generate(); | ||
| 369 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 370 | + | ||
| 371 | + let solution = Solution::new( | ||
| 372 | + &question, | ||
| 373 | + &author, | ||
| 374 | + SolutionBody::try_new("İlk deneme.").unwrap(), | ||
| 375 | + ) | ||
| 376 | + .insert(&db) | ||
| 377 | + .await | ||
| 378 | + .unwrap(); | ||
| 379 | + | ||
| 380 | + let edited = Solution::set_body( | ||
| 381 | + solution.get_id(), | ||
| 382 | + &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), | ||
| 383 | + &db, | ||
| 384 | + ) | ||
| 385 | + .await | ||
| 386 | + .unwrap() | ||
| 387 | + .unwrap(); | ||
| 388 | + assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); | ||
| 389 | + assert_eq!(edited.get_id(), solution.get_id()); | ||
| 390 | + | ||
| 391 | + // Editing a missing solution is None, not an error. | ||
| 392 | + assert!( | ||
| 393 | + Solution::set_body( | ||
| 394 | + &SolutionId::generate(), | ||
| 395 | + &SolutionBody::try_new("boş").unwrap(), | ||
| 396 | + &db, | ||
| 397 | + ) | ||
| 398 | + .await | ||
| 399 | + .unwrap() | ||
| 400 | + .is_none() | ||
| 401 | + ); | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + #[tokio::test] | ||
| 405 | + async fn counts_for_groups_per_question() { | ||
| 406 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 407 | + let two = PoolQuestionId::generate(); | ||
| 408 | + let one = PoolQuestionId::generate(); | ||
| 409 | + let none = PoolQuestionId::generate(); | ||
| 410 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 411 | + | ||
| 412 | + for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { | ||
| 413 | + for body in bodies { | ||
| 414 | + Solution::new(question, &author, SolutionBody::try_new(body).unwrap()) | ||
| 415 | + .insert(&db) | ||
| 416 | + .await | ||
| 417 | + .unwrap(); | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | + | ||
| 421 | + let counts = | ||
| 422 | + Solution::counts_for(&[two.clone(), one.clone(), none.clone()], &db) | ||
| 423 | + .await | ||
| 424 | + .unwrap(); | ||
| 425 | + assert_eq!(counts.get(two.key()), Some(&2)); | ||
| 426 | + assert_eq!(counts.get(one.key()), Some(&1)); | ||
| 427 | + // No solutions = no entry; the caller reads the miss as zero. | ||
| 428 | + assert_eq!(counts.get(none.key()), None); | ||
| 429 | + assert!(Solution::counts_for(&[], &db).await.unwrap().is_empty()); | ||
| 430 | + } | ||
| 431 | + | ||
| 432 | + #[tokio::test] | ||
| 433 | + async fn body_rules() { | ||
| 434 | + assert!(SolutionBody::try_new("").is_err()); | ||
| 435 | + assert!(SolutionBody::try_new(" ").is_err()); | ||
| 436 | + assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err()); | ||
| 437 | + assert_eq!( | ||
| 438 | + SolutionBody::try_new("Kısmi integrasyon.").unwrap().as_str(), | ||
| 439 | + "Kısmi integrasyon." | ||
| 440 | + ); | ||
| 441 | + } | ||
| 442 | +} | ||
src/lib.rsmodified+3 -1
| @@ -32,7 +32,7 @@ use crate::state::AppState; | |||
| 32 | info( | 32 | info( |
| 33 | title = "Hezarfen Backend API", | 33 | title = "Hezarfen Backend API", |
| 34 | version = env!("CARGO_PKG_VERSION"), | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - 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). 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.", | 35 | + 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.", |
| 36 | ), | 36 | ), |
| 37 | modifiers(&SecurityAddon), | 37 | modifiers(&SecurityAddon), |
| 38 | tags( | 38 | tags( |
| @@ -46,6 +46,7 @@ use crate::state::AppState; | |||
| 46 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), | 46 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| 47 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | 47 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 48 | (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"), | 48 | (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"), |
| 49 | + (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), | ||
| 49 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 50 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 50 | (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"), | 51 | (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"), |
| 51 | (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"), | 52 | (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"), |
| @@ -91,6 +92,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 91 | .nest("/marks", web::marks::routes()) | 92 | .nest("/marks", web::marks::routes()) |
| 92 | .nest("/work", web::work::routes()) | 93 | .nest("/work", web::work::routes()) |
| 93 | .nest("/pomodoro", web::pomodoro::routes()) | 94 | .nest("/pomodoro", web::pomodoro::routes()) |
| 95 | + .nest("/questions", web::questions::routes()) | ||
| 94 | .nest("/attendance", web::attendance::routes()) | 96 | .nest("/attendance", web::attendance::routes()) |
| 95 | .nest("/settings", web::settings::routes()) | 97 | .nest("/settings", web::settings::routes()) |
| 96 | .nest("/subjects", web::subjects::routes()) | 98 | .nest("/subjects", web::subjects::routes()) |
src/web/exams.rsmodified+7 -43
| @@ -3,10 +3,9 @@ use std::time::Duration; | |||
| 3 | 3 | ||
| 4 | use axum::Json; | 4 | use axum::Json; |
| 5 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | 5 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| 6 | -use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; | 6 | +use axum::http::StatusCode; |
| 7 | -use axum::http::{HeaderValue, StatusCode}; | 7 | +use axum::response::Response; |
| 8 | use axum::response::sse::{Event, KeepAlive, Sse}; | 8 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 9 | -use axum::response::{IntoResponse, Response}; | ||
| 10 | use serde::{Deserialize, Serialize}; | 9 | use serde::{Deserialize, Serialize}; |
| 11 | use tokio_stream::wrappers::IntervalStream; | 10 | use tokio_stream::wrappers::IntervalStream; |
| 12 | use tokio_stream::{Stream, StreamExt}; | 11 | use tokio_stream::{Stream, StreamExt}; |
| @@ -15,8 +14,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 15 | use utoipa_axum::routes; | 14 | use utoipa_axum::routes; |
| 16 | 15 | ||
| 17 | use crate::constant::{ | 16 | use crate::constant::{ |
| 18 | - EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, QUESTION_IMAGE_CONTENT_TYPES, | 17 | + EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES, |
| 19 | - UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 20 | }; | 18 | }; |
| 21 | use crate::database::Database; | 19 | use crate::database::Database; |
| 22 | use crate::domain::course::Course; | 20 | use crate::domain::course::Course; |
| @@ -44,7 +42,8 @@ use super::courses::{can_manage_course, can_view_course, visible_courses}; | |||
| 44 | use super::subjects::subject_in_course; | 42 | use super::subjects::subject_in_course; |
| 45 | use super::{ | 43 | use super::{ |
| 46 | CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm, | 44 | CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm, |
| 47 | - blob_path, check_not_past, paginate, person_map, read_upload, remove_blob, set_or_clear, | 45 | + blob_path, check_not_past, image_content_type, paginate, person_map, read_upload, remove_blob, |
| 46 | + set_or_clear, | ||
| 48 | }; | 47 | }; |
| 49 | 48 | ||
| 50 | /// Serializes the exam subsystem's cross-record check-then-writes, which | 49 | /// Serializes the exam subsystem's cross-record check-then-writes, which |
| @@ -1779,19 +1778,6 @@ async fn ensure_question_content_visible( | |||
| 1779 | Ok(()) | 1778 | Ok(()) |
| 1780 | } | 1779 | } |
| 1781 | 1780 | ||
| 1782 | -/// The declared content type, held to the raster allowlist — SVG stays out | ||
| 1783 | -/// (it can script) since these bytes are rendered inline to whole classes. | ||
| 1784 | -fn image_content_type(raw: &str) -> Result<FileContentType, AppError> { | ||
| 1785 | - let content_type = FileContentType::try_new(raw)?; | ||
| 1786 | - if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) { | ||
| 1787 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 1788 | - field: "content_type", | ||
| 1789 | - reason: "must be image/png, image/jpeg, image/webp, or image/gif", | ||
| 1790 | - })); | ||
| 1791 | - } | ||
| 1792 | - Ok(content_type) | ||
| 1793 | -} | ||
| 1794 | - | ||
| 1795 | /// The whole image write tail, shared by both upload endpoints: new blob to | 1781 | /// The whole image write tail, shared by both upload endpoints: new blob to |
| 1796 | /// disk, row UPSERT (the deterministic per-slot id makes it a replace), then | 1782 | /// disk, row UPSERT (the deterministic per-slot id makes it a replace), then |
| 1797 | /// the replaced blob off disk. A failed row write takes the fresh blob back | 1783 | /// the replaced blob off disk. A failed row write takes the fresh blob back |
| @@ -1830,31 +1816,9 @@ async fn store_image( | |||
| 1830 | } | 1816 | } |
| 1831 | } | 1817 | } |
| 1832 | 1818 | ||
| 1833 | -/// The stored bytes as an inline-displayable response: the declared (and | 1819 | +/// The stored bytes, served inline via [`super::serve_inline_blob`]. |
| 1834 | -/// allowlisted) content type, `nosniff`, and `no-store` — exam content has no | ||
| 1835 | -/// business in shared caches, and a replaced image must not linger. | ||
| 1836 | async fn serve_image(st: &AppState, image: &QuestionImage) -> Result<Response, AppError> { | 1820 | async fn serve_image(st: &AppState, image: &QuestionImage) -> Result<Response, AppError> { |
| 1837 | - let bytes = tokio::fs::read(blob_path(&st.files_path, image.get_file())) | 1821 | + super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
| 1838 | - .await | ||
| 1839 | - .map_err(|err| { | ||
| 1840 | - // The row exists but its blob doesn't — server-side damage (a | ||
| 1841 | - // lost volume path), not a client 404. | ||
| 1842 | - AppError::Internal(format!( | ||
| 1843 | - "missing blob for question image {}: {err}", | ||
| 1844 | - image.get_file() | ||
| 1845 | - )) | ||
| 1846 | - })?; | ||
| 1847 | - let content_type = HeaderValue::from_str(image.get_content_type().as_str()) | ||
| 1848 | - .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); | ||
| 1849 | - Ok(( | ||
| 1850 | - [ | ||
| 1851 | - (CONTENT_TYPE, content_type), | ||
| 1852 | - (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), | ||
| 1853 | - (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), | ||
| 1854 | - ], | ||
| 1855 | - bytes, | ||
| 1856 | - ) | ||
| 1857 | - .into_response()) | ||
| 1858 | } | 1822 | } |
| 1859 | 1823 | ||
| 1860 | /// Attach (or replace) a question's illustration — any question kind may | 1824 | /// Attach (or replace) a question's illustration — any question kind may |
src/web/mod.rsmodified+48 -2
| @@ -13,6 +13,7 @@ pub mod marks; | |||
| 13 | pub mod messages; | 13 | pub mod messages; |
| 14 | pub mod notes; | 14 | pub mod notes; |
| 15 | pub mod pomodoro; | 15 | pub mod pomodoro; |
| 16 | +pub mod questions; | ||
| 16 | pub mod sessions; | 17 | pub mod sessions; |
| 17 | pub mod settings; | 18 | pub mod settings; |
| 18 | pub mod subjects; | 19 | pub mod subjects; |
| @@ -35,12 +36,15 @@ use std::path::{Path as FsPath, PathBuf}; | |||
| 35 | 36 | ||
| 36 | use axum::extract::Multipart; | 37 | use axum::extract::Multipart; |
| 37 | use axum::extract::multipart::MultipartError; | 38 | use axum::extract::multipart::MultipartError; |
| 38 | -use axum::http::StatusCode; | 39 | +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; |
| 40 | +use axum::http::{HeaderValue, StatusCode}; | ||
| 41 | +use axum::response::{IntoResponse, Response}; | ||
| 39 | use serde::{Deserialize, Deserializer}; | 42 | use serde::{Deserialize, Deserializer}; |
| 40 | use utoipa::ToSchema; | 43 | use utoipa::ToSchema; |
| 41 | 44 | ||
| 42 | -use crate::constant::SCHEDULE_PAST_GRACE_MS; | 45 | +use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS}; |
| 43 | use crate::database::Database; | 46 | use crate::database::Database; |
| 47 | +use crate::domain::note_file::FileContentType; | ||
| 44 | use crate::domain::parent_link::ParentLink; | 48 | use crate::domain::parent_link::ParentLink; |
| 45 | use crate::domain::role::Role; | 49 | use crate::domain::role::Role; |
| 46 | use crate::domain::timestamp::Timestamp; | 50 | use crate::domain::timestamp::Timestamp; |
| @@ -140,6 +144,48 @@ pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { | |||
| 140 | } | 144 | } |
| 141 | } | 145 | } |
| 142 | 146 | ||
| 147 | +/// The declared content type of an inline-displayed image upload, held to the | ||
| 148 | +/// raster allowlist — SVG stays out (it can script) since these bytes are | ||
| 149 | +/// rendered inline to whole classes. Shared by exam question images and pool | ||
| 150 | +/// question photos. | ||
| 151 | +pub(crate) fn image_content_type(raw: &str) -> Result<FileContentType, AppError> { | ||
| 152 | + let content_type = FileContentType::try_new(raw)?; | ||
| 153 | + if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) { | ||
| 154 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 155 | + field: "content_type", | ||
| 156 | + reason: "must be image/png, image/jpeg, image/webp, or image/gif", | ||
| 157 | + })); | ||
| 158 | + } | ||
| 159 | + Ok(content_type) | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// A stored blob as an inline-displayable response: the declared (and | ||
| 163 | +/// allowlisted) content type, `nosniff`, and `no-store` — moderated/exam | ||
| 164 | +/// content has no business in shared caches, and a replaced image must not | ||
| 165 | +/// linger. | ||
| 166 | +pub(crate) async fn serve_inline_blob( | ||
| 167 | + files_path: &FsPath, | ||
| 168 | + file: &str, | ||
| 169 | + content_type: &FileContentType, | ||
| 170 | +) -> 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 | + })?; | ||
| 176 | + let content_type = HeaderValue::from_str(content_type.as_str()) | ||
| 177 | + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); | ||
| 178 | + Ok(( | ||
| 179 | + [ | ||
| 180 | + (CONTENT_TYPE, content_type), | ||
| 181 | + (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), | ||
| 182 | + (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), | ||
| 183 | + ], | ||
| 184 | + bytes, | ||
| 185 | + ) | ||
| 186 | + .into_response()) | ||
| 187 | +} | ||
| 188 | + | ||
| 143 | /// Multipart read failures: the route-level body cap maps to 413 like the | 189 | /// Multipart read failures: the route-level body cap maps to 413 like the |
| 144 | /// school-limit check; anything else is a malformed body. | 190 | /// school-limit check; anything else is a malformed body. |
| 145 | pub(crate) fn multipart_error(err: MultipartError) -> AppError { | 191 | pub(crate) fn multipart_error(err: MultipartError) -> AppError { |
src/web/questions.rsadded+920 -0
| @@ -0,0 +1,920 @@ | |||
| 1 | +//! The school question pool: students ask (optionally with a photo of the | ||
| 2 | +//! problem), teacher+ approve, and every approved question is readable — and | ||
| 3 | +//! answerable — by the whole school. Parents stay out (they observe reports, | ||
| 4 | +//! they don't take part). Pending questions are visible only to their asker | ||
| 5 | +//! and to teacher+ (the approval queue); approval freezes the content, so the | ||
| 6 | +//! only edit ever needed post-approval is deletion — which is also how a | ||
| 7 | +//! teacher rejects: there is no "rejected" state to manage. Solutions are the | ||
| 8 | +//! opposite: unmoderated, so their author may edit the body and attach, | ||
| 9 | +//! replace, or drop one photo at any time — moderation there is delete-only. | ||
| 10 | + | ||
| 11 | +use axum::Json; | ||
| 12 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | ||
| 13 | +use axum::http::StatusCode; | ||
| 14 | +use axum::response::Response; | ||
| 15 | +use serde::{Deserialize, Serialize}; | ||
| 16 | +use utoipa::{IntoParams, ToSchema}; | ||
| 17 | +use utoipa_axum::router::OpenApiRouter; | ||
| 18 | +use utoipa_axum::routes; | ||
| 19 | + | ||
| 20 | +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | ||
| 21 | +use crate::domain::pool_question::{ | ||
| 22 | + POOL_QUESTION_STATUSES, PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, | ||
| 23 | +}; | ||
| 24 | +use crate::domain::role::Role; | ||
| 25 | +use crate::domain::settings::Settings; | ||
| 26 | +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | ||
| 27 | +use crate::domain::user::User; | ||
| 28 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 29 | +use crate::state::AppState; | ||
| 30 | + | ||
| 31 | +use super::{ | ||
| 32 | + CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, | ||
| 33 | + blob_path, image_content_type, paginate, person_map, read_upload, remove_blob, | ||
| 34 | + serve_inline_blob, | ||
| 35 | +}; | ||
| 36 | + | ||
| 37 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 38 | + OpenApiRouter::new() | ||
| 39 | + .routes(routes!(ask_question, list_questions)) | ||
| 40 | + .routes(routes!(get_question, delete_question)) | ||
| 41 | + .routes(routes!(approve_question)) | ||
| 42 | + .routes(routes!(offer_solution, list_solutions)) | ||
| 43 | + .routes(routes!(delete_solution, edit_solution)) | ||
| 44 | + // The image routes get their own HTTP body cap, like the note-file | ||
| 45 | + // ones: the server-wide hard ceiling plus multipart framing headroom. | ||
| 46 | + .merge( | ||
| 47 | + OpenApiRouter::new() | ||
| 48 | + .routes(routes!(upload_image, get_image, delete_image)) | ||
| 49 | + .routes(routes!( | ||
| 50 | + upload_solution_image, | ||
| 51 | + get_solution_image, | ||
| 52 | + delete_solution_image | ||
| 53 | + )) | ||
| 54 | + .layer(DefaultBodyLimit::max( | ||
| 55 | + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 56 | + )), | ||
| 57 | + ) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// A 404 unless `user` may see `question`: approved questions are | ||
| 61 | +/// school-wide; a pending one exists only for its asker and for teacher+ | ||
| 62 | +/// (the approval queue) — everyone else must not even learn it exists. | ||
| 63 | +fn ensure_visible(question: &PoolQuestion, user: &User) -> Result<(), AppError> { | ||
| 64 | + if question.is_approved() | ||
| 65 | + || user.get_role().at_least(Role::Teacher) | ||
| 66 | + || question.get_asker() == user.get_id() | ||
| 67 | + { | ||
| 68 | + return Ok(()); | ||
| 69 | + } | ||
| 70 | + Err(AppError::NotFound) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// The shared front half of the asker-only, pending-only writes (image | ||
| 74 | +/// upload/removal): 404 invisible, 403 not the asker, 409 already approved. | ||
| 75 | +fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), AppError> { | ||
| 76 | + ensure_visible(question, user)?; | ||
| 77 | + if question.get_asker() != user.get_id() { | ||
| 78 | + return Err(AppError::Forbidden( | ||
| 79 | + "only the asker may change the question's image", | ||
| 80 | + )); | ||
| 81 | + } | ||
| 82 | + if question.is_approved() { | ||
| 83 | + return Err(AppError::Conflict( | ||
| 84 | + "the question is approved — its content is frozen", | ||
| 85 | + )); | ||
| 86 | + } | ||
| 87 | + Ok(()) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppError> { | ||
| 91 | + PoolQuestion::read(&PoolQuestionId::from_key(id), &st.db) | ||
| 92 | + .await? | ||
| 93 | + .ok_or(AppError::NotFound) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +#[derive(Deserialize, ToSchema)] | ||
| 97 | +struct AskQuestion { | ||
| 98 | + #[schema(example = "Bu integrali çözemedim")] | ||
| 99 | + title: String, | ||
| 100 | + #[schema(example = "∫x·eˣ dx nasıl adım adım çözülür?")] | ||
| 101 | + body: String, | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +#[derive(Deserialize, ToSchema)] | ||
| 105 | +struct OfferSolution { | ||
| 106 | + #[schema(example = "Kısmi integrasyon: u = x, dv = eˣ dx …")] | ||
| 107 | + body: String, | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +#[derive(Deserialize, IntoParams)] | ||
| 111 | +struct PoolQuestionFilter { | ||
| 112 | + /// Narrow to one status: `pending` (for a student: own unapproved | ||
| 113 | + /// questions; for teacher+: the approval queue) or `approved` (the pool). | ||
| 114 | + /// Omit for both. | ||
| 115 | + #[param(example = "pending")] | ||
| 116 | + status: Option<String>, | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// A stored pool photo's metadata — a question's or a solution's; the bytes | ||
| 120 | +/// come from `GET /questions/{id}/image` or | ||
| 121 | +/// `GET /questions/{id}/solutions/{sid}/image`. | ||
| 122 | +#[derive(Serialize, ToSchema)] | ||
| 123 | +struct PoolImageMeta { | ||
| 124 | + #[schema(example = "image/jpeg")] | ||
| 125 | + content_type: String, | ||
| 126 | + /// Byte size of the stored image. | ||
| 127 | + #[schema(example = 204_800)] | ||
| 128 | + size: i64, | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// A pool question. `status` is `pending` (awaiting approval — visible only | ||
| 132 | +/// to the asker and teacher+) or `approved` (in the school-wide pool). | ||
| 133 | +#[derive(Serialize, ToSchema)] | ||
| 134 | +struct PoolQuestionResponse { | ||
| 135 | + id: String, | ||
| 136 | + /// The student who asked. | ||
| 137 | + asker: PersonRef, | ||
| 138 | + title: String, | ||
| 139 | + body: String, | ||
| 140 | + #[schema(example = "approved")] | ||
| 141 | + status: String, | ||
| 142 | + /// When it was asked, UTC unix-milliseconds (server-stamped). | ||
| 143 | + asked_at: i64, | ||
| 144 | + /// Who approved it; `null` while pending. | ||
| 145 | + approved_by: Option<PersonRef>, | ||
| 146 | + /// The attached photo's metadata; `null` when there is none. Bytes at | ||
| 147 | + /// `GET /questions/{id}/image`. | ||
| 148 | + image: Option<PoolImageMeta>, | ||
| 149 | + /// How many solutions the question carries — so a list can show activity | ||
| 150 | + /// without a per-question round trip. | ||
| 151 | + solution_count: i64, | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +impl PoolQuestionResponse { | ||
| 155 | + fn new( | ||
| 156 | + question: &PoolQuestion, | ||
| 157 | + people: &std::collections::HashMap<String, PersonRef>, | ||
| 158 | + solution_count: i64, | ||
| 159 | + ) -> Self { | ||
| 160 | + Self { | ||
| 161 | + id: question.get_id().key().to_string(), | ||
| 162 | + asker: PersonRef::resolve(people, question.get_asker()), | ||
| 163 | + title: question.get_title().as_str().to_string(), | ||
| 164 | + body: question.get_body().as_str().to_string(), | ||
| 165 | + status: question.get_status().to_string(), | ||
| 166 | + asked_at: question.get_asked_at().as_millis(), | ||
| 167 | + approved_by: question | ||
| 168 | + .get_approved_by() | ||
| 169 | + .map(|approver| PersonRef::resolve(people, approver)), | ||
| 170 | + image: question.get_image_content_type().map(|content_type| { | ||
| 171 | + PoolImageMeta { | ||
| 172 | + content_type: content_type.as_str().to_string(), | ||
| 173 | + size: question.get_image_size().unwrap_or(0), | ||
| 174 | + } | ||
| 175 | + }), | ||
| 176 | + solution_count, | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// One offered solution on a pool question. | ||
| 182 | +#[derive(Serialize, ToSchema)] | ||
| 183 | +struct SolutionResponse { | ||
| 184 | + id: String, | ||
| 185 | + /// The question this solution answers. | ||
| 186 | + question: String, | ||
| 187 | + /// Who offered it — any role, student to admin. | ||
| 188 | + author: PersonRef, | ||
| 189 | + body: String, | ||
| 190 | + /// When it was offered, UTC unix-milliseconds (server-stamped). | ||
| 191 | + offered_at: i64, | ||
| 192 | + /// The attached photo's metadata; `null` when there is none. Bytes at | ||
| 193 | + /// `GET /questions/{id}/solutions/{sid}/image`. | ||
| 194 | + image: Option<PoolImageMeta>, | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +impl SolutionResponse { | ||
| 198 | + fn new(solution: &Solution, people: &std::collections::HashMap<String, PersonRef>) -> Self { | ||
| 199 | + Self { | ||
| 200 | + id: solution.get_id().key().to_string(), | ||
| 201 | + question: solution.get_question().key().to_string(), | ||
| 202 | + author: PersonRef::resolve(people, solution.get_author()), | ||
| 203 | + body: solution.get_body().as_str().to_string(), | ||
| 204 | + offered_at: solution.get_offered_at().as_millis(), | ||
| 205 | + image: solution.get_image_content_type().map(|content_type| { | ||
| 206 | + PoolImageMeta { | ||
| 207 | + content_type: content_type.as_str().to_string(), | ||
| 208 | + size: solution.get_image_size().unwrap_or(0), | ||
| 209 | + } | ||
| 210 | + }), | ||
| 211 | + } | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Join the askers, approvers, and solution tallies of a page of questions | ||
| 216 | +/// into responses — both joins run over the page slice only, so a long pool | ||
| 217 | +/// history never widens the queries. | ||
| 218 | +async fn question_responses( | ||
| 219 | + questions: &[PoolQuestion], | ||
| 220 | + st: &AppState, | ||
| 221 | +) -> Result<Vec<PoolQuestionResponse>, AppError> { | ||
| 222 | + let ids = questions.iter().flat_map(|question| { | ||
| 223 | + std::iter::once(question.get_asker().clone()) | ||
| 224 | + .chain(question.get_approved_by().cloned()) | ||
| 225 | + }); | ||
| 226 | + let people = person_map(ids, &st.db).await?; | ||
| 227 | + let question_ids: Vec<PoolQuestionId> = questions | ||
| 228 | + .iter() | ||
| 229 | + .map(|question| question.get_id().clone()) | ||
| 230 | + .collect(); | ||
| 231 | + let counts = Solution::counts_for(&question_ids, &st.db).await?; | ||
| 232 | + Ok(questions | ||
| 233 | + .iter() | ||
| 234 | + .map(|question| { | ||
| 235 | + let count = counts.get(question.get_id().key()).copied().unwrap_or(0); | ||
| 236 | + PoolQuestionResponse::new(question, &people, count) | ||
| 237 | + }) | ||
| 238 | + .collect()) | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +/// Ask a question. Students only — the pool exists for students to get help; | ||
| 242 | +/// staff answer, they don't ask. Born `pending`: invisible to the school | ||
| 243 | +/// until a teacher+ approves it, so nothing unmoderated ever reaches the | ||
| 244 | +/// pool. Attach a photo of the problem afterwards via | ||
| 245 | +/// `POST /questions/{id}/image` (only while pending). | ||
| 246 | +#[utoipa::path( | ||
| 247 | + post, | ||
| 248 | + path = "/", | ||
| 249 | + tag = "questions", | ||
| 250 | + security(("session_cookie" = [])), | ||
| 251 | + request_body = AskQuestion, | ||
| 252 | + responses( | ||
| 253 | + (status = 201, description = "Question created, pending approval", body = PoolQuestionResponse), | ||
| 254 | + (status = 400, description = "Invalid title or body", body = ErrorResponse), | ||
| 255 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 256 | + (status = 403, description = "Requires the student role", body = ErrorResponse), | ||
| 257 | + ), | ||
| 258 | +)] | ||
| 259 | +async fn ask_question( | ||
| 260 | + State(st): State<AppState>, | ||
| 261 | + CurrentUser(user): CurrentUser, | ||
| 262 | + Json(req): Json<AskQuestion>, | ||
| 263 | +) -> Result<(StatusCode, Json<PoolQuestionResponse>), AppError> { | ||
| 264 | + if user.get_role() != Role::Student { | ||
| 265 | + return Err(AppError::Forbidden("only students ask pool questions")); | ||
| 266 | + } | ||
| 267 | + let title = PoolQuestionTitle::try_new(&req.title)?; | ||
| 268 | + let body = PoolQuestionBody::try_new(&req.body)?; | ||
| 269 | + let question = PoolQuestion::new(user.get_id(), title, body) | ||
| 270 | + .insert(&st.db) | ||
| 271 | + .await?; | ||
| 272 | + let responses = question_responses(std::slice::from_ref(&question), &st).await?; | ||
| 273 | + let response = responses | ||
| 274 | + .into_iter() | ||
| 275 | + .next() | ||
| 276 | + .ok_or_else(|| AppError::Internal("failed to render the created question".into()))?; | ||
| 277 | + Ok((StatusCode::CREATED, Json(response))) | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +/// The question pool, newest first. Everyone (parents excepted) sees every | ||
| 281 | +/// `approved` question; `pending` ones appear only to their asker and to | ||
| 282 | +/// teacher+ — so for a teacher, `?status=pending` is the approval queue. | ||
| 283 | +/// Paged via `?limit=&offset=`. | ||
| 284 | +#[utoipa::path( | ||
| 285 | + get, | ||
| 286 | + path = "/", | ||
| 287 | + tag = "questions", | ||
| 288 | + security(("session_cookie" = [])), | ||
| 289 | + params(PoolQuestionFilter, PageParams), | ||
| 290 | + responses( | ||
| 291 | + (status = 200, description = "A page of the questions visible to the caller", body = Page<PoolQuestionResponse>), | ||
| 292 | + (status = 400, description = "Unknown status, or invalid limit or offset", body = ErrorResponse), | ||
| 293 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 294 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 295 | + ), | ||
| 296 | +)] | ||
| 297 | +async fn list_questions( | ||
| 298 | + State(st): State<AppState>, | ||
| 299 | + RequireStudent(user): RequireStudent, | ||
| 300 | + Query(filter): Query<PoolQuestionFilter>, | ||
| 301 | + Query(page): Query<PageParams>, | ||
| 302 | +) -> Result<Json<Page<PoolQuestionResponse>>, AppError> { | ||
| 303 | + let (limit, offset) = page.resolve()?; | ||
| 304 | + if let Some(ref status) = filter.status | ||
| 305 | + && !POOL_QUESTION_STATUSES.contains(&status.as_str()) | ||
| 306 | + { | ||
| 307 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 308 | + field: "status", | ||
| 309 | + reason: "must be one of: pending, approved", | ||
| 310 | + })); | ||
| 311 | + } | ||
| 312 | + | ||
| 313 | + let mut questions = if user.get_role().at_least(Role::Teacher) { | ||
| 314 | + PoolQuestion::list_all(&st.db).await? | ||
| 315 | + } else { | ||
| 316 | + PoolQuestion::list_visible_to(user.get_id(), &st.db).await? | ||
| 317 | + }; | ||
| 318 | + if let Some(ref status) = filter.status { | ||
| 319 | + questions.retain(|question| question.get_status() == status); | ||
| 320 | + } | ||
| 321 | + | ||
| 322 | + let total = questions.len() as i64; | ||
| 323 | + let items = question_responses(paginate(&questions, limit, offset), &st).await?; | ||
| 324 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +/// One question. Approved questions are school-wide; a pending one 404s for | ||
| 328 | +/// everyone but its asker and teacher+. | ||
| 329 | +#[utoipa::path( | ||
| 330 | + get, | ||
| 331 | + path = "/{id}", | ||
| 332 | + tag = "questions", | ||
| 333 | + security(("session_cookie" = [])), | ||
| 334 | + params(("id" = String, Path, description = "Question id")), | ||
| 335 | + responses( | ||
| 336 | + (status = 200, description = "The question", body = PoolQuestionResponse), | ||
| 337 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 338 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 339 | + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | ||
| 340 | + ), | ||
| 341 | +)] | ||
| 342 | +async fn get_question( | ||
| 343 | + State(st): State<AppState>, | ||
| 344 | + RequireStudent(user): RequireStudent, | ||
| 345 | + Path(id): Path<String>, | ||
| 346 | +) -> Result<Json<PoolQuestionResponse>, AppError> { | ||
| 347 | + let question = question_or_404(&st, &id).await?; | ||
| 348 | + ensure_visible(&question, &user)?; | ||
| 349 | + let responses = question_responses(std::slice::from_ref(&question), &st).await?; | ||
| 350 | + let response = responses | ||
| 351 | + .into_iter() | ||
| 352 | + .next() | ||
| 353 | + .ok_or_else(|| AppError::Internal("failed to render the question".into()))?; | ||
| 354 | + Ok(Json(response)) | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/// Approve a pending question into the school-wide pool (teacher+), | ||
| 358 | +/// stamping the approver. One-way: approved content is frozen, and there is | ||
| 359 | +/// no "rejected" state — to turn a question down, delete it. | ||
| 360 | +#[utoipa::path( | ||
| 361 | + post, | ||
| 362 | + path = "/{id}/approve", | ||
| 363 | + tag = "questions", | ||
| 364 | + security(("session_cookie" = [])), | ||
| 365 | + params(("id" = String, Path, description = "Question id")), | ||
| 366 | + responses( | ||
| 367 | + (status = 200, description = "The question, now approved", body = PoolQuestionResponse), | ||
| 368 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 369 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 370 | + (status = 404, description = "No such question", body = ErrorResponse), | ||
| 371 | + (status = 409, description = "Already approved", body = ErrorResponse), | ||
| 372 | + ), | ||
| 373 | +)] | ||
| 374 | +async fn approve_question( | ||
| 375 | + State(st): State<AppState>, | ||
| 376 | + RequireTeacher(user): RequireTeacher, | ||
| 377 | + Path(id): Path<String>, | ||
| 378 | +) -> Result<Json<PoolQuestionResponse>, AppError> { | ||
| 379 | + let approved = PoolQuestion::approve(&PoolQuestionId::from_key(&id), user.get_id(), &st.db) | ||
| 380 | + .await?; | ||
| 381 | + let question = match approved { | ||
| 382 | + Some(question) => question, | ||
| 383 | + // Nothing was pending under that id: either it's already approved | ||
| 384 | + // (409) or it never existed / was deleted (404). | ||
| 385 | + None => { | ||
| 386 | + question_or_404(&st, &id).await?; | ||
| 387 | + return Err(AppError::Conflict("the question is already approved")); | ||
| 388 | + } | ||
| 389 | + }; | ||
| 390 | + let responses = question_responses(std::slice::from_ref(&question), &st).await?; | ||
| 391 | + let response = responses | ||
| 392 | + .into_iter() | ||
| 393 | + .next() | ||
| 394 | + .ok_or_else(|| AppError::Internal("failed to render the approved question".into()))?; | ||
| 395 | + Ok(Json(response)) | ||
| 396 | +} | ||
| 397 | + | ||
| 398 | +/// Delete a question — the asker withdrawing their own, or teacher+ | ||
| 399 | +/// moderating (this is also how a pending question is rejected). Takes the | ||
| 400 | +/// question's solutions and every image blob — its own and its solutions' — | ||
| 401 | +/// with it. | ||
| 402 | +#[utoipa::path( | ||
| 403 | + delete, | ||
| 404 | + path = "/{id}", | ||
| 405 | + tag = "questions", | ||
| 406 | + security(("session_cookie" = [])), | ||
| 407 | + params(("id" = String, Path, description = "Question id")), | ||
| 408 | + responses( | ||
| 409 | + (status = 204, description = "Deleted, solutions included"), | ||
| 410 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 411 | + (status = 403, description = "Not the asker (and not teacher+)", body = ErrorResponse), | ||
| 412 | + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | ||
| 413 | + ), | ||
| 414 | +)] | ||
| 415 | +async fn delete_question( | ||
| 416 | + State(st): State<AppState>, | ||
| 417 | + RequireStudent(user): RequireStudent, | ||
| 418 | + Path(id): Path<String>, | ||
| 419 | +) -> Result<StatusCode, AppError> { | ||
| 420 | + let question = question_or_404(&st, &id).await?; | ||
| 421 | + ensure_visible(&question, &user)?; | ||
| 422 | + if question.get_asker() != user.get_id() && !user.get_role().at_least(Role::Teacher) { | ||
| 423 | + return Err(AppError::Forbidden( | ||
| 424 | + "only the asker or a teacher+ may delete a question", | ||
| 425 | + )); | ||
| 426 | + } | ||
| 427 | + let (removed, swept) = PoolQuestion::delete(question.get_id(), &st.db) | ||
| 428 | + .await? | ||
| 429 | + .ok_or(AppError::NotFound)?; | ||
| 430 | + // Rows went first (in one transaction); now every blob they pointed at — | ||
| 431 | + // the question's photo and each swept solution's — comes off disk. | ||
| 432 | + if let Some(file) = removed.get_image_file() { | ||
| 433 | + remove_blob(&st.files_path, file).await; | ||
| 434 | + } | ||
| 435 | + for solution in &swept { | ||
| 436 | + if let Some(file) = solution.get_image_file() { | ||
| 437 | + remove_blob(&st.files_path, file).await; | ||
| 438 | + } | ||
| 439 | + } | ||
| 440 | + Ok(StatusCode::NO_CONTENT) | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +// ---- the question's photo --------------------------------------------------- | ||
| 444 | +// One optional image per question — the snapshot of the problem sheet. Bytes | ||
| 445 | +// on disk under a server-generated ULID, metadata on the question row itself. | ||
| 446 | +// Asker-only, and only while pending: an image landing after approval would | ||
| 447 | +// put unmoderated bytes in the pool, so approval freezes it with the text. | ||
| 448 | + | ||
| 449 | +/// Attach (or replace) the question's photo. Asker only, while the question | ||
| 450 | +/// is still `pending` — approval freezes content, image included. | ||
| 451 | +/// `multipart/form-data` with the image under a `file` field; the declared | ||
| 452 | +/// content type must be `image/png`, `image/jpeg`, `image/webp`, or | ||
| 453 | +/// `image/gif` (rasters only — no SVG), the bytes at most the school's | ||
| 454 | +/// `max_file_bytes` (settings). | ||
| 455 | +#[utoipa::path( | ||
| 456 | + post, | ||
| 457 | + path = "/{id}/image", | ||
| 458 | + tag = "questions", | ||
| 459 | + security(("session_cookie" = [])), | ||
| 460 | + params(("id" = String, Path, description = "Question id")), | ||
| 461 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 462 | + responses( | ||
| 463 | + (status = 201, description = "Image stored", body = PoolImageMeta), | ||
| 464 | + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), | ||
| 465 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 466 | + (status = 403, description = "Not the asker", body = ErrorResponse), | ||
| 467 | + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | ||
| 468 | + (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), | ||
| 469 | + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), | ||
| 470 | + ), | ||
| 471 | +)] | ||
| 472 | +async fn upload_image( | ||
| 473 | + State(st): State<AppState>, | ||
| 474 | + RequireStudent(user): RequireStudent, | ||
| 475 | + Path(id): Path<String>, | ||
| 476 | + mut multipart: Multipart, | ||
| 477 | +) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> { | ||
| 478 | + let question = question_or_404(&st, &id).await?; | ||
| 479 | + ensure_asker_editable(&question, &user)?; | ||
| 480 | + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | ||
| 481 | + let upload = read_upload(&mut multipart, limit).await?; | ||
| 482 | + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; | ||
| 483 | + | ||
| 484 | + // Blob first, row second — a stored row always points at a real blob. | ||
| 485 | + let file = ulid::Ulid::new().to_string(); | ||
| 486 | + let path = blob_path(&st.files_path, &file); | ||
| 487 | + tokio::fs::write(&path, &upload.data) | ||
| 488 | + .await | ||
| 489 | + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; | ||
| 490 | + let size = upload.data.len() as i64; | ||
| 491 | + match PoolQuestion::set_image(question.get_id(), &file, &content_type, size, &st.db).await { | ||
| 492 | + // The guarded UPDATE found the question still pending: point-of-truth | ||
| 493 | + // write done; the replaced blob (if any) comes off disk. | ||
| 494 | + Ok(Some(before)) => { | ||
| 495 | + if let Some(replaced) = before.get_image_file() { | ||
| 496 | + remove_blob(&st.files_path, replaced).await; | ||
| 497 | + } | ||
| 498 | + Ok(( | ||
| 499 | + StatusCode::CREATED, | ||
| 500 | + Json(PoolImageMeta { | ||
| 501 | + content_type: content_type.as_str().to_string(), | ||
| 502 | + size, | ||
| 503 | + }), | ||
| 504 | + )) | ||
| 505 | + } | ||
| 506 | + // Approved or deleted mid-upload — the fresh blob is an orphan. | ||
| 507 | + Ok(None) => { | ||
| 508 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 509 | + Err(AppError::Conflict("the question is no longer pending")) | ||
| 510 | + } | ||
| 511 | + Err(err) => { | ||
| 512 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 513 | + Err(err) | ||
| 514 | + } | ||
| 515 | + } | ||
| 516 | +} | ||
| 517 | + | ||
| 518 | +/// The question's photo bytes. Access follows the question itself: approved → | ||
| 519 | +/// school-wide, pending → asker and teacher+ only. | ||
| 520 | +#[utoipa::path( | ||
| 521 | + get, | ||
| 522 | + path = "/{id}/image", | ||
| 523 | + tag = "questions", | ||
| 524 | + security(("session_cookie" = [])), | ||
| 525 | + params(("id" = String, Path, description = "Question id")), | ||
| 526 | + responses( | ||
| 527 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 528 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 529 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 530 | + (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), | ||
| 531 | + ), | ||
| 532 | +)] | ||
| 533 | +async fn get_image( | ||
| 534 | + State(st): State<AppState>, | ||
| 535 | + RequireStudent(user): RequireStudent, | ||
| 536 | + Path(id): Path<String>, | ||
| 537 | +) -> Result<Response, AppError> { | ||
| 538 | + let question = question_or_404(&st, &id).await?; | ||
| 539 | + ensure_visible(&question, &user)?; | ||
| 540 | + match (question.get_image_file(), question.get_image_content_type()) { | ||
| 541 | + (Some(file), Some(content_type)) => { | ||
| 542 | + serve_inline_blob(&st.files_path, file, content_type).await | ||
| 543 | + } | ||
| 544 | + _ => Err(AppError::NotFound), | ||
| 545 | + } | ||
| 546 | +} | ||
| 547 | + | ||
| 548 | +/// Remove the question's photo. Asker only, while still `pending` — after | ||
| 549 | +/// approval the content (image included) is frozen. | ||
| 550 | +#[utoipa::path( | ||
| 551 | + delete, | ||
| 552 | + path = "/{id}/image", | ||
| 553 | + tag = "questions", | ||
| 554 | + security(("session_cookie" = [])), | ||
| 555 | + params(("id" = String, Path, description = "Question id")), | ||
| 556 | + responses( | ||
| 557 | + (status = 204, description = "Image removed"), | ||
| 558 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 559 | + (status = 403, description = "Not the asker", body = ErrorResponse), | ||
| 560 | + (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), | ||
| 561 | + (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), | ||
| 562 | + ), | ||
| 563 | +)] | ||
| 564 | +async fn delete_image( | ||
| 565 | + State(st): State<AppState>, | ||
| 566 | + RequireStudent(user): RequireStudent, | ||
| 567 | + Path(id): Path<String>, | ||
| 568 | +) -> Result<StatusCode, AppError> { | ||
| 569 | + let question = question_or_404(&st, &id).await?; | ||
| 570 | + ensure_asker_editable(&question, &user)?; | ||
| 571 | + if question.get_image_file().is_none() { | ||
| 572 | + return Err(AppError::NotFound); | ||
| 573 | + } | ||
| 574 | + let before = PoolQuestion::clear_image(question.get_id(), &st.db) | ||
| 575 | + .await? | ||
| 576 | + .ok_or(AppError::Conflict("the question is no longer pending"))?; | ||
| 577 | + if let Some(file) = before.get_image_file() { | ||
| 578 | + remove_blob(&st.files_path, file).await; | ||
| 579 | + } | ||
| 580 | + Ok(StatusCode::NO_CONTENT) | ||
| 581 | +} | ||
| 582 | + | ||
| 583 | +// ---- solutions -------------------------------------------------------------- | ||
| 584 | + | ||
| 585 | +/// The solution, provided the caller may see the question it hangs on — | ||
| 586 | +/// visibility never splits below the question (a solution on a question you | ||
| 587 | +/// can't see must not exist for you either). | ||
| 588 | +async fn visible_solution( | ||
| 589 | + st: &AppState, | ||
| 590 | + user: &User, | ||
| 591 | + id: &str, | ||
| 592 | + sid: &str, | ||
| 593 | +) -> Result<Solution, AppError> { | ||
| 594 | + let question = question_or_404(st, id).await?; | ||
| 595 | + ensure_visible(&question, user)?; | ||
| 596 | + Solution::read_for(&SolutionId::from_key(sid), question.get_id(), &st.db) | ||
| 597 | + .await? | ||
| 598 | + .ok_or(AppError::NotFound) | ||
| 599 | +} | ||
| 600 | + | ||
| 601 | +/// The shared front half of the author-only solution writes (body edit, | ||
| 602 | +/// image upload/removal): 404 invisible or missing, then 403 not the author. | ||
| 603 | +/// Teacher+ get no pass here — moderation stays delete-only, a teacher never | ||
| 604 | +/// rewrites someone else's answer. And unlike a question there is no freeze | ||
| 605 | +/// gate: solutions are unmoderated, so their authors edit anytime. | ||
| 606 | +async fn author_solution( | ||
| 607 | + st: &AppState, | ||
| 608 | + user: &User, | ||
| 609 | + id: &str, | ||
| 610 | + sid: &str, | ||
| 611 | +) -> Result<Solution, AppError> { | ||
| 612 | + let solution = visible_solution(st, user, id, sid).await?; | ||
| 613 | + if solution.get_author() != user.get_id() { | ||
| 614 | + return Err(AppError::Forbidden("only the author may edit a solution")); | ||
| 615 | + } | ||
| 616 | + Ok(solution) | ||
| 617 | +} | ||
| 618 | + | ||
| 619 | +/// Offer a solution on an approved question. Anyone in the school may — | ||
| 620 | +/// students and staff alike (parents stay read-out). Pending questions take | ||
| 621 | +/// no solutions (409 for those who can see them, 404 for everyone else). | ||
| 622 | +#[utoipa::path( | ||
| 623 | + post, | ||
| 624 | + path = "/{id}/solutions", | ||
| 625 | + tag = "questions", | ||
| 626 | + security(("session_cookie" = [])), | ||
| 627 | + params(("id" = String, Path, description = "Question id")), | ||
| 628 | + request_body = OfferSolution, | ||
| 629 | + responses( | ||
| 630 | + (status = 201, description = "Solution offered", body = SolutionResponse), | ||
| 631 | + (status = 400, description = "Invalid body", body = ErrorResponse), | ||
| 632 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 633 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 634 | + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | ||
| 635 | + (status = 409, description = "The question is not approved yet", body = ErrorResponse), | ||
| 636 | + ), | ||
| 637 | +)] | ||
| 638 | +async fn offer_solution( | ||
| 639 | + State(st): State<AppState>, | ||
| 640 | + RequireStudent(user): RequireStudent, | ||
| 641 | + Path(id): Path<String>, | ||
| 642 | + Json(req): Json<OfferSolution>, | ||
| 643 | +) -> Result<(StatusCode, Json<SolutionResponse>), AppError> { | ||
| 644 | + let question = question_or_404(&st, &id).await?; | ||
| 645 | + ensure_visible(&question, &user)?; | ||
| 646 | + if !question.is_approved() { | ||
| 647 | + return Err(AppError::Conflict( | ||
| 648 | + "the question is not approved yet — solutions open with the pool", | ||
| 649 | + )); | ||
| 650 | + } | ||
| 651 | + let body = SolutionBody::try_new(&req.body)?; | ||
| 652 | + let solution = Solution::new(question.get_id(), user.get_id(), body) | ||
| 653 | + .insert(&st.db) | ||
| 654 | + .await?; | ||
| 655 | + let people = person_map([user.get_id().clone()], &st.db).await?; | ||
| 656 | + Ok(( | ||
| 657 | + StatusCode::CREATED, | ||
| 658 | + Json(SolutionResponse::new(&solution, &people)), | ||
| 659 | + )) | ||
| 660 | +} | ||
| 661 | + | ||
| 662 | +/// The question's solutions, oldest first (a discussion reads downward). | ||
| 663 | +/// Visibility follows the question. Paged via `?limit=&offset=`. | ||
| 664 | +#[utoipa::path( | ||
| 665 | + get, | ||
| 666 | + path = "/{id}/solutions", | ||
| 667 | + tag = "questions", | ||
| 668 | + security(("session_cookie" = [])), | ||
| 669 | + params(("id" = String, Path, description = "Question id"), PageParams), | ||
| 670 | + responses( | ||
| 671 | + (status = 200, description = "A page of the question's solutions", body = Page<SolutionResponse>), | ||
| 672 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 673 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 674 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 675 | + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | ||
| 676 | + ), | ||
| 677 | +)] | ||
| 678 | +async fn list_solutions( | ||
| 679 | + State(st): State<AppState>, | ||
| 680 | + RequireStudent(user): RequireStudent, | ||
| 681 | + Path(id): Path<String>, | ||
| 682 | + Query(page): Query<PageParams>, | ||
| 683 | +) -> Result<Json<Page<SolutionResponse>>, AppError> { | ||
| 684 | + let (limit, offset) = page.resolve()?; | ||
| 685 | + let question = question_or_404(&st, &id).await?; | ||
| 686 | + ensure_visible(&question, &user)?; | ||
| 687 | + let solutions = Solution::list_for(question.get_id(), &st.db).await?; | ||
| 688 | + let total = solutions.len() as i64; | ||
| 689 | + let slice = paginate(&solutions, limit, offset); | ||
| 690 | + let people = person_map( | ||
| 691 | + slice.iter().map(|solution| solution.get_author().clone()), | ||
| 692 | + &st.db, | ||
| 693 | + ) | ||
| 694 | + .await?; | ||
| 695 | + let items = slice | ||
| 696 | + .iter() | ||
| 697 | + .map(|solution| SolutionResponse::new(solution, &people)) | ||
| 698 | + .collect(); | ||
| 699 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 700 | +} | ||
| 701 | + | ||
| 702 | +/// Delete a solution — its author withdrawing it, or teacher+ moderating. | ||
| 703 | +/// Takes the solution's image blob with it. | ||
| 704 | +#[utoipa::path( | ||
| 705 | + delete, | ||
| 706 | + path = "/{id}/solutions/{sid}", | ||
| 707 | + tag = "questions", | ||
| 708 | + security(("session_cookie" = [])), | ||
| 709 | + params( | ||
| 710 | + ("id" = String, Path, description = "Question id"), | ||
| 711 | + ("sid" = String, Path, description = "Solution id"), | ||
| 712 | + ), | ||
| 713 | + responses( | ||
| 714 | + (status = 204, description = "Solution deleted"), | ||
| 715 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 716 | + (status = 403, description = "Not the author (and not teacher+)", body = ErrorResponse), | ||
| 717 | + (status = 404, description = "No such question or solution", body = ErrorResponse), | ||
| 718 | + ), | ||
| 719 | +)] | ||
| 720 | +async fn delete_solution( | ||
| 721 | + State(st): State<AppState>, | ||
| 722 | + RequireStudent(user): RequireStudent, | ||
| 723 | + Path((id, sid)): Path<(String, String)>, | ||
| 724 | +) -> Result<StatusCode, AppError> { | ||
| 725 | + let solution = visible_solution(&st, &user, &id, &sid).await?; | ||
| 726 | + if solution.get_author() != user.get_id() && !user.get_role().at_least(Role::Teacher) { | ||
| 727 | + return Err(AppError::Forbidden( | ||
| 728 | + "only the author or a teacher+ may delete a solution", | ||
| 729 | + )); | ||
| 730 | + } | ||
| 731 | + // Row first, blob after — a crash in between strands at worst an | ||
| 732 | + // unreachable file. | ||
| 733 | + let deleted = solution.delete(&st.db).await?; | ||
| 734 | + if let Some(file) = deleted.get_image_file() { | ||
| 735 | + remove_blob(&st.files_path, file).await; | ||
| 736 | + } | ||
| 737 | + Ok(StatusCode::NO_CONTENT) | ||
| 738 | +} | ||
| 739 | + | ||
| 740 | +/// Edit a solution's body — its author reworking their own answer. Author | ||
| 741 | +/// only, teacher+ included out: moderation stays delete-only (a moderator | ||
| 742 | +/// removes a bad solution, never rewrites someone else's words under their | ||
| 743 | +/// name). No freeze either — solutions are unmoderated, so editing stays | ||
| 744 | +/// open for as long as the solution lives. | ||
| 745 | +#[utoipa::path( | ||
| 746 | + patch, | ||
| 747 | + path = "/{id}/solutions/{sid}", | ||
| 748 | + tag = "questions", | ||
| 749 | + security(("session_cookie" = [])), | ||
| 750 | + params( | ||
| 751 | + ("id" = String, Path, description = "Question id"), | ||
| 752 | + ("sid" = String, Path, description = "Solution id"), | ||
| 753 | + ), | ||
| 754 | + request_body = OfferSolution, | ||
| 755 | + responses( | ||
| 756 | + (status = 200, description = "The updated solution", body = SolutionResponse), | ||
| 757 | + (status = 400, description = "Invalid body", body = ErrorResponse), | ||
| 758 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 759 | + (status = 403, description = "Not the author", body = ErrorResponse), | ||
| 760 | + (status = 404, description = "No such question or solution", body = ErrorResponse), | ||
| 761 | + ), | ||
| 762 | +)] | ||
| 763 | +async fn edit_solution( | ||
| 764 | + State(st): State<AppState>, | ||
| 765 | + RequireStudent(user): RequireStudent, | ||
| 766 | + Path((id, sid)): Path<(String, String)>, | ||
| 767 | + Json(req): Json<OfferSolution>, | ||
| 768 | +) -> Result<Json<SolutionResponse>, AppError> { | ||
| 769 | + let solution = author_solution(&st, &user, &id, &sid).await?; | ||
| 770 | + let body = SolutionBody::try_new(&req.body)?; | ||
| 771 | + let updated = Solution::set_body(solution.get_id(), &body, &st.db) | ||
| 772 | + .await? | ||
| 773 | + .ok_or(AppError::NotFound)?; | ||
| 774 | + let people = person_map([user.get_id().clone()], &st.db).await?; | ||
| 775 | + Ok(Json(SolutionResponse::new(&updated, &people))) | ||
| 776 | +} | ||
| 777 | + | ||
| 778 | +// ---- the solution's photo --------------------------------------------------- | ||
| 779 | +// One optional image per solution — the photographed worked steps or diagram. | ||
| 780 | +// Same blob discipline as the question's photo (bytes on disk under a | ||
| 781 | +// server-generated ULID, metadata on the row), but author-only *anytime*: | ||
| 782 | +// solutions carry no moderation state, so there is no approval to freeze | ||
| 783 | +// them. | ||
| 784 | + | ||
| 785 | +/// Attach (or replace) the solution's photo. Author only — and at any time, | ||
| 786 | +/// since solutions are never frozen. `multipart/form-data` with the image | ||
| 787 | +/// under a `file` field; the declared content type must be `image/png`, | ||
| 788 | +/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the | ||
| 789 | +/// bytes at most the school's `max_file_bytes` (settings). | ||
| 790 | +#[utoipa::path( | ||
| 791 | + post, | ||
| 792 | + path = "/{id}/solutions/{sid}/image", | ||
| 793 | + tag = "questions", | ||
| 794 | + security(("session_cookie" = [])), | ||
| 795 | + params( | ||
| 796 | + ("id" = String, Path, description = "Question id"), | ||
| 797 | + ("sid" = String, Path, description = "Solution id"), | ||
| 798 | + ), | ||
| 799 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 800 | + responses( | ||
| 801 | + (status = 201, description = "Image stored", body = PoolImageMeta), | ||
| 802 | + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), | ||
| 803 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 804 | + (status = 403, description = "Not the author", body = ErrorResponse), | ||
| 805 | + (status = 404, description = "No such question or solution", body = ErrorResponse), | ||
| 806 | + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), | ||
| 807 | + ), | ||
| 808 | +)] | ||
| 809 | +async fn upload_solution_image( | ||
| 810 | + State(st): State<AppState>, | ||
| 811 | + RequireStudent(user): RequireStudent, | ||
| 812 | + Path((id, sid)): Path<(String, String)>, | ||
| 813 | + mut multipart: Multipart, | ||
| 814 | +) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> { | ||
| 815 | + let solution = author_solution(&st, &user, &id, &sid).await?; | ||
| 816 | + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | ||
| 817 | + let upload = read_upload(&mut multipart, limit).await?; | ||
| 818 | + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; | ||
| 819 | + | ||
| 820 | + // Blob first, row second — a stored row always points at a real blob. | ||
| 821 | + let file = ulid::Ulid::new().to_string(); | ||
| 822 | + let path = blob_path(&st.files_path, &file); | ||
| 823 | + tokio::fs::write(&path, &upload.data) | ||
| 824 | + .await | ||
| 825 | + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; | ||
| 826 | + let size = upload.data.len() as i64; | ||
| 827 | + match Solution::set_image(solution.get_id(), &file, &content_type, size, &st.db).await { | ||
| 828 | + // Row write done; the replaced blob (if any) comes off disk. | ||
| 829 | + Ok(Some(before)) => { | ||
| 830 | + if let Some(replaced) = before.get_image_file() { | ||
| 831 | + remove_blob(&st.files_path, replaced).await; | ||
| 832 | + } | ||
| 833 | + Ok(( | ||
| 834 | + StatusCode::CREATED, | ||
| 835 | + Json(PoolImageMeta { | ||
| 836 | + content_type: content_type.as_str().to_string(), | ||
| 837 | + size, | ||
| 838 | + }), | ||
| 839 | + )) | ||
| 840 | + } | ||
| 841 | + // Deleted mid-upload — the fresh blob is an orphan. | ||
| 842 | + Ok(None) => { | ||
| 843 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 844 | + Err(AppError::NotFound) | ||
| 845 | + } | ||
| 846 | + Err(err) => { | ||
| 847 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 848 | + Err(err) | ||
| 849 | + } | ||
| 850 | + } | ||
| 851 | +} | ||
| 852 | + | ||
| 853 | +/// The solution photo's bytes. Access follows the question the solution | ||
| 854 | +/// hangs on — in practice school-wide, since solutions exist only on | ||
| 855 | +/// approved questions. | ||
| 856 | +#[utoipa::path( | ||
| 857 | + get, | ||
| 858 | + path = "/{id}/solutions/{sid}/image", | ||
| 859 | + tag = "questions", | ||
| 860 | + security(("session_cookie" = [])), | ||
| 861 | + params( | ||
| 862 | + ("id" = String, Path, description = "Question id"), | ||
| 863 | + ("sid" = String, Path, description = "Solution id"), | ||
| 864 | + ), | ||
| 865 | + responses( | ||
| 866 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 867 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 868 | + (status = 403, description = "Requires student role or higher", body = ErrorResponse), | ||
| 869 | + (status = 404, description = "No such question, solution, or image", body = ErrorResponse), | ||
| 870 | + ), | ||
| 871 | +)] | ||
| 872 | +async fn get_solution_image( | ||
| 873 | + State(st): State<AppState>, | ||
| 874 | + RequireStudent(user): RequireStudent, | ||
| 875 | + Path((id, sid)): Path<(String, String)>, | ||
| 876 | +) -> Result<Response, AppError> { | ||
| 877 | + let solution = visible_solution(&st, &user, &id, &sid).await?; | ||
| 878 | + match (solution.get_image_file(), solution.get_image_content_type()) { | ||
| 879 | + (Some(file), Some(content_type)) => { | ||
| 880 | + serve_inline_blob(&st.files_path, file, content_type).await | ||
| 881 | + } | ||
| 882 | + _ => Err(AppError::NotFound), | ||
| 883 | + } | ||
| 884 | +} | ||
| 885 | + | ||
| 886 | +/// Remove the solution's photo. Author only, anytime — solutions are never | ||
| 887 | +/// frozen. | ||
| 888 | +#[utoipa::path( | ||
| 889 | + delete, | ||
| 890 | + path = "/{id}/solutions/{sid}/image", | ||
| 891 | + tag = "questions", | ||
| 892 | + security(("session_cookie" = [])), | ||
| 893 | + params( | ||
| 894 | + ("id" = String, Path, description = "Question id"), | ||
| 895 | + ("sid" = String, Path, description = "Solution id"), | ||
| 896 | + ), | ||
| 897 | + responses( | ||
| 898 | + (status = 204, description = "Image removed"), | ||
| 899 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 900 | + (status = 403, description = "Not the author", body = ErrorResponse), | ||
| 901 | + (status = 404, description = "No such question, solution, or image", body = ErrorResponse), | ||
| 902 | + ), | ||
| 903 | +)] | ||
| 904 | +async fn delete_solution_image( | ||
| 905 | + State(st): State<AppState>, | ||
| 906 | + RequireStudent(user): RequireStudent, | ||
| 907 | + Path((id, sid)): Path<(String, String)>, | ||
| 908 | +) -> Result<StatusCode, AppError> { | ||
| 909 | + let solution = author_solution(&st, &user, &id, &sid).await?; | ||
| 910 | + if solution.get_image_file().is_none() { | ||
| 911 | + return Err(AppError::NotFound); | ||
| 912 | + } | ||
| 913 | + let before = Solution::clear_image(solution.get_id(), &st.db) | ||
| 914 | + .await? | ||
| 915 | + .ok_or(AppError::NotFound)?; | ||
| 916 | + if let Some(file) = before.get_image_file() { | ||
| 917 | + remove_blob(&st.files_path, file).await; | ||
| 918 | + } | ||
| 919 | + Ok(StatusCode::NO_CONTENT) | ||
| 920 | +} | ||
tests/integration.rsmodified+339 -0
| @@ -11432,3 +11432,342 @@ async fn stale_parent_link_is_inert_after_role_change() { | |||
| 11432 | ); | 11432 | ); |
| 11433 | } | 11433 | } |
| 11434 | } | 11434 | } |
| 11435 | + | ||
| 11436 | +// --- the question pool --------------------------------------------------- | ||
| 11437 | + | ||
| 11438 | +/// The pool lifecycle end to end: a student asks (pending — invisible to | ||
| 11439 | +/// other students, listed for teachers), a teacher approves (one-way, 409 on | ||
| 11440 | +/// repeat), the pool opens school-wide, anyone offers solutions, and | ||
| 11441 | +/// moderation deletes cascade. | ||
| 11442 | +#[tokio::test] | ||
| 11443 | +async fn question_pool_lifecycle() { | ||
| 11444 | + let (app, db) = app_and_db().await; | ||
| 11445 | + let asker = login(&app, "ali").await; | ||
| 11446 | + let stranger = login(&app, "veli").await; | ||
| 11447 | + let teacher = login_as(&app, &db, "hoca", "teacher").await; | ||
| 11448 | + | ||
| 11449 | + // Only students ask: the teacher is refused. | ||
| 11450 | + let ask = json!({ "title": "Integral", "body": "∫x·eˣ dx?" }); | ||
| 11451 | + let res = send(&app, "POST", "/questions", Some(&teacher), Some(ask.clone())).await; | ||
| 11452 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11453 | + | ||
| 11454 | + let res = send(&app, "POST", "/questions", Some(&asker), Some(ask)).await; | ||
| 11455 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 11456 | + assert_eq!(res.body["status"], "pending"); | ||
| 11457 | + let qid = id_of(&res.body); | ||
| 11458 | + | ||
| 11459 | + // Pending: the asker and the teacher see it; another student must not | ||
| 11460 | + // even learn it exists — and it takes no solutions yet. | ||
| 11461 | + for (cookie, visible) in [(&asker, true), (&teacher, true), (&stranger, false)] { | ||
| 11462 | + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(cookie), None).await; | ||
| 11463 | + let expected = if visible { StatusCode::OK } else { StatusCode::NOT_FOUND }; | ||
| 11464 | + assert_eq!(res.status, expected, "{}", res.body); | ||
| 11465 | + } | ||
| 11466 | + let offer = json!({ "body": "Kısmi integrasyon." }); | ||
| 11467 | + let res = send( | ||
| 11468 | + &app, | ||
| 11469 | + "POST", | ||
| 11470 | + &format!("/questions/{qid}/solutions"), | ||
| 11471 | + Some(&asker), | ||
| 11472 | + Some(offer.clone()), | ||
| 11473 | + ) | ||
| 11474 | + .await; | ||
| 11475 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 11476 | + | ||
| 11477 | + // The teacher's ?status=pending list is the approval queue; approval is | ||
| 11478 | + // teacher-gated and one-way. | ||
| 11479 | + let res = send(&app, "GET", "/questions?status=pending", Some(&teacher), None).await; | ||
| 11480 | + assert_eq!(common::total(&res.body), 1); | ||
| 11481 | + let res = send( | ||
| 11482 | + &app, | ||
| 11483 | + "POST", | ||
| 11484 | + &format!("/questions/{qid}/approve"), | ||
| 11485 | + Some(&stranger), | ||
| 11486 | + None, | ||
| 11487 | + ) | ||
| 11488 | + .await; | ||
| 11489 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11490 | + let res = send( | ||
| 11491 | + &app, | ||
| 11492 | + "POST", | ||
| 11493 | + &format!("/questions/{qid}/approve"), | ||
| 11494 | + Some(&teacher), | ||
| 11495 | + None, | ||
| 11496 | + ) | ||
| 11497 | + .await; | ||
| 11498 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 11499 | + assert_eq!(res.body["status"], "approved"); | ||
| 11500 | + assert_eq!(res.body["approved_by"]["username"], "hoca"); | ||
| 11501 | + let res = send( | ||
| 11502 | + &app, | ||
| 11503 | + "POST", | ||
| 11504 | + &format!("/questions/{qid}/approve"), | ||
| 11505 | + Some(&teacher), | ||
| 11506 | + None, | ||
| 11507 | + ) | ||
| 11508 | + .await; | ||
| 11509 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 11510 | + | ||
| 11511 | + // Approved: school-wide — the stranger reads it and answers it. | ||
| 11512 | + let res = send(&app, "GET", "/questions", Some(&stranger), None).await; | ||
| 11513 | + assert_eq!(common::total(&res.body), 1); | ||
| 11514 | + let res = send( | ||
| 11515 | + &app, | ||
| 11516 | + "POST", | ||
| 11517 | + &format!("/questions/{qid}/solutions"), | ||
| 11518 | + Some(&stranger), | ||
| 11519 | + Some(offer), | ||
| 11520 | + ) | ||
| 11521 | + .await; | ||
| 11522 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 11523 | + let sid = id_of(&res.body); | ||
| 11524 | + | ||
| 11525 | + // Deleting the solution: a third party may not, its author may. | ||
| 11526 | + let res = send( | ||
| 11527 | + &app, | ||
| 11528 | + "DELETE", | ||
| 11529 | + &format!("/questions/{qid}/solutions/{sid}"), | ||
| 11530 | + Some(&asker), | ||
| 11531 | + None, | ||
| 11532 | + ) | ||
| 11533 | + .await; | ||
| 11534 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11535 | + let res = send( | ||
| 11536 | + &app, | ||
| 11537 | + "DELETE", | ||
| 11538 | + &format!("/questions/{qid}/solutions/{sid}"), | ||
| 11539 | + Some(&stranger), | ||
| 11540 | + None, | ||
| 11541 | + ) | ||
| 11542 | + .await; | ||
| 11543 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 11544 | + | ||
| 11545 | + // Question delete (asker withdraws) cascades what's left. | ||
| 11546 | + let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await; | ||
| 11547 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 11548 | + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&teacher), None).await; | ||
| 11549 | + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); | ||
| 11550 | +} | ||
| 11551 | + | ||
| 11552 | +/// Parents are observers: every pool surface (list, ask, answer) is closed to | ||
| 11553 | +/// them. | ||
| 11554 | +#[tokio::test] | ||
| 11555 | +async fn question_pool_locks_parents_out() { | ||
| 11556 | + let (app, db) = app_and_db().await; | ||
| 11557 | + let parent = login_as(&app, &db, "anne", "parent").await; | ||
| 11558 | + let res = send(&app, "GET", "/questions", Some(&parent), None).await; | ||
| 11559 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11560 | + let res = send( | ||
| 11561 | + &app, | ||
| 11562 | + "POST", | ||
| 11563 | + "/questions", | ||
| 11564 | + Some(&parent), | ||
| 11565 | + Some(json!({ "title": "t", "body": "b" })), | ||
| 11566 | + ) | ||
| 11567 | + .await; | ||
| 11568 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11569 | +} | ||
| 11570 | + | ||
| 11571 | +/// The question photo: asker-only upload while pending, SVG refused, bytes | ||
| 11572 | +/// served under the question's visibility, approval freezes the slot. | ||
| 11573 | +#[tokio::test] | ||
| 11574 | +async fn question_pool_image_upload_and_freeze() { | ||
| 11575 | + let (app, db) = app_and_db().await; | ||
| 11576 | + let asker = login(&app, "ali").await; | ||
| 11577 | + let stranger = login(&app, "veli").await; | ||
| 11578 | + let teacher = login_as(&app, &db, "hoca", "teacher").await; | ||
| 11579 | + | ||
| 11580 | + let res = send( | ||
| 11581 | + &app, | ||
| 11582 | + "POST", | ||
| 11583 | + "/questions", | ||
| 11584 | + Some(&asker), | ||
| 11585 | + Some(json!({ "title": "Harita", "body": "Hangi şehir?" })), | ||
| 11586 | + ) | ||
| 11587 | + .await; | ||
| 11588 | + let qid = id_of(&res.body); | ||
| 11589 | + let upload = |cookie: &str, content_type: &str| { | ||
| 11590 | + let uri = format!("/questions/{qid}/image"); | ||
| 11591 | + let body = common::multipart_file("soru.png", content_type, b"png-bytes"); | ||
| 11592 | + let cookie = cookie.to_string(); | ||
| 11593 | + let app = app.clone(); | ||
| 11594 | + async move { | ||
| 11595 | + common::send_raw( | ||
| 11596 | + &app, | ||
| 11597 | + "POST", | ||
| 11598 | + &uri, | ||
| 11599 | + Some(&cookie), | ||
| 11600 | + Some("multipart/form-data; boundary=hezarfen-test-boundary"), | ||
| 11601 | + body, | ||
| 11602 | + ) | ||
| 11603 | + .await | ||
| 11604 | + } | ||
| 11605 | + }; | ||
| 11606 | + | ||
| 11607 | + // SVG is out; the teacher isn't the asker; the asker's PNG lands. | ||
| 11608 | + let (status, _, _) = upload(&asker, "image/svg+xml").await; | ||
| 11609 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 11610 | + let (status, _, _) = upload(&teacher, "image/png").await; | ||
| 11611 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 11612 | + let (status, _, _) = upload(&asker, "image/png").await; | ||
| 11613 | + assert_eq!(status, StatusCode::CREATED); | ||
| 11614 | + | ||
| 11615 | + // Pending bytes follow pending visibility: asker yes, stranger no. | ||
| 11616 | + let uri = format!("/questions/{qid}/image"); | ||
| 11617 | + let (status, headers, bytes) = | ||
| 11618 | + common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; | ||
| 11619 | + assert_eq!(status, StatusCode::OK); | ||
| 11620 | + assert_eq!(headers["content-type"], "image/png"); | ||
| 11621 | + assert_eq!(bytes, b"png-bytes"); | ||
| 11622 | + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; | ||
| 11623 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 11624 | + | ||
| 11625 | + // Approval freezes the image with the text: replace and remove both 409. | ||
| 11626 | + let res = send( | ||
| 11627 | + &app, | ||
| 11628 | + "POST", | ||
| 11629 | + &format!("/questions/{qid}/approve"), | ||
| 11630 | + Some(&teacher), | ||
| 11631 | + None, | ||
| 11632 | + ) | ||
| 11633 | + .await; | ||
| 11634 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 11635 | + let (status, _, _) = upload(&asker, "image/png").await; | ||
| 11636 | + assert_eq!(status, StatusCode::CONFLICT); | ||
| 11637 | + let (status, _, _) = | ||
| 11638 | + common::send_raw(&app, "DELETE", &uri, Some(&asker), None, Vec::new()).await; | ||
| 11639 | + assert_eq!(status, StatusCode::CONFLICT); | ||
| 11640 | + | ||
| 11641 | + // But the approved bytes are now school-wide, and ride the question meta. | ||
| 11642 | + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; | ||
| 11643 | + assert_eq!(status, StatusCode::OK); | ||
| 11644 | + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&stranger), None).await; | ||
| 11645 | + assert_eq!(res.body["image"]["content_type"], "image/png"); | ||
| 11646 | +} | ||
| 11647 | + | ||
| 11648 | +/// The solution's photo and body stay the author's alone (no freeze — no | ||
| 11649 | +/// moderation state to protect), bytes follow the question's visibility, and | ||
| 11650 | +/// question rows tally their solutions. | ||
| 11651 | +#[tokio::test] | ||
| 11652 | +async fn solution_images_edits_and_counts() { | ||
| 11653 | + let (app, db) = app_and_db().await; | ||
| 11654 | + let asker = login(&app, "ali").await; | ||
| 11655 | + let helper = login(&app, "veli").await; | ||
| 11656 | + let teacher = login_as(&app, &db, "hoca", "teacher").await; | ||
| 11657 | + | ||
| 11658 | + // An approved question with the helper's solution under it. | ||
| 11659 | + let res = send( | ||
| 11660 | + &app, | ||
| 11661 | + "POST", | ||
| 11662 | + "/questions", | ||
| 11663 | + Some(&asker), | ||
| 11664 | + Some(json!({ "title": "Limit", "body": "x→0 iken sin(x)/x?" })), | ||
| 11665 | + ) | ||
| 11666 | + .await; | ||
| 11667 | + let qid = id_of(&res.body); | ||
| 11668 | + let res = send( | ||
| 11669 | + &app, | ||
| 11670 | + "POST", | ||
| 11671 | + &format!("/questions/{qid}/approve"), | ||
| 11672 | + Some(&teacher), | ||
| 11673 | + None, | ||
| 11674 | + ) | ||
| 11675 | + .await; | ||
| 11676 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 11677 | + let res = send( | ||
| 11678 | + &app, | ||
| 11679 | + "POST", | ||
| 11680 | + &format!("/questions/{qid}/solutions"), | ||
| 11681 | + Some(&helper), | ||
| 11682 | + Some(json!({ "body": "Birebir 1'e gider." })), | ||
| 11683 | + ) | ||
| 11684 | + .await; | ||
| 11685 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 11686 | + assert!(res.body["image"].is_null()); | ||
| 11687 | + let sid = id_of(&res.body); | ||
| 11688 | + | ||
| 11689 | + // Image writes are the author's: the asker is refused, the helper lands. | ||
| 11690 | + let uri = format!("/questions/{qid}/solutions/{sid}/image"); | ||
| 11691 | + let upload = |cookie: &str| { | ||
| 11692 | + let uri = uri.clone(); | ||
| 11693 | + let body = common::multipart_file("cozum.png", "image/png", b"png-bytes"); | ||
| 11694 | + let cookie = cookie.to_string(); | ||
| 11695 | + let app = app.clone(); | ||
| 11696 | + async move { | ||
| 11697 | + common::send_raw( | ||
| 11698 | + &app, | ||
| 11699 | + "POST", | ||
| 11700 | + &uri, | ||
| 11701 | + Some(&cookie), | ||
| 11702 | + Some("multipart/form-data; boundary=hezarfen-test-boundary"), | ||
| 11703 | + body, | ||
| 11704 | + ) | ||
| 11705 | + .await | ||
| 11706 | + } | ||
| 11707 | + }; | ||
| 11708 | + let (status, _, _) = upload(&asker).await; | ||
| 11709 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 11710 | + let (status, _, _) = upload(&teacher).await; | ||
| 11711 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 11712 | + let (status, _, _) = upload(&helper).await; | ||
| 11713 | + assert_eq!(status, StatusCode::CREATED); | ||
| 11714 | + | ||
| 11715 | + // Bytes follow the question's visibility — approved, so any student | ||
| 11716 | + // reads them — and the meta rides the solution row. | ||
| 11717 | + let (status, headers, bytes) = | ||
| 11718 | + common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; | ||
| 11719 | + assert_eq!(status, StatusCode::OK); | ||
| 11720 | + assert_eq!(headers["content-type"], "image/png"); | ||
| 11721 | + assert_eq!(bytes, b"png-bytes"); | ||
| 11722 | + let res = send( | ||
| 11723 | + &app, | ||
| 11724 | + "GET", | ||
| 11725 | + &format!("/questions/{qid}/solutions"), | ||
| 11726 | + Some(&asker), | ||
| 11727 | + None, | ||
| 11728 | + ) | ||
| 11729 | + .await; | ||
| 11730 | + assert_eq!(res.body["items"][0]["image"]["content_type"], "image/png"); | ||
| 11731 | + | ||
| 11732 | + // Body edits are author-only too — teacher+ moderate by deleting, never | ||
| 11733 | + // by rewriting. | ||
| 11734 | + let edit = json!({ "body": "Standart limit: sin(x)/x → 1." }); | ||
| 11735 | + let res = send( | ||
| 11736 | + &app, | ||
| 11737 | + "PATCH", | ||
| 11738 | + &format!("/questions/{qid}/solutions/{sid}"), | ||
| 11739 | + Some(&asker), | ||
| 11740 | + Some(edit.clone()), | ||
| 11741 | + ) | ||
| 11742 | + .await; | ||
| 11743 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 11744 | + let res = send( | ||
| 11745 | + &app, | ||
| 11746 | + "PATCH", | ||
| 11747 | + &format!("/questions/{qid}/solutions/{sid}"), | ||
| 11748 | + Some(&helper), | ||
| 11749 | + Some(edit), | ||
| 11750 | + ) | ||
| 11751 | + .await; | ||
| 11752 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 11753 | + assert_eq!(res.body["body"], "Standart limit: sin(x)/x → 1."); | ||
| 11754 | + assert_eq!(res.body["image"]["content_type"], "image/png"); | ||
| 11755 | + | ||
| 11756 | + // Question rows tally their solutions, in the list and the single GET. | ||
| 11757 | + let res = send(&app, "GET", "/questions?limit=5", Some(&asker), None).await; | ||
| 11758 | + assert_eq!(res.body["items"][0]["solution_count"], 1); | ||
| 11759 | + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&asker), None).await; | ||
| 11760 | + assert_eq!(res.body["solution_count"], 1); | ||
| 11761 | + | ||
| 11762 | + // The author drops the photo; a second removal finds nothing. | ||
| 11763 | + let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; | ||
| 11764 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 11765 | + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; | ||
| 11766 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 11767 | + let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; | ||
| 11768 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 11769 | + | ||
| 11770 | + // And the question delete still sweeps everything under it. | ||
| 11771 | + let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await; | ||
| 11772 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 11773 | +} | ||