From 0df048b7abc1eef44bf7872b578ffa38575c2f18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 21 Jul 2026 04:58:41 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(questions):=20student=20Q&A=20?= =?UTF-8?q?pool=20with=20moderated=20solutions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Students ask (one photo, pending-only edits), teacher+ approve into a school-wide pool — approval freezes content so nothing unmoderated slips in after review; rejection is deletion, no rejected state. Anyone above parent offers solutions: text + one photo, author-edited anytime (unmoderated), delete-only moderation. Question rows carry solution_count; deletes cascade solutions and image blobs (zero orphans). Question and solution photos reuse the exam-image raster allowlist and size cap via serve helpers shared out of exams. --- README.md | 92 +++- src/constant.rs | 18 +- src/database.rs | 25 + src/domain/mod.rs | 2 + src/domain/pool_question.rs | 457 ++++++++++++++++++ src/domain/solution.rs | 442 +++++++++++++++++ src/lib.rs | 4 +- src/web/exams.rs | 50 +- src/web/mod.rs | 50 +- src/web/questions.rs | 920 ++++++++++++++++++++++++++++++++++++ tests/integration.rs | 339 +++++++++++++ 11 files changed, 2348 insertions(+), 51 deletions(-) create mode 100644 src/domain/pool_question.rs create mode 100644 src/domain/solution.rs create mode 100644 src/web/questions.rs diff --git a/README.md b/README.md index 8483e8c..b62f05b 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,15 @@ with a server-stamped **pomodoro log** (the timer runs in the frontend; the backend records the focus stints, and teachers can read any student's log), and every user has an **attendance report** (event + per-course lesson tallies with rates). +A school-wide **question pool** runs on moderation: a student asks a question +(optionally attaching one photo of the problem — raster only, same +`max_file_bytes` cap), 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 with anyone free to offer +**solutions** under it (parents stay out) — text plus an optional photo of +the worked steps, both editable by the solution's author anytime; pending +questions show only to their asker and to teacher+, and approval freezes the +content so nothing unmoderated ever reaches the pool. School-varying policy is data, not code: exam kinds (each with its weight in course averages), attendance statuses, grade-display bands, and the note-file 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`, means dev mirror mode without credentials; a cookie-using browser frontend must be allowlisted explicitly. Works with `docker compose` too. +The backend keeps its database WebSocket alive with a periodic trivial query, +and the SDK reconnects on its own if the socket drops anyway (a `podman +restart hezarfen-surrealdb`, say). During that brief reconnect window requests +answer `503` with `Retry-After: 1` instead of a `500` — the outage is +transient, so clients just retry a moment later. + Without compose: ```sh @@ -227,6 +242,9 @@ course enrollments. | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | | 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' | +| 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 | +| 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 | +| 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 | | Read **own** attendance report | student | | | 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 | | 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 | 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") | | 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) | | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | +| POST | `/questions` | student | `{title, body}` — ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ | +| GET | `/questions` | student | `?status=pending\|approved` — the pool questions visible to the caller, each with its `solution_count` · paged | +| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) | +| POST | `/questions/{id}/approve` | teacher | Approve a pending question — publishes it school-wide; content frozen after (`409` if already approved) | +| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it | +| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≤ `max_file_bytes` | +| GET | `/questions/{id}/image` | student | The photo bytes | +| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) | +| POST | `/questions/{id}/solutions` | student | `{body}` — offer a solution on an approved question (anyone in the school) | +| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first — a discussion thread · paged | +| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it | +| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` — edit own solution (author only, teacher+ included out; solutions never freeze) | +| 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` | +| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) | +| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) | | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) | | GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | | 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 is just sending a new message back — the frontend prefixes the subject if it wants an `Re:`. +## Question pool + +Students get stuck; the pool is where the school unsticks them — with a +moderation gate so nothing unreviewed goes school-wide. `POST /questions` +(students only, exact role) creates the question `pending`: only the asker +and teacher+ can see it (anyone else gets a `404`, not a `403` — a pending +question's existence is nobody else's business), and `GET +/questions?status=pending` is a teacher's approval queue. The asker may +attach **one photo** of the problem (`POST /questions/{id}/image`, +`multipart/form-data` with a `file` part — raster types only, no SVG, ≤ the +school's `max_file_bytes`), replace it, or remove it — while pending only. + +`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes +readable by every signed-in user above `parent`, and its content — title, +body, photo — **freezes**, because an edit after approval would bypass the +moderation that just happened. There is no rejected state and no edit +endpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+ +deletes. Approving twice is a `409`; the response records `approved_by`. + +Anyone in the school (student through admin — not parents) may then offer a +**solution**: `POST /questions/{id}/solutions` with a text body, listed +oldest-first like a discussion thread (`GET`, paged). Solutions are the +unmoderated half of the pool, so nothing about them ever freezes: the author +— and only the author, teacher+ included out — may edit the body (`PATCH +/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked +steps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules +and `max_file_bytes` cap as the question's photo), replace it, or remove it, +at any time; moderation stays delete-only — a teacher+ removes a bad +solution, never rewrites someone else's words. A solution is deleted by its +author or by teacher+, its photo blob going with it; deleting a question — +asker withdrawing, or teacher+ moderating — takes its solutions and every +photo blob (its own and its solutions') with it. Each question row reports +its `solution_count`, and questions and solutions embed their people as +person refs (`{id, username, display_name}`), so the UI never shows a raw +ULID. + ## Per-school policy (settings & terms) Every school runs differently; the parts that vary are data, not code. One @@ -1017,13 +1086,32 @@ src/ exam_answer.rs ExamAnswerId · AnswerText · ExamAnswer (one row per question+user) · auto_score (choice-question suggestion) exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user) + question_image.rs QuestionImageId · QuestionImage (question/choice picture + metadata; bytes on disk under FILES_PATH) + profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) + preferences.rs Theme · Language (own UI preferences) + message.rs MessageId · MessageSubject · MessageBody · MessageLabel · + Message (per-copy folders: inbox/sent/archive/trash) + parent_link.rs ParentLinkId · ParentLink (parent↔student tie = the parent's read grant) + registration.rs RegistrationId · Registration (a seat on a registration event's signup list) + subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum) + term.rs TermId · TermName · Term (school term window) + settings.rs ExamKindDef · GradeBand · Settings (per-school policy) + pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log) + pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody · + PoolQuestion (student-asked question; teacher-approved into + the school-wide pool; optional photo as metadata + disk blob) + solution.rs SolutionId · SolutionBody · Solution (discussion thread on an + approved pool question; dies with the question) web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + auth extractors extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish) - auth.rs users.rs notes.rs events.rs courses.rs sessions.rs exams.rs - marks.rs work.rs attendance.rs + page.rs PageParams · Page (shared pagination) + auth.rs users.rs notes.rs messages.rs events.rs courses.rs subjects.rs + sessions.rs exams.rs questions.rs marks.rs work.rs pomodoro.rs + attendance.rs settings.rs terms.rs ``` Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory diff --git a/src/constant.rs b/src/constant.rs index bb837a0..b72627b 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -61,12 +61,18 @@ pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024; /// the file bytes themselves. pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; -/// The content types a question image may declare — raster formats only. SVG -/// is deliberately out: it can carry scripts, and these bytes are served for -/// inline display to everyone sitting the exam. +/// The content types an uploaded inline image (exam question images, pool +/// question photos) may declare — raster formats only. SVG is deliberately +/// out: it can carry scripts, and these bytes are served for inline display +/// to whole classes. pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; +/// Bounds for a pool question (the student-asked Q&A pool) and its solutions. +pub const MAX_POOL_QUESTION_TITLE_LEN: usize = 200; +pub const MAX_POOL_QUESTION_BODY_LEN: usize = 10_000; +pub const MAX_SOLUTION_BODY_LEN: usize = 10_000; + pub const MAX_EVENT_TITLE_LEN: usize = 200; pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; @@ -141,6 +147,12 @@ pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; +/// Cadence of the background keepalive query on the database WebSocket. The +/// traffic keeps the connection from being dropped as idle; when it does drop, +/// the ping also makes the SDK notice and reconnect long before the next real +/// request would. +pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 30; + /// Cadence of the `state` ticks on the student exam-room WebSocket /// (`GET /exams/{id}/attempt/ws`). pub const EXAM_WS_TICK_SECS: u64 = 2; diff --git a/src/database.rs b/src/database.rs index be97952..9c4f68e 100644 --- a/src/database.rs +++ b/src/database.rs @@ -33,6 +33,8 @@ pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session"; pub const SETTINGS_TABLE: &str = "settings"; pub const TERM_TABLE: &str = "term"; pub const SUBJECT_TABLE: &str = "subject"; +pub const POOL_QUESTION_TABLE: &str = "pool_question"; +pub const SOLUTION_TABLE: &str = "solution"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the @@ -246,6 +248,29 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record; DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE; + DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record; + DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; + DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; + DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; + DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; + DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option>; + DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option; + DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option; + DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option; + DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; + DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; + + DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS question ON solution TYPE record; + DEFINE FIELD IF NOT EXISTS author ON solution TYPE record; + DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; + DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; + DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option; + DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option; + DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option; + DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; + DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array; DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 80c26f0..1c9d9b4 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -17,6 +17,7 @@ pub mod note; pub mod note_file; pub mod parent_link; pub mod pomodoro; +pub mod pool_question; pub mod preferences; pub mod profile; pub mod question_image; @@ -25,6 +26,7 @@ pub mod role; pub mod session; pub mod session_attendance; pub mod settings; +pub mod solution; pub mod subject; pub mod term; pub mod timestamp; diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs new file mode 100644 index 0000000..e7e7be6 --- /dev/null +++ b/src/domain/pool_question.rs @@ -0,0 +1,457 @@ +//! A student-asked question on its way into the school-wide question pool. +//! Born `pending` (visible to its asker and to teacher+, who run the approval +//! queue); a teacher+ approval flips it to `approved`, which publishes it to +//! the whole school for everyone to read and offer solutions on. Approved +//! content is frozen — edits after approval would bypass moderation — so the +//! only post-approval change is deletion (asker or teacher+), which takes the +//! question's solutions with it. An optional photo of the problem rides on +//! the row as metadata (`image_*`); the bytes live on disk under +//! [`crate::config::Config::files_path`] in a file named by `image_file` — a +//! fresh server-generated ULID per upload. The web layer owns the blob I/O; +//! this module owns the rows. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN}; +use crate::database::{Database, POOL_QUESTION_TABLE}; +use crate::domain::note_file::FileContentType; +use crate::domain::solution::Solution; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_required; + +/// The two lifecycle states. `pending`: awaiting teacher+ approval, visible +/// only to the asker and to teacher+. `approved`: in the pool, school-wide. +/// Rejection is not a state — a teacher+ simply deletes the question. +pub const STATUS_PENDING: &str = "pending"; +pub const STATUS_APPROVED: &str = "approved"; +pub const POOL_QUESTION_STATUSES: [&str; 2] = [STATUS_PENDING, STATUS_APPROVED]; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PoolQuestionId(RecordId); + +impl PoolQuestionId { + pub fn generate() -> Self { + Self(RecordId::new(POOL_QUESTION_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(POOL_QUESTION_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PoolQuestionTitle(String); + +impl PoolQuestionTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_POOL_QUESTION_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PoolQuestionBody(String); + +impl PoolQuestionBody { + pub fn try_new(value: &str) -> Result { + validate_required("body", value, MAX_POOL_QUESTION_BODY_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct PoolQuestion { + id: PoolQuestionId, + asker: UserId, + title: PoolQuestionTitle, + body: PoolQuestionBody, + status: String, + asked_at: Timestamp, + approved_by: Option, + /// The photo's on-disk blob name — a fresh ULID every upload; `None` when + /// the question carries no image. + image_file: Option, + image_content_type: Option, + image_size: Option, +} + +impl PoolQuestion { + pub fn new(asker: &UserId, title: PoolQuestionTitle, body: PoolQuestionBody) -> Self { + Self { + id: PoolQuestionId::generate(), + asker: asker.clone(), + title, + body, + status: STATUS_PENDING.to_string(), + asked_at: Timestamp::now(), + approved_by: None, + image_file: None, + image_content_type: None, + image_size: None, + } + } + + pub fn get_id(&self) -> &PoolQuestionId { + &self.id + } + + pub fn get_asker(&self) -> &UserId { + &self.asker + } + + pub fn get_title(&self) -> &PoolQuestionTitle { + &self.title + } + + pub fn get_body(&self) -> &PoolQuestionBody { + &self.body + } + + pub fn get_status(&self) -> &str { + &self.status + } + + pub fn is_approved(&self) -> bool { + self.status == STATUS_APPROVED + } + + pub fn get_asked_at(&self) -> Timestamp { + self.asked_at + } + + pub fn get_approved_by(&self) -> Option<&UserId> { + self.approved_by.as_ref() + } + + pub fn get_image_file(&self) -> Option<&str> { + self.image_file.as_deref() + } + + pub fn get_image_content_type(&self) -> Option<&FileContentType> { + self.image_content_type.as_ref() + } + + pub fn get_image_size(&self) -> Option { + self.image_size + } + + pub async fn insert(self, db: &Database) -> Result { + let created: Option = db.create(self.id.record()).content(self).await?; + created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) + } + + pub async fn read(id: &PoolQuestionId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every question, newest first — the teacher+ view (approval queue and + /// pool in one list). + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The pool as a non-staff user sees it, newest first: every approved + /// question, plus the caller's own pending ones. + pub async fn list_visible_to( + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ + ORDER BY asked_at DESC, id DESC", + ) + .bind(("approved", STATUS_APPROVED)) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Publish a pending question into the pool, stamping who approved it. + /// The `WHERE status = $pending` guard makes the transition atomic: of two + /// racing approvals exactly one wins, and an approve can never land on a + /// question deleted mid-flight. `None` = the question wasn't pending + /// (already approved, or gone) — the caller sorts out which. + pub async fn approve( + id: &PoolQuestionId, + approver: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $q SET status = $approved, approved_by = $by \ + WHERE status = $pending RETURN AFTER", + ) + .bind(("q", id.record())) + .bind(("approved", STATUS_APPROVED)) + .bind(("by", approver.record())) + .bind(("pending", STATUS_PENDING)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Point the question at a freshly written image blob. Guarded on + /// `pending` for the same reason approval is: an image landing after + /// approval would put unmoderated bytes in the pool, so an upload that + /// loses the race gets `None` (and the caller takes the orphan blob back + /// off disk). Returns the *before* row — its `image_file` is the replaced + /// blob the caller must remove. + pub async fn set_image( + id: &PoolQuestionId, + file: &str, + content_type: &FileContentType, + size: i64, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ + WHERE status = $pending RETURN BEFORE", + ) + .bind(("q", id.record())) + .bind(("file", file.to_string())) + .bind(("ct", content_type.clone())) + .bind(("size", size)) + .bind(("pending", STATUS_PENDING)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Detach the question's image (pending only, like `set_image`). Returns + /// the *before* row — its `image_file` is the blob the caller must remove. + pub async fn clear_image( + id: &PoolQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ + WHERE status = $pending RETURN BEFORE", + ) + .bind(("q", id.record())) + .bind(("pending", STATUS_PENDING)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Delete the question and its solutions in one transaction, returning + /// the removed rows — the question's *and* the swept solutions' — so the + /// caller can take every image blob off disk (solutions carry photos too, + /// and a row-only sweep would strand theirs forever). + pub async fn delete( + id: &PoolQuestionId, + db: &Database, + ) -> Result)>, AppError> { + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE solution WHERE question = $q RETURN BEFORE; + DELETE $q RETURN BEFORE; + COMMIT TRANSACTION;", + ) + .bind(("q", id.record())) + .await? + .check()?; + // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. + let solutions = result.take::>(1)?; + Ok(result + .take::>(2)? + .into_iter() + .next() + .map(|question| (question, solutions))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database; + use crate::domain::solution::{Solution, SolutionBody}; + + fn question(asker: &UserId) -> PoolQuestion { + PoolQuestion::new( + asker, + PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), + PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), + ) + } + + #[tokio::test] + async fn approval_is_a_one_way_race_safe_transition() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + + let q = question(&asker).insert(&db).await.unwrap(); + assert_eq!(q.get_status(), STATUS_PENDING); + assert!(q.get_approved_by().is_none()); + + let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + assert!(approved.is_approved()); + assert_eq!(approved.get_approved_by(), Some(&teacher)); + + // A second approval finds nothing pending. + assert!( + PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .is_none() + ); + // And a missing question approves to None, not an error. + assert!( + PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn visibility_hides_others_pending_questions() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let other = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + + let pending = question(&asker).insert(&db).await.unwrap(); + let published = question(&other).insert(&db).await.unwrap(); + PoolQuestion::approve(published.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + + // The asker sees their own pending question plus the pool; a stranger + // sees only the pool; the teacher view (list_all) sees everything. + assert_eq!(PoolQuestion::list_visible_to(&asker, &db).await.unwrap().len(), 2); + let stranger_view = PoolQuestion::list_visible_to(&other, &db).await.unwrap(); + assert_eq!(stranger_view.len(), 1); + assert_eq!(stranger_view[0].get_id(), published.get_id()); + assert_eq!(PoolQuestion::list_all(&db).await.unwrap().len(), 2); + assert!( + PoolQuestion::read(pending.get_id(), &db) + .await + .unwrap() + .is_some() + ); + } + + #[tokio::test] + async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + let png = FileContentType::try_new("image/png").unwrap(); + + let q = question(&asker).insert(&db).await.unwrap(); + let before = PoolQuestion::set_image(q.get_id(), "blob_a", &png, 3, &db) + .await + .unwrap() + .unwrap(); + assert!(before.get_image_file().is_none()); + + // A replace reports the old blob for cleanup. + let before = PoolQuestion::set_image(q.get_id(), "blob_b", &png, 5, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_a")); + let stored = PoolQuestion::read(q.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_image_file(), Some("blob_b")); + assert_eq!(stored.get_image_size(), Some(5)); + + // Clearing reports the detached blob and empties the fields. + let before = PoolQuestion::clear_image(q.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_b")); + assert!( + PoolQuestion::read(q.get_id(), &db) + .await + .unwrap() + .unwrap() + .get_image_file() + .is_none() + ); + + // Once approved, the image is frozen with the rest of the content. + PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + assert!( + PoolQuestion::set_image(q.get_id(), "blob_c", &png, 7, &db) + .await + .unwrap() + .is_none() + ); + assert!( + PoolQuestion::clear_image(q.get_id(), &db) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn delete_cascades_solutions_and_returns_the_row() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let helper = UserId::from_key(&Ulid::new().to_string()); + + let q = question(&asker).insert(&db).await.unwrap(); + let offered = Solution::new( + q.get_id(), + &helper, + SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), + ) + .insert(&db) + .await + .unwrap(); + + // The swept solutions ride back with the question so the caller can + // take their image blobs off disk. + let (removed, swept) = PoolQuestion::delete(q.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(removed.get_id(), q.get_id()); + assert_eq!(swept.len(), 1); + assert_eq!(swept[0].get_id(), offered.get_id()); + assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none()); + assert!(Solution::list_for(q.get_id(), &db).await.unwrap().is_empty()); + + // Deleting the already-deleted is None, not an error. + assert!(PoolQuestion::delete(q.get_id(), &db).await.unwrap().is_none()); + } +} diff --git a/src/domain/solution.rs b/src/domain/solution.rs new file mode 100644 index 0000000..89b8501 --- /dev/null +++ b/src/domain/solution.rs @@ -0,0 +1,442 @@ +//! A solution offered on an approved pool question (see +//! [`crate::domain::pool_question`]). Anyone in the school — student or staff +//! — may offer one; rows list oldest first, reading as a discussion thread. +//! Solutions die with their question (the question delete cascades here). +//! Like a question, a solution may carry one photo (`image_*` metadata on the +//! row, bytes on disk under a server-generated ULID) — but unlike a question +//! it has no moderation state, so its author may edit the body and swap the +//! photo at any time; there is nothing to freeze. + +use std::collections::HashMap; + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::MAX_SOLUTION_BODY_LEN; +use crate::database::{Database, SOLUTION_TABLE}; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::PoolQuestionId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_required; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SolutionId(RecordId); + +impl SolutionId { + pub fn generate() -> Self { + Self(RecordId::new(SOLUTION_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(SOLUTION_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SolutionBody(String); + +impl SolutionBody { + pub fn try_new(value: &str) -> Result { + validate_required("body", value, MAX_SOLUTION_BODY_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Solution { + id: SolutionId, + question: PoolQuestionId, + author: UserId, + body: SolutionBody, + offered_at: Timestamp, + /// The photo's on-disk blob name — a fresh ULID every upload; `None` when + /// the solution carries no image. + image_file: Option, + image_content_type: Option, + image_size: Option, +} + +/// One `GROUP BY question` row of [`Solution::counts_for`]. +#[derive(SurrealValue)] +struct SolutionCount { + question: PoolQuestionId, + n: i64, +} + +impl Solution { + pub fn new(question: &PoolQuestionId, author: &UserId, body: SolutionBody) -> Self { + Self { + id: SolutionId::generate(), + question: question.clone(), + author: author.clone(), + body, + offered_at: Timestamp::now(), + image_file: None, + image_content_type: None, + image_size: None, + } + } + + pub fn get_id(&self) -> &SolutionId { + &self.id + } + + pub fn get_question(&self) -> &PoolQuestionId { + &self.question + } + + pub fn get_author(&self) -> &UserId { + &self.author + } + + pub fn get_body(&self) -> &SolutionBody { + &self.body + } + + pub fn get_offered_at(&self) -> Timestamp { + self.offered_at + } + + pub fn get_image_file(&self) -> Option<&str> { + self.image_file.as_deref() + } + + pub fn get_image_content_type(&self) -> Option<&FileContentType> { + self.image_content_type.as_ref() + } + + pub fn get_image_size(&self) -> Option { + self.image_size + } + + pub async fn insert(self, db: &Database) -> Result { + let created: Option = db.create(self.id.record()).content(self).await?; + created.ok_or_else(|| AppError::Internal("failed to create solution".into())) + } + + /// Read a solution only if it belongs to `question` — keeps the nested + /// route honest (a solution id under someone else's question 404s). + pub async fn read_for( + id: &SolutionId, + question: &PoolQuestionId, + db: &Database, + ) -> Result, AppError> { + let solution: Option = db.select(id.record()).await?; + Ok(solution.filter(|solution| &solution.question == question)) + } + + /// The question's solutions, oldest first — a discussion reads downward. + /// The id tiebreak keeps same-millisecond offers in a stable order (ULID + /// keys sort chronologically). + pub async fn list_for( + question: &PoolQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM solution WHERE question = $q ORDER BY offered_at ASC, id ASC") + .bind(("q", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Per-question solution tallies for a page of questions, in one grouped + /// query — a per-row `count()` would cost a query per question. Keys are + /// question record keys; a question with no solutions has no entry, so + /// the caller reads misses as zero. + pub async fn counts_for( + questions: &[PoolQuestionId], + db: &Database, + ) -> Result, AppError> { + if questions.is_empty() { + return Ok(HashMap::new()); + } + let ids: Vec = questions.iter().map(|question| question.record()).collect(); + let mut result = db + .query("SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question") + .bind(("qs", ids)) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .map(|row| (row.question.key().to_string(), row.n)) + .collect()) + } + + /// Replace the body. Unconditional (solutions have no moderation state to + /// guard, unlike a question's `pending` gate) — `None` only means the row + /// was deleted mid-flight. Authorship is the web layer's check. + pub async fn set_body( + id: &SolutionId, + body: &SolutionBody, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("UPDATE $s SET body = $b RETURN AFTER") + .bind(("s", id.record())) + .bind(("b", body.clone())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Point the solution at a freshly written image blob. Unconditional for + /// the same reason as [`Self::set_body`]. Returns the *before* row — its + /// `image_file` is the replaced blob the caller must remove; `None` means + /// the row was deleted mid-flight (the fresh blob is the caller's orphan + /// to take back off disk). + pub async fn set_image( + id: &SolutionId, + file: &str, + content_type: &FileContentType, + size: i64, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") + .bind(("s", id.record())) + .bind(("file", file.to_string())) + .bind(("ct", content_type.clone())) + .bind(("size", size)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Detach the solution's image. Returns the *before* row — its + /// `image_file` is the blob the caller must remove. + pub async fn clear_image( + id: &SolutionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ + RETURN BEFORE", + ) + .bind(("s", id.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn rows_scope_to_their_question_and_list_oldest_first() { + let db = crate::database::init_mem().await.unwrap(); + let question_a = PoolQuestionId::generate(); + let question_b = PoolQuestionId::generate(); + let author = UserId::from_key(&Ulid::new().to_string()); + + let first = Solution::new( + &question_a, + &author, + SolutionBody::try_new("Önce türevi al.").unwrap(), + ) + .insert(&db) + .await + .unwrap(); + let second = Solution::new( + &question_a, + &author, + SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), + ) + .insert(&db) + .await + .unwrap(); + + let listed = Solution::list_for(&question_a, &db).await.unwrap(); + assert_eq!(listed.len(), 2); + assert_eq!(listed[0].get_id(), first.get_id()); + assert_eq!(listed[1].get_id(), second.get_id()); + assert!(Solution::list_for(&question_b, &db).await.unwrap().is_empty()); + + // Readable under its own question, invisible under another. + assert!( + Solution::read_for(first.get_id(), &question_a, &db) + .await + .unwrap() + .is_some() + ); + assert!( + Solution::read_for(first.get_id(), &question_b, &db) + .await + .unwrap() + .is_none() + ); + + first.delete(&db).await.unwrap(); + assert_eq!(Solution::list_for(&question_a, &db).await.unwrap().len(), 1); + } + + #[tokio::test] + async fn image_set_replace_clear_report_the_replaced_blob() { + let db = crate::database::init_mem().await.unwrap(); + let question = PoolQuestionId::generate(); + let author = UserId::from_key(&Ulid::new().to_string()); + let png = FileContentType::try_new("image/png").unwrap(); + + let solution = Solution::new( + &question, + &author, + SolutionBody::try_new("Grafiği çiz.").unwrap(), + ) + .insert(&db) + .await + .unwrap(); + + let before = Solution::set_image(solution.get_id(), "blob_a", &png, 3, &db) + .await + .unwrap() + .unwrap(); + assert!(before.get_image_file().is_none()); + + // A replace reports the old blob for cleanup. + let before = Solution::set_image(solution.get_id(), "blob_b", &png, 5, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_a")); + let stored = Solution::read_for(solution.get_id(), &question, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_image_file(), Some("blob_b")); + assert_eq!(stored.get_image_size(), Some(5)); + + // Clearing reports the detached blob and empties the fields. + let before = Solution::clear_image(solution.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_b")); + assert!( + Solution::read_for(solution.get_id(), &question, &db) + .await + .unwrap() + .unwrap() + .get_image_file() + .is_none() + ); + + // A row deleted mid-flight surfaces as None, not an error. + solution.clone().delete(&db).await.unwrap(); + assert!( + Solution::set_image(solution.get_id(), "blob_c", &png, 7, &db) + .await + .unwrap() + .is_none() + ); + assert!( + Solution::clear_image(solution.get_id(), &db) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn set_body_edits_in_place() { + let db = crate::database::init_mem().await.unwrap(); + let question = PoolQuestionId::generate(); + let author = UserId::from_key(&Ulid::new().to_string()); + + let solution = Solution::new( + &question, + &author, + SolutionBody::try_new("İlk deneme.").unwrap(), + ) + .insert(&db) + .await + .unwrap(); + + let edited = Solution::set_body( + solution.get_id(), + &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), + &db, + ) + .await + .unwrap() + .unwrap(); + assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); + assert_eq!(edited.get_id(), solution.get_id()); + + // Editing a missing solution is None, not an error. + assert!( + Solution::set_body( + &SolutionId::generate(), + &SolutionBody::try_new("boş").unwrap(), + &db, + ) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn counts_for_groups_per_question() { + let db = crate::database::init_mem().await.unwrap(); + let two = PoolQuestionId::generate(); + let one = PoolQuestionId::generate(); + let none = PoolQuestionId::generate(); + let author = UserId::from_key(&Ulid::new().to_string()); + + for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { + for body in bodies { + Solution::new(question, &author, SolutionBody::try_new(body).unwrap()) + .insert(&db) + .await + .unwrap(); + } + } + + let counts = + Solution::counts_for(&[two.clone(), one.clone(), none.clone()], &db) + .await + .unwrap(); + assert_eq!(counts.get(two.key()), Some(&2)); + assert_eq!(counts.get(one.key()), Some(&1)); + // No solutions = no entry; the caller reads the miss as zero. + assert_eq!(counts.get(none.key()), None); + assert!(Solution::counts_for(&[], &db).await.unwrap().is_empty()); + } + + #[tokio::test] + async fn body_rules() { + assert!(SolutionBody::try_new("").is_err()); + assert!(SolutionBody::try_new(" ").is_err()); + assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err()); + assert_eq!( + SolutionBody::try_new("Kısmi integrasyon.").unwrap().as_str(), + "Kısmi integrasyon." + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index bf16031..b9ad7b6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( @@ -46,6 +46,7 @@ use crate::state::AppState; (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (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"), + (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), (name = "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 { .nest("/marks", web::marks::routes()) .nest("/work", web::work::routes()) .nest("/pomodoro", web::pomodoro::routes()) + .nest("/questions", web::questions::routes()) .nest("/attendance", web::attendance::routes()) .nest("/settings", web::settings::routes()) .nest("/subjects", web::subjects::routes()) diff --git a/src/web/exams.rs b/src/web/exams.rs index 8795240..bba4cb6 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -3,10 +3,9 @@ use std::time::Duration; use axum::Json; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; -use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; -use axum::http::{HeaderValue, StatusCode}; +use axum::http::StatusCode; +use axum::response::Response; use axum::response::sse::{Event, KeepAlive, Sse}; -use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use tokio_stream::wrappers::IntervalStream; use tokio_stream::{Stream, StreamExt}; @@ -15,8 +14,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{ - EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, QUESTION_IMAGE_CONTENT_TYPES, - UPLOAD_BODY_OVERHEAD_BYTES, + EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES, }; use crate::database::Database; use crate::domain::course::Course; @@ -44,7 +42,8 @@ use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::subjects::subject_in_course; use super::{ CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm, - blob_path, check_not_past, paginate, person_map, read_upload, remove_blob, set_or_clear, + blob_path, check_not_past, image_content_type, paginate, person_map, read_upload, remove_blob, + set_or_clear, }; /// Serializes the exam subsystem's cross-record check-then-writes, which @@ -1779,19 +1778,6 @@ async fn ensure_question_content_visible( Ok(()) } -/// The declared content type, held to the raster allowlist — SVG stays out -/// (it can script) since these bytes are rendered inline to whole classes. -fn image_content_type(raw: &str) -> Result { - let content_type = FileContentType::try_new(raw)?; - if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "content_type", - reason: "must be image/png, image/jpeg, image/webp, or image/gif", - })); - } - Ok(content_type) -} - /// The whole image write tail, shared by both upload endpoints: new blob to /// disk, row UPSERT (the deterministic per-slot id makes it a replace), then /// the replaced blob off disk. A failed row write takes the fresh blob back @@ -1830,31 +1816,9 @@ async fn store_image( } } -/// The stored bytes as an inline-displayable response: the declared (and -/// allowlisted) content type, `nosniff`, and `no-store` — exam content has no -/// business in shared caches, and a replaced image must not linger. +/// The stored bytes, served inline via [`super::serve_inline_blob`]. async fn serve_image(st: &AppState, image: &QuestionImage) -> Result { - let bytes = tokio::fs::read(blob_path(&st.files_path, image.get_file())) - .await - .map_err(|err| { - // The row exists but its blob doesn't — server-side damage (a - // lost volume path), not a client 404. - AppError::Internal(format!( - "missing blob for question image {}: {err}", - image.get_file() - )) - })?; - let content_type = HeaderValue::from_str(image.get_content_type().as_str()) - .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); - Ok(( - [ - (CONTENT_TYPE, content_type), - (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), - (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), - ], - bytes, - ) - .into_response()) + super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await } /// Attach (or replace) a question's illustration — any question kind may diff --git a/src/web/mod.rs b/src/web/mod.rs index 6f040f2..9178b00 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -13,6 +13,7 @@ pub mod marks; pub mod messages; pub mod notes; pub mod pomodoro; +pub mod questions; pub mod sessions; pub mod settings; pub mod subjects; @@ -35,12 +36,15 @@ use std::path::{Path as FsPath, PathBuf}; use axum::extract::Multipart; use axum::extract::multipart::MultipartError; -use axum::http::StatusCode; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; +use axum::http::{HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Deserializer}; use utoipa::ToSchema; -use crate::constant::SCHEDULE_PAST_GRACE_MS; +use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS}; use crate::database::Database; +use crate::domain::note_file::FileContentType; use crate::domain::parent_link::ParentLink; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -140,6 +144,48 @@ pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { } } +/// The declared content type of an inline-displayed image upload, held to the +/// raster allowlist — SVG stays out (it can script) since these bytes are +/// rendered inline to whole classes. Shared by exam question images and pool +/// question photos. +pub(crate) fn image_content_type(raw: &str) -> Result { + let content_type = FileContentType::try_new(raw)?; + if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "content_type", + reason: "must be image/png, image/jpeg, image/webp, or image/gif", + })); + } + Ok(content_type) +} + +/// A stored blob as an inline-displayable response: the declared (and +/// allowlisted) content type, `nosniff`, and `no-store` — moderated/exam +/// content has no business in shared caches, and a replaced image must not +/// linger. +pub(crate) async fn serve_inline_blob( + files_path: &FsPath, + file: &str, + content_type: &FileContentType, +) -> Result { + let bytes = tokio::fs::read(blob_path(files_path, file)).await.map_err(|err| { + // The row exists but its blob doesn't — server-side damage (a lost + // volume path), not a client 404. + AppError::Internal(format!("missing blob for image {file}: {err}")) + })?; + let content_type = HeaderValue::from_str(content_type.as_str()) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); + Ok(( + [ + (CONTENT_TYPE, content_type), + (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), + (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), + ], + bytes, + ) + .into_response()) +} + /// Multipart read failures: the route-level body cap maps to 413 like the /// school-limit check; anything else is a malformed body. pub(crate) fn multipart_error(err: MultipartError) -> AppError { diff --git a/src/web/questions.rs b/src/web/questions.rs new file mode 100644 index 0000000..ce46028 --- /dev/null +++ b/src/web/questions.rs @@ -0,0 +1,920 @@ +//! The school question pool: students ask (optionally with a photo of the +//! problem), teacher+ approve, and every approved question is readable — and +//! answerable — by the whole school. Parents stay out (they observe reports, +//! they don't take part). Pending questions are visible only to their asker +//! and to teacher+ (the approval queue); approval freezes the content, so the +//! only edit ever needed post-approval is deletion — which is also how a +//! teacher rejects: there is no "rejected" state to manage. Solutions are the +//! opposite: unmoderated, so their author may edit the body and attach, +//! replace, or drop one photo at any time — moderation there is delete-only. + +use axum::Json; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::http::StatusCode; +use axum::response::Response; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::domain::pool_question::{ + POOL_QUESTION_STATUSES, PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, +}; +use crate::domain::role::Role; +use crate::domain::settings::Settings; +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; +use crate::domain::user::User; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{ + CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, + blob_path, image_content_type, paginate, person_map, read_upload, remove_blob, + serve_inline_blob, +}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(ask_question, list_questions)) + .routes(routes!(get_question, delete_question)) + .routes(routes!(approve_question)) + .routes(routes!(offer_solution, list_solutions)) + .routes(routes!(delete_solution, edit_solution)) + // The image routes get their own HTTP body cap, like the note-file + // ones: the server-wide hard ceiling plus multipart framing headroom. + .merge( + OpenApiRouter::new() + .routes(routes!(upload_image, get_image, delete_image)) + .routes(routes!( + upload_solution_image, + get_solution_image, + delete_solution_image + )) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )), + ) +} + +/// A 404 unless `user` may see `question`: approved questions are +/// school-wide; a pending one exists only for its asker and for teacher+ +/// (the approval queue) — everyone else must not even learn it exists. +fn ensure_visible(question: &PoolQuestion, user: &User) -> Result<(), AppError> { + if question.is_approved() + || user.get_role().at_least(Role::Teacher) + || question.get_asker() == user.get_id() + { + return Ok(()); + } + Err(AppError::NotFound) +} + +/// The shared front half of the asker-only, pending-only writes (image +/// upload/removal): 404 invisible, 403 not the asker, 409 already approved. +fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), AppError> { + ensure_visible(question, user)?; + if question.get_asker() != user.get_id() { + return Err(AppError::Forbidden( + "only the asker may change the question's image", + )); + } + if question.is_approved() { + return Err(AppError::Conflict( + "the question is approved — its content is frozen", + )); + } + Ok(()) +} + +async fn question_or_404(st: &AppState, id: &str) -> Result { + PoolQuestion::read(&PoolQuestionId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound) +} + +#[derive(Deserialize, ToSchema)] +struct AskQuestion { + #[schema(example = "Bu integrali çözemedim")] + title: String, + #[schema(example = "∫x·eˣ dx nasıl adım adım çözülür?")] + body: String, +} + +#[derive(Deserialize, ToSchema)] +struct OfferSolution { + #[schema(example = "Kısmi integrasyon: u = x, dv = eˣ dx …")] + body: String, +} + +#[derive(Deserialize, IntoParams)] +struct PoolQuestionFilter { + /// Narrow to one status: `pending` (for a student: own unapproved + /// questions; for teacher+: the approval queue) or `approved` (the pool). + /// Omit for both. + #[param(example = "pending")] + status: Option, +} + +/// A stored pool photo's metadata — a question's or a solution's; the bytes +/// come from `GET /questions/{id}/image` or +/// `GET /questions/{id}/solutions/{sid}/image`. +#[derive(Serialize, ToSchema)] +struct PoolImageMeta { + #[schema(example = "image/jpeg")] + content_type: String, + /// Byte size of the stored image. + #[schema(example = 204_800)] + size: i64, +} + +/// A pool question. `status` is `pending` (awaiting approval — visible only +/// to the asker and teacher+) or `approved` (in the school-wide pool). +#[derive(Serialize, ToSchema)] +struct PoolQuestionResponse { + id: String, + /// The student who asked. + asker: PersonRef, + title: String, + body: String, + #[schema(example = "approved")] + status: String, + /// When it was asked, UTC unix-milliseconds (server-stamped). + asked_at: i64, + /// Who approved it; `null` while pending. + approved_by: Option, + /// The attached photo's metadata; `null` when there is none. Bytes at + /// `GET /questions/{id}/image`. + image: Option, + /// How many solutions the question carries — so a list can show activity + /// without a per-question round trip. + solution_count: i64, +} + +impl PoolQuestionResponse { + fn new( + question: &PoolQuestion, + people: &std::collections::HashMap, + solution_count: i64, + ) -> Self { + Self { + id: question.get_id().key().to_string(), + asker: PersonRef::resolve(people, question.get_asker()), + title: question.get_title().as_str().to_string(), + body: question.get_body().as_str().to_string(), + status: question.get_status().to_string(), + asked_at: question.get_asked_at().as_millis(), + approved_by: question + .get_approved_by() + .map(|approver| PersonRef::resolve(people, approver)), + image: question.get_image_content_type().map(|content_type| { + PoolImageMeta { + content_type: content_type.as_str().to_string(), + size: question.get_image_size().unwrap_or(0), + } + }), + solution_count, + } + } +} + +/// One offered solution on a pool question. +#[derive(Serialize, ToSchema)] +struct SolutionResponse { + id: String, + /// The question this solution answers. + question: String, + /// Who offered it — any role, student to admin. + author: PersonRef, + body: String, + /// When it was offered, UTC unix-milliseconds (server-stamped). + offered_at: i64, + /// The attached photo's metadata; `null` when there is none. Bytes at + /// `GET /questions/{id}/solutions/{sid}/image`. + image: Option, +} + +impl SolutionResponse { + fn new(solution: &Solution, people: &std::collections::HashMap) -> Self { + Self { + id: solution.get_id().key().to_string(), + question: solution.get_question().key().to_string(), + author: PersonRef::resolve(people, solution.get_author()), + body: solution.get_body().as_str().to_string(), + offered_at: solution.get_offered_at().as_millis(), + image: solution.get_image_content_type().map(|content_type| { + PoolImageMeta { + content_type: content_type.as_str().to_string(), + size: solution.get_image_size().unwrap_or(0), + } + }), + } + } +} + +/// Join the askers, approvers, and solution tallies of a page of questions +/// into responses — both joins run over the page slice only, so a long pool +/// history never widens the queries. +async fn question_responses( + questions: &[PoolQuestion], + st: &AppState, +) -> Result, AppError> { + let ids = questions.iter().flat_map(|question| { + std::iter::once(question.get_asker().clone()) + .chain(question.get_approved_by().cloned()) + }); + let people = person_map(ids, &st.db).await?; + let question_ids: Vec = questions + .iter() + .map(|question| question.get_id().clone()) + .collect(); + let counts = Solution::counts_for(&question_ids, &st.db).await?; + Ok(questions + .iter() + .map(|question| { + let count = counts.get(question.get_id().key()).copied().unwrap_or(0); + PoolQuestionResponse::new(question, &people, count) + }) + .collect()) +} + +/// Ask a question. Students only — the pool exists for students to get help; +/// staff answer, they don't ask. Born `pending`: invisible to the school +/// until a teacher+ approves it, so nothing unmoderated ever reaches the +/// pool. Attach a photo of the problem afterwards via +/// `POST /questions/{id}/image` (only while pending). +#[utoipa::path( + post, + path = "/", + tag = "questions", + security(("session_cookie" = [])), + request_body = AskQuestion, + responses( + (status = 201, description = "Question created, pending approval", body = PoolQuestionResponse), + (status = 400, description = "Invalid title or body", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role", body = ErrorResponse), + ), +)] +async fn ask_question( + State(st): State, + CurrentUser(user): CurrentUser, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + if user.get_role() != Role::Student { + return Err(AppError::Forbidden("only students ask pool questions")); + } + let title = PoolQuestionTitle::try_new(&req.title)?; + let body = PoolQuestionBody::try_new(&req.body)?; + let question = PoolQuestion::new(user.get_id(), title, body) + .insert(&st.db) + .await?; + let responses = question_responses(std::slice::from_ref(&question), &st).await?; + let response = responses + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to render the created question".into()))?; + Ok((StatusCode::CREATED, Json(response))) +} + +/// The question pool, newest first. Everyone (parents excepted) sees every +/// `approved` question; `pending` ones appear only to their asker and to +/// teacher+ — so for a teacher, `?status=pending` is the approval queue. +/// Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/", + tag = "questions", + security(("session_cookie" = [])), + params(PoolQuestionFilter, PageParams), + responses( + (status = 200, description = "A page of the questions visible to the caller", body = Page), + (status = 400, description = "Unknown status, or invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + ), +)] +async fn list_questions( + State(st): State, + RequireStudent(user): RequireStudent, + Query(filter): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + if let Some(ref status) = filter.status + && !POOL_QUESTION_STATUSES.contains(&status.as_str()) + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "status", + reason: "must be one of: pending, approved", + })); + } + + let mut questions = if user.get_role().at_least(Role::Teacher) { + PoolQuestion::list_all(&st.db).await? + } else { + PoolQuestion::list_visible_to(user.get_id(), &st.db).await? + }; + if let Some(ref status) = filter.status { + questions.retain(|question| question.get_status() == status); + } + + let total = questions.len() as i64; + let items = question_responses(paginate(&questions, limit, offset), &st).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// One question. Approved questions are school-wide; a pending one 404s for +/// everyone but its asker and teacher+. +#[utoipa::path( + get, + path = "/{id}", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + responses( + (status = 200, description = "The question", body = PoolQuestionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), + ), +)] +async fn get_question( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, +) -> Result, AppError> { + let question = question_or_404(&st, &id).await?; + ensure_visible(&question, &user)?; + let responses = question_responses(std::slice::from_ref(&question), &st).await?; + let response = responses + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to render the question".into()))?; + Ok(Json(response)) +} + +/// Approve a pending question into the school-wide pool (teacher+), +/// stamping the approver. One-way: approved content is frozen, and there is +/// no "rejected" state — to turn a question down, delete it. +#[utoipa::path( + post, + path = "/{id}/approve", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + responses( + (status = 200, description = "The question, now approved", body = PoolQuestionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such question", body = ErrorResponse), + (status = 409, description = "Already approved", body = ErrorResponse), + ), +)] +async fn approve_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + let approved = PoolQuestion::approve(&PoolQuestionId::from_key(&id), user.get_id(), &st.db) + .await?; + let question = match approved { + Some(question) => question, + // Nothing was pending under that id: either it's already approved + // (409) or it never existed / was deleted (404). + None => { + question_or_404(&st, &id).await?; + return Err(AppError::Conflict("the question is already approved")); + } + }; + let responses = question_responses(std::slice::from_ref(&question), &st).await?; + let response = responses + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to render the approved question".into()))?; + Ok(Json(response)) +} + +/// Delete a question — the asker withdrawing their own, or teacher+ +/// moderating (this is also how a pending question is rejected). Takes the +/// question's solutions and every image blob — its own and its solutions' — +/// with it. +#[utoipa::path( + delete, + path = "/{id}", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + responses( + (status = 204, description = "Deleted, solutions included"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the asker (and not teacher+)", body = ErrorResponse), + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), + ), +)] +async fn delete_question( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, +) -> Result { + let question = question_or_404(&st, &id).await?; + ensure_visible(&question, &user)?; + if question.get_asker() != user.get_id() && !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden( + "only the asker or a teacher+ may delete a question", + )); + } + let (removed, swept) = PoolQuestion::delete(question.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + // Rows went first (in one transaction); now every blob they pointed at — + // the question's photo and each swept solution's — comes off disk. + if let Some(file) = removed.get_image_file() { + remove_blob(&st.files_path, file).await; + } + for solution in &swept { + if let Some(file) = solution.get_image_file() { + remove_blob(&st.files_path, file).await; + } + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- the question's photo --------------------------------------------------- +// One optional image per question — the snapshot of the problem sheet. Bytes +// on disk under a server-generated ULID, metadata on the question row itself. +// Asker-only, and only while pending: an image landing after approval would +// put unmoderated bytes in the pool, so approval freezes it with the text. + +/// Attach (or replace) the question's photo. Asker only, while the question +/// is still `pending` — approval freezes content, image included. +/// `multipart/form-data` with the image under a `file` field; the declared +/// content type must be `image/png`, `image/jpeg`, `image/webp`, or +/// `image/gif` (rasters only — no SVG), the bytes at most the school's +/// `max_file_bytes` (settings). +#[utoipa::path( + post, + path = "/{id}/image", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = PoolImageMeta), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the asker", body = ErrorResponse), + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), + (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let question = question_or_404(&st, &id).await?; + ensure_asker_editable(&question, &user)?; + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + + // Blob first, row second — a stored row always points at a real blob. + let file = ulid::Ulid::new().to_string(); + let path = blob_path(&st.files_path, &file); + tokio::fs::write(&path, &upload.data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; + let size = upload.data.len() as i64; + match PoolQuestion::set_image(question.get_id(), &file, &content_type, size, &st.db).await { + // The guarded UPDATE found the question still pending: point-of-truth + // write done; the replaced blob (if any) comes off disk. + Ok(Some(before)) => { + if let Some(replaced) = before.get_image_file() { + remove_blob(&st.files_path, replaced).await; + } + Ok(( + StatusCode::CREATED, + Json(PoolImageMeta { + content_type: content_type.as_str().to_string(), + size, + }), + )) + } + // Approved or deleted mid-upload — the fresh blob is an orphan. + Ok(None) => { + let _ = tokio::fs::remove_file(&path).await; + Err(AppError::Conflict("the question is no longer pending")) + } + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} + +/// The question's photo bytes. Access follows the question itself: approved → +/// school-wide, pending → asker and teacher+ only. +#[utoipa::path( + get, + path = "/{id}/image", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), + ), +)] +async fn get_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, +) -> Result { + let question = question_or_404(&st, &id).await?; + ensure_visible(&question, &user)?; + match (question.get_image_file(), question.get_image_content_type()) { + (Some(file), Some(content_type)) => { + serve_inline_blob(&st.files_path, file, content_type).await + } + _ => Err(AppError::NotFound), + } +} + +/// Remove the question's photo. Asker only, while still `pending` — after +/// approval the content (image included) is frozen. +#[utoipa::path( + delete, + path = "/{id}/image", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + responses( + (status = 204, description = "Image removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the asker", body = ErrorResponse), + (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), + (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), + ), +)] +async fn delete_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, +) -> Result { + let question = question_or_404(&st, &id).await?; + ensure_asker_editable(&question, &user)?; + if question.get_image_file().is_none() { + return Err(AppError::NotFound); + } + let before = PoolQuestion::clear_image(question.get_id(), &st.db) + .await? + .ok_or(AppError::Conflict("the question is no longer pending"))?; + if let Some(file) = before.get_image_file() { + remove_blob(&st.files_path, file).await; + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- solutions -------------------------------------------------------------- + +/// The solution, provided the caller may see the question it hangs on — +/// visibility never splits below the question (a solution on a question you +/// can't see must not exist for you either). +async fn visible_solution( + st: &AppState, + user: &User, + id: &str, + sid: &str, +) -> Result { + let question = question_or_404(st, id).await?; + ensure_visible(&question, user)?; + Solution::read_for(&SolutionId::from_key(sid), question.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound) +} + +/// The shared front half of the author-only solution writes (body edit, +/// image upload/removal): 404 invisible or missing, then 403 not the author. +/// Teacher+ get no pass here — moderation stays delete-only, a teacher never +/// rewrites someone else's answer. And unlike a question there is no freeze +/// gate: solutions are unmoderated, so their authors edit anytime. +async fn author_solution( + st: &AppState, + user: &User, + id: &str, + sid: &str, +) -> Result { + let solution = visible_solution(st, user, id, sid).await?; + if solution.get_author() != user.get_id() { + return Err(AppError::Forbidden("only the author may edit a solution")); + } + Ok(solution) +} + +/// Offer a solution on an approved question. Anyone in the school may — +/// students and staff alike (parents stay read-out). Pending questions take +/// no solutions (409 for those who can see them, 404 for everyone else). +#[utoipa::path( + post, + path = "/{id}/solutions", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id")), + request_body = OfferSolution, + responses( + (status = 201, description = "Solution offered", body = SolutionResponse), + (status = 400, description = "Invalid body", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), + (status = 409, description = "The question is not approved yet", body = ErrorResponse), + ), +)] +async fn offer_solution( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let question = question_or_404(&st, &id).await?; + ensure_visible(&question, &user)?; + if !question.is_approved() { + return Err(AppError::Conflict( + "the question is not approved yet — solutions open with the pool", + )); + } + let body = SolutionBody::try_new(&req.body)?; + let solution = Solution::new(question.get_id(), user.get_id(), body) + .insert(&st.db) + .await?; + let people = person_map([user.get_id().clone()], &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(SolutionResponse::new(&solution, &people)), + )) +} + +/// The question's solutions, oldest first (a discussion reads downward). +/// Visibility follows the question. Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/solutions", + tag = "questions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Question id"), PageParams), + responses( + (status = 200, description = "A page of the question's solutions", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), + ), +)] +async fn list_solutions( + State(st): State, + RequireStudent(user): RequireStudent, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let question = question_or_404(&st, &id).await?; + ensure_visible(&question, &user)?; + let solutions = Solution::list_for(question.get_id(), &st.db).await?; + let total = solutions.len() as i64; + let slice = paginate(&solutions, limit, offset); + let people = person_map( + slice.iter().map(|solution| solution.get_author().clone()), + &st.db, + ) + .await?; + let items = slice + .iter() + .map(|solution| SolutionResponse::new(solution, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Delete a solution — its author withdrawing it, or teacher+ moderating. +/// Takes the solution's image blob with it. +#[utoipa::path( + delete, + path = "/{id}/solutions/{sid}", + tag = "questions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Question id"), + ("sid" = String, Path, description = "Solution id"), + ), + responses( + (status = 204, description = "Solution deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the author (and not teacher+)", body = ErrorResponse), + (status = 404, description = "No such question or solution", body = ErrorResponse), + ), +)] +async fn delete_solution( + State(st): State, + RequireStudent(user): RequireStudent, + Path((id, sid)): Path<(String, String)>, +) -> Result { + let solution = visible_solution(&st, &user, &id, &sid).await?; + if solution.get_author() != user.get_id() && !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden( + "only the author or a teacher+ may delete a solution", + )); + } + // Row first, blob after — a crash in between strands at worst an + // unreachable file. + let deleted = solution.delete(&st.db).await?; + if let Some(file) = deleted.get_image_file() { + remove_blob(&st.files_path, file).await; + } + Ok(StatusCode::NO_CONTENT) +} + +/// Edit a solution's body — its author reworking their own answer. Author +/// only, teacher+ included out: moderation stays delete-only (a moderator +/// removes a bad solution, never rewrites someone else's words under their +/// name). No freeze either — solutions are unmoderated, so editing stays +/// open for as long as the solution lives. +#[utoipa::path( + patch, + path = "/{id}/solutions/{sid}", + tag = "questions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Question id"), + ("sid" = String, Path, description = "Solution id"), + ), + request_body = OfferSolution, + responses( + (status = 200, description = "The updated solution", body = SolutionResponse), + (status = 400, description = "Invalid body", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the author", body = ErrorResponse), + (status = 404, description = "No such question or solution", body = ErrorResponse), + ), +)] +async fn edit_solution( + State(st): State, + RequireStudent(user): RequireStudent, + Path((id, sid)): Path<(String, String)>, + Json(req): Json, +) -> Result, AppError> { + let solution = author_solution(&st, &user, &id, &sid).await?; + let body = SolutionBody::try_new(&req.body)?; + let updated = Solution::set_body(solution.get_id(), &body, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let people = person_map([user.get_id().clone()], &st.db).await?; + Ok(Json(SolutionResponse::new(&updated, &people))) +} + +// ---- the solution's photo --------------------------------------------------- +// One optional image per solution — the photographed worked steps or diagram. +// Same blob discipline as the question's photo (bytes on disk under a +// server-generated ULID, metadata on the row), but author-only *anytime*: +// solutions carry no moderation state, so there is no approval to freeze +// them. + +/// Attach (or replace) the solution's photo. Author only — and at any time, +/// since solutions are never frozen. `multipart/form-data` with the image +/// under a `file` field; the declared content type must be `image/png`, +/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the +/// bytes at most the school's `max_file_bytes` (settings). +#[utoipa::path( + post, + path = "/{id}/solutions/{sid}/image", + tag = "questions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Question id"), + ("sid" = String, Path, description = "Solution id"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = PoolImageMeta), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the author", body = ErrorResponse), + (status = 404, description = "No such question or solution", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_solution_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path((id, sid)): Path<(String, String)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let solution = author_solution(&st, &user, &id, &sid).await?; + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + + // Blob first, row second — a stored row always points at a real blob. + let file = ulid::Ulid::new().to_string(); + let path = blob_path(&st.files_path, &file); + tokio::fs::write(&path, &upload.data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; + let size = upload.data.len() as i64; + match Solution::set_image(solution.get_id(), &file, &content_type, size, &st.db).await { + // Row write done; the replaced blob (if any) comes off disk. + Ok(Some(before)) => { + if let Some(replaced) = before.get_image_file() { + remove_blob(&st.files_path, replaced).await; + } + Ok(( + StatusCode::CREATED, + Json(PoolImageMeta { + content_type: content_type.as_str().to_string(), + size, + }), + )) + } + // Deleted mid-upload — the fresh blob is an orphan. + Ok(None) => { + let _ = tokio::fs::remove_file(&path).await; + Err(AppError::NotFound) + } + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} + +/// The solution photo's bytes. Access follows the question the solution +/// hangs on — in practice school-wide, since solutions exist only on +/// approved questions. +#[utoipa::path( + get, + path = "/{id}/solutions/{sid}/image", + tag = "questions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Question id"), + ("sid" = String, Path, description = "Solution id"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires student role or higher", body = ErrorResponse), + (status = 404, description = "No such question, solution, or image", body = ErrorResponse), + ), +)] +async fn get_solution_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path((id, sid)): Path<(String, String)>, +) -> Result { + let solution = visible_solution(&st, &user, &id, &sid).await?; + match (solution.get_image_file(), solution.get_image_content_type()) { + (Some(file), Some(content_type)) => { + serve_inline_blob(&st.files_path, file, content_type).await + } + _ => Err(AppError::NotFound), + } +} + +/// Remove the solution's photo. Author only, anytime — solutions are never +/// frozen. +#[utoipa::path( + delete, + path = "/{id}/solutions/{sid}/image", + tag = "questions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Question id"), + ("sid" = String, Path, description = "Solution id"), + ), + responses( + (status = 204, description = "Image removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the author", body = ErrorResponse), + (status = 404, description = "No such question, solution, or image", body = ErrorResponse), + ), +)] +async fn delete_solution_image( + State(st): State, + RequireStudent(user): RequireStudent, + Path((id, sid)): Path<(String, String)>, +) -> Result { + let solution = author_solution(&st, &user, &id, &sid).await?; + if solution.get_image_file().is_none() { + return Err(AppError::NotFound); + } + let before = Solution::clear_image(solution.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if let Some(file) = before.get_image_file() { + remove_blob(&st.files_path, file).await; + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/tests/integration.rs b/tests/integration.rs index 4de2954..d72ee3d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11432,3 +11432,342 @@ async fn stale_parent_link_is_inert_after_role_change() { ); } } + +// --- the question pool --------------------------------------------------- + +/// The pool lifecycle end to end: a student asks (pending — invisible to +/// other students, listed for teachers), a teacher approves (one-way, 409 on +/// repeat), the pool opens school-wide, anyone offers solutions, and +/// moderation deletes cascade. +#[tokio::test] +async fn question_pool_lifecycle() { + let (app, db) = app_and_db().await; + let asker = login(&app, "ali").await; + let stranger = login(&app, "veli").await; + let teacher = login_as(&app, &db, "hoca", "teacher").await; + + // Only students ask: the teacher is refused. + let ask = json!({ "title": "Integral", "body": "∫x·eˣ dx?" }); + let res = send(&app, "POST", "/questions", Some(&teacher), Some(ask.clone())).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + let res = send(&app, "POST", "/questions", Some(&asker), Some(ask)).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["status"], "pending"); + let qid = id_of(&res.body); + + // Pending: the asker and the teacher see it; another student must not + // even learn it exists — and it takes no solutions yet. + for (cookie, visible) in [(&asker, true), (&teacher, true), (&stranger, false)] { + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(cookie), None).await; + let expected = if visible { StatusCode::OK } else { StatusCode::NOT_FOUND }; + assert_eq!(res.status, expected, "{}", res.body); + } + let offer = json!({ "body": "Kısmi integrasyon." }); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/solutions"), + Some(&asker), + Some(offer.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // The teacher's ?status=pending list is the approval queue; approval is + // teacher-gated and one-way. + let res = send(&app, "GET", "/questions?status=pending", Some(&teacher), None).await; + assert_eq!(common::total(&res.body), 1); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/approve"), + Some(&stranger), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/approve"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "approved"); + assert_eq!(res.body["approved_by"]["username"], "hoca"); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/approve"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // Approved: school-wide — the stranger reads it and answers it. + let res = send(&app, "GET", "/questions", Some(&stranger), None).await; + assert_eq!(common::total(&res.body), 1); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/solutions"), + Some(&stranger), + Some(offer), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let sid = id_of(&res.body); + + // Deleting the solution: a third party may not, its author may. + let res = send( + &app, + "DELETE", + &format!("/questions/{qid}/solutions/{sid}"), + Some(&asker), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/questions/{qid}/solutions/{sid}"), + Some(&stranger), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // Question delete (asker withdraws) cascades what's left. + let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// Parents are observers: every pool surface (list, ask, answer) is closed to +/// them. +#[tokio::test] +async fn question_pool_locks_parents_out() { + let (app, db) = app_and_db().await; + let parent = login_as(&app, &db, "anne", "parent").await; + let res = send(&app, "GET", "/questions", Some(&parent), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + "/questions", + Some(&parent), + Some(json!({ "title": "t", "body": "b" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} + +/// The question photo: asker-only upload while pending, SVG refused, bytes +/// served under the question's visibility, approval freezes the slot. +#[tokio::test] +async fn question_pool_image_upload_and_freeze() { + let (app, db) = app_and_db().await; + let asker = login(&app, "ali").await; + let stranger = login(&app, "veli").await; + let teacher = login_as(&app, &db, "hoca", "teacher").await; + + let res = send( + &app, + "POST", + "/questions", + Some(&asker), + Some(json!({ "title": "Harita", "body": "Hangi şehir?" })), + ) + .await; + let qid = id_of(&res.body); + let upload = |cookie: &str, content_type: &str| { + let uri = format!("/questions/{qid}/image"); + let body = common::multipart_file("soru.png", content_type, b"png-bytes"); + let cookie = cookie.to_string(); + let app = app.clone(); + async move { + common::send_raw( + &app, + "POST", + &uri, + Some(&cookie), + Some("multipart/form-data; boundary=hezarfen-test-boundary"), + body, + ) + .await + } + }; + + // SVG is out; the teacher isn't the asker; the asker's PNG lands. + let (status, _, _) = upload(&asker, "image/svg+xml").await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _, _) = upload(&teacher, "image/png").await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _, _) = upload(&asker, "image/png").await; + assert_eq!(status, StatusCode::CREATED); + + // Pending bytes follow pending visibility: asker yes, stranger no. + let uri = format!("/questions/{qid}/image"); + let (status, headers, bytes) = + common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], "image/png"); + assert_eq!(bytes, b"png-bytes"); + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // Approval freezes the image with the text: replace and remove both 409. + let res = send( + &app, + "POST", + &format!("/questions/{qid}/approve"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let (status, _, _) = upload(&asker, "image/png").await; + assert_eq!(status, StatusCode::CONFLICT); + let (status, _, _) = + common::send_raw(&app, "DELETE", &uri, Some(&asker), None, Vec::new()).await; + assert_eq!(status, StatusCode::CONFLICT); + + // But the approved bytes are now school-wide, and ride the question meta. + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&stranger), None).await; + assert_eq!(res.body["image"]["content_type"], "image/png"); +} + +/// The solution's photo and body stay the author's alone (no freeze — no +/// moderation state to protect), bytes follow the question's visibility, and +/// question rows tally their solutions. +#[tokio::test] +async fn solution_images_edits_and_counts() { + let (app, db) = app_and_db().await; + let asker = login(&app, "ali").await; + let helper = login(&app, "veli").await; + let teacher = login_as(&app, &db, "hoca", "teacher").await; + + // An approved question with the helper's solution under it. + let res = send( + &app, + "POST", + "/questions", + Some(&asker), + Some(json!({ "title": "Limit", "body": "x→0 iken sin(x)/x?" })), + ) + .await; + let qid = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/approve"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/questions/{qid}/solutions"), + Some(&helper), + Some(json!({ "body": "Birebir 1'e gider." })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert!(res.body["image"].is_null()); + let sid = id_of(&res.body); + + // Image writes are the author's: the asker is refused, the helper lands. + let uri = format!("/questions/{qid}/solutions/{sid}/image"); + let upload = |cookie: &str| { + let uri = uri.clone(); + let body = common::multipart_file("cozum.png", "image/png", b"png-bytes"); + let cookie = cookie.to_string(); + let app = app.clone(); + async move { + common::send_raw( + &app, + "POST", + &uri, + Some(&cookie), + Some("multipart/form-data; boundary=hezarfen-test-boundary"), + body, + ) + .await + } + }; + let (status, _, _) = upload(&asker).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _, _) = upload(&teacher).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _, _) = upload(&helper).await; + assert_eq!(status, StatusCode::CREATED); + + // Bytes follow the question's visibility — approved, so any student + // reads them — and the meta rides the solution row. + let (status, headers, bytes) = + common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], "image/png"); + assert_eq!(bytes, b"png-bytes"); + let res = send( + &app, + "GET", + &format!("/questions/{qid}/solutions"), + Some(&asker), + None, + ) + .await; + assert_eq!(res.body["items"][0]["image"]["content_type"], "image/png"); + + // Body edits are author-only too — teacher+ moderate by deleting, never + // by rewriting. + let edit = json!({ "body": "Standart limit: sin(x)/x → 1." }); + let res = send( + &app, + "PATCH", + &format!("/questions/{qid}/solutions/{sid}"), + Some(&asker), + Some(edit.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/questions/{qid}/solutions/{sid}"), + Some(&helper), + Some(edit), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["body"], "Standart limit: sin(x)/x → 1."); + assert_eq!(res.body["image"]["content_type"], "image/png"); + + // Question rows tally their solutions, in the list and the single GET. + let res = send(&app, "GET", "/questions?limit=5", Some(&asker), None).await; + assert_eq!(res.body["items"][0]["solution_count"], 1); + let res = send(&app, "GET", &format!("/questions/{qid}"), Some(&asker), None).await; + assert_eq!(res.body["solution_count"], 1); + + // The author drops the photo; a second removal finds nothing. + let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // And the question delete still sweeps everything under it. + let res = send(&app, "DELETE", &format!("/questions/{qid}"), Some(&asker), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +}