forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

questions.rs925 lines, 37.9 KiBHistoryRawDownload
1//! The school question pool: students ask (optionally with a photo of the
2//! problem), teacher+ approve, and every approved question is readable — and
3//! answerable — by the whole school. Parents stay out (they observe reports,
4//! they don't take part). Pending questions are visible only to their asker
5//! and to teacher+ (the approval queue); approval freezes the content, so the
6//! only edit ever needed post-approval is deletion — which is also how a
7//! teacher rejects: there is no "rejected" state to manage. Solutions are the
8//! opposite: unmoderated, so their author may edit the body and attach,
9//! replace, or drop one photo at any time — moderation there is delete-only.
10
11use std::collections::HashMap;
12
13use axum::Json;
14use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
15use axum::http::StatusCode;
16use axum::response::Response;
17use serde::{Deserialize, Serialize};
18use utoipa::{IntoParams, ToSchema};
19use utoipa_axum::router::OpenApiRouter;
20use utoipa_axum::routes;
21
22use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES};
23use crate::domain::pool_question::{
24 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,
25};
26use crate::domain::pool_question_image::PoolQuestionImage;
27use crate::domain::role::Role;
28use crate::domain::solution::{Solution, SolutionBody, SolutionId};
29use crate::domain::solution_image::SolutionImage;
30use crate::domain::user::User;
31use crate::error::{AppError, ErrorResponse, ValidationError};
32use crate::service::pool_question;
33use crate::service::pool_question_image;
34use crate::service::solution;
35use crate::service::solution_image;
36use crate::state::AppState;
37use crate::web::tenant_state::State;
38
39use super::{
40 CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm,
41 person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob,
42};
43
44pub fn routes() -> OpenApiRouter<AppState> {
45 OpenApiRouter::new()
46 .routes(routes!(ask_question, list_questions))
47 .routes(routes!(get_question, delete_question))
48 .routes(routes!(approve_question))
49 .routes(routes!(offer_solution, list_solutions))
50 .routes(routes!(delete_solution, edit_solution))
51 // The image routes get their own HTTP body cap, like the note-file
52 // ones: the server-wide hard ceiling plus multipart framing headroom.
53 .merge(
54 OpenApiRouter::new()
55 .routes(routes!(upload_image, get_image, delete_image))
56 .routes(routes!(
57 upload_solution_image,
58 get_solution_image,
59 delete_solution_image
60 ))
61 .layer(DefaultBodyLimit::max(
62 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
63 )),
64 )
65}
66
67/// A 404 unless `user` may see `question`: approved questions are
68/// school-wide; a pending one exists only for its asker and for teacher+
69/// (the approval queue) — everyone else must not even learn it exists.
70fn ensure_visible(question: &PoolQuestion, user: &User) -> Result<(), AppError> {
71 if question.is_approved()
72 || user.get_role().at_least(Role::Teacher)
73 || question.get_asker() == user.get_id()
74 {
75 return Ok(());
76 }
77 Err(AppError::NotFound)
78}
79
80/// The shared front half of the asker-only, pending-only writes (image
81/// upload/removal): 404 invisible, 403 not the asker, 409 already approved.
82fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), AppError> {
83 ensure_visible(question, user)?;
84 if question.get_asker() != user.get_id() {
85 return Err(AppError::Forbidden(
86 "only the asker may change the question's image",
87 ));
88 }
89 if question.is_approved() {
90 return Err(AppError::Conflict(
91 "the question is approved — its content is frozen",
92 ));
93 }
94 Ok(())
95}
96
97async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppError> {
98 pool_question::read(&st.db, &PoolQuestionId::from_key(id))
99 .await?
100 .ok_or(AppError::NotFound)
101}
102
103#[derive(Deserialize, ToSchema)]
104struct AskQuestion {
105 #[schema(example = "Bu integrali çözemedim", max_length = 200)]
106 title: String,
107 #[schema(example = "∫x·eˣ dx nasıl adım adım çözülür?", max_length = 10000)]
108 body: String,
109}
110
111#[derive(Deserialize, ToSchema)]
112struct OfferSolution {
113 #[schema(example = "Kısmi integrasyon: u = x, dv = eˣ dx …", max_length = 10000)]
114 body: String,
115}
116
117#[derive(Deserialize, IntoParams)]
118struct PoolQuestionFilter {
119 /// Narrow to one status: `pending` (for a student: own unapproved
120 /// questions; for teacher+: the approval queue) or `approved` (the pool).
121 /// Omit for both.
122 #[param(example = "pending")]
123 status: Option<String>,
124}
125
126/// A stored pool photo's metadata — a question's or a solution's; the bytes
127/// come from `GET /questions/{id}/image` or
128/// `GET /questions/{id}/solutions/{sid}/image`.
129#[derive(Serialize, ToSchema)]
130struct PoolImageMeta {
131 #[schema(example = "image/jpeg")]
132 content_type: String,
133 /// Byte size of the stored image.
134 #[schema(example = 204_800)]
135 size: i64,
136}
137
138/// A pool question. `status` is `pending` (awaiting approval — visible only
139/// to the asker and teacher+) or `approved` (in the school-wide pool).
140#[derive(Serialize, ToSchema)]
141struct PoolQuestionResponse {
142 id: String,
143 /// The student who asked.
144 asker: PersonRef,
145 title: String,
146 body: String,
147 #[schema(example = "approved")]
148 status: String,
149 /// When it was asked, UTC unix-milliseconds (server-stamped).
150 asked_at: i64,
151 /// Who approved it; `null` while pending.
152 approved_by: Option<PersonRef>,
153 /// The attached photo's metadata; `null` when there is none. Bytes at
154 /// `GET /questions/{id}/image`.
155 image: Option<PoolImageMeta>,
156 /// How many solutions the question carries — so a list can show activity
157 /// without a per-question round trip.
158 solution_count: i64,
159}
160
161impl PoolQuestionResponse {
162 fn new(
163 question: &PoolQuestion,
164 people: &std::collections::HashMap<String, PersonRef>,
165 solution_count: i64,
166 image: Option<&PoolQuestionImage>,
167 ) -> Self {
168 Self {
169 id: question.get_id().key().to_string(),
170 asker: PersonRef::resolve(people, question.get_asker()),
171 title: question.get_title().as_str().to_string(),
172 body: question.get_body().as_str().to_string(),
173 status: question.get_status().to_string(),
174 asked_at: question.get_asked_at().as_millis(),
175 approved_by: question
176 .get_approved_by()
177 .map(|approver| PersonRef::resolve(people, approver)),
178 image: image.map(|image| PoolImageMeta {
179 content_type: image.get_content_type().as_str().to_string(),
180 size: image.get_size(),
181 }),
182 solution_count,
183 }
184 }
185}
186
187/// One offered solution on a pool question.
188#[derive(Serialize, ToSchema)]
189struct SolutionResponse {
190 id: String,
191 /// The question this solution answers.
192 question: String,
193 /// Who offered it — any role, student to admin.
194 author: PersonRef,
195 body: String,
196 /// When it was offered, UTC unix-milliseconds (server-stamped).
197 offered_at: i64,
198 /// The attached photo's metadata; `null` when there is none. Bytes at
199 /// `GET /questions/{id}/solutions/{sid}/image`.
200 image: Option<PoolImageMeta>,
201}
202
203impl SolutionResponse {
204 fn new(
205 solution: &Solution,
206 people: &std::collections::HashMap<String, PersonRef>,
207 image: Option<&SolutionImage>,
208 ) -> Self {
209 Self {
210 id: solution.get_id().key().to_string(),
211 question: solution.get_question().key().to_string(),
212 author: PersonRef::resolve(people, solution.get_author()),
213 body: solution.get_body().as_str().to_string(),
214 offered_at: solution.get_offered_at().as_millis(),
215 image: image.map(|image| PoolImageMeta {
216 content_type: image.get_content_type().as_str().to_string(),
217 size: image.get_size(),
218 }),
219 }
220 }
221}
222
223/// Join the askers, approvers, and solution tallies of a page of questions
224/// into responses — both joins run over the page slice only, so a long pool
225/// history never widens the queries.
226async fn question_responses(
227 questions: &[PoolQuestion],
228 st: &AppState,
229) -> Result<Vec<PoolQuestionResponse>, AppError> {
230 let ids = questions.iter().flat_map(|question| {
231 std::iter::once(*question.get_asker()).chain(question.get_approved_by().cloned())
232 });
233 let people = person_map(ids, &st.db).await?;
234 let question_ids: Vec<PoolQuestionId> = questions
235 .iter()
236 .map(|question| *question.get_id())
237 .collect();
238 let counts = solution::counts_for(&st.db, &question_ids).await?;
239 // The photos bucket onto the page in one query, exactly like the
240 // solution tallies — never an image read per row.
241 let image_refs: Vec<&PoolQuestionId> = questions.iter().map(|q| q.get_id()).collect();
242 let mut images: HashMap<String, PoolQuestionImage> = HashMap::new();
243 for image in pool_question_image::list_for_questions(&st.db, &image_refs).await? {
244 images.insert(image.get_question().key(), image);
245 }
246 Ok(questions
247 .iter()
248 .map(|question| {
249 let count = counts.get(&question.get_id().key()).copied().unwrap_or(0);
250 let image = images.get(question.get_id().key().as_str());
251 PoolQuestionResponse::new(question, &people, count, image)
252 })
253 .collect())
254}
255
256/// Ask a question. Students only — the pool exists for students to get help;
257/// staff answer, they don't ask. Born `pending`: invisible to the school
258/// until a teacher+ approves it, so nothing unmoderated ever reaches the
259/// pool. Attach a photo of the problem afterwards via
260/// `POST /questions/{id}/image` (only while pending).
261#[utoipa::path(
262 post,
263 path = "/",
264 tag = "questions",
265 security(("session_cookie" = [])),
266 request_body = AskQuestion,
267 responses(
268 (status = 201, description = "Question created, pending approval", body = PoolQuestionResponse),
269 (status = 400, description = "Invalid title or body", body = ErrorResponse),
270 (status = 401, description = "Not authenticated", body = ErrorResponse),
271 (status = 403, description = "Requires the student role", body = ErrorResponse),
272 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
273 ),
274)]
275async fn ask_question(
276 State(st): State<AppState>,
277 CurrentUser(user): CurrentUser,
278 Json(req): Json<AskQuestion>,
279) -> Result<(StatusCode, Json<PoolQuestionResponse>), AppError> {
280 if user.get_role() != Role::Student {
281 return Err(AppError::Forbidden("only students ask pool questions"));
282 }
283 let title = PoolQuestionTitle::try_new(&req.title)?;
284 let body = PoolQuestionBody::try_new(&req.body)?;
285 let question =
286 pool_question::insert(&st.db, PoolQuestion::new(user.get_id(), title, body)).await?;
287 let responses = question_responses(std::slice::from_ref(&question), &st).await?;
288 let response = responses
289 .into_iter()
290 .next()
291 .ok_or_else(|| AppError::Internal("failed to render the created question".into()))?;
292 Ok((StatusCode::CREATED, Json(response)))
293}
294
295/// The question pool, newest first. Everyone (parents excepted) sees every
296/// `approved` question; `pending` ones appear only to their asker and to
297/// teacher+ — so for a teacher, `?status=pending` is the approval queue.
298/// Paged via `?limit=&offset=`.
299///
300/// The visibility gate and the `status` filter share one SQL `WHERE`, so
301/// `total` counts the filtered set — `?status=pending` never loads the whole
302/// pool into a `Vec` first. A `status` other than `pending` or `approved`
303/// is a 400.
304#[utoipa::path(
305 get,
306 path = "/",
307 tag = "questions",
308 security(("session_cookie" = [])),
309 params(PoolQuestionFilter, PageParams),
310 responses(
311 (status = 200, description = "A page of the questions visible to the caller", body = Page<PoolQuestionResponse>),
312 (status = 400, description = "Unknown status, or invalid limit or offset", body = ErrorResponse),
313 (status = 401, description = "Not authenticated", body = ErrorResponse),
314 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
315 ),
316)]
317async fn list_questions(
318 State(st): State<AppState>,
319 RequireStudent(user): RequireStudent,
320 Query(filter): Query<PoolQuestionFilter>,
321 Query(page): Query<PageParams>,
322) -> Result<Json<Page<PoolQuestionResponse>>, AppError> {
323 let (limit, offset) = page.resolve()?;
324 let status = filter.status.as_deref().map(str::trim);
325 if let Some(status) = status
326 && !POOL_QUESTION_STATUSES.contains(&status)
327 {
328 return Err(AppError::Validation(ValidationError::Invalid {
329 field: "status",
330 reason: "must be one of: pending, approved",
331 }));
332 }
333
334 // Visibility stays exactly what the two reads encoded: teacher+ see the
335 // approval queue and the pool, everyone else the pool plus their own
336 // pending questions. Gate and status filter ride one SQL WHERE — `total`
337 // is the filtered count, and the window is the database's.
338 let viewer = (!user.get_role().at_least(Role::Teacher)).then_some(user.get_id());
339 let (questions, total) =
340 pool_question::list(&st.db, viewer, status, limit, offset).await?;
341
342 let items = question_responses(&questions, &st).await?;
343 Ok(Json(Page::new(items, total, limit, offset)))
344}
345
346/// One question. Approved questions are school-wide; a pending one 404s for
347/// everyone but its asker and teacher+.
348#[utoipa::path(
349 get,
350 path = "/{id}",
351 tag = "questions",
352 security(("session_cookie" = [])),
353 params(("id" = String, Path, description = "Question id")),
354 responses(
355 (status = 200, description = "The question", body = PoolQuestionResponse),
356 (status = 401, description = "Not authenticated", body = ErrorResponse),
357 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
358 (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse),
359 ),
360)]
361async fn get_question(
362 State(st): State<AppState>,
363 RequireStudent(user): RequireStudent,
364 Path(id): Path<String>,
365) -> Result<Json<PoolQuestionResponse>, AppError> {
366 let question = question_or_404(&st, &id).await?;
367 ensure_visible(&question, &user)?;
368 let responses = question_responses(std::slice::from_ref(&question), &st).await?;
369 let response = responses
370 .into_iter()
371 .next()
372 .ok_or_else(|| AppError::Internal("failed to render the question".into()))?;
373 Ok(Json(response))
374}
375
376/// Approve a pending question into the school-wide pool (teacher+),
377/// stamping the approver. One-way: approved content is frozen, and there is
378/// no "rejected" state — to turn a question down, delete it.
379#[utoipa::path(
380 post,
381 path = "/{id}/approve",
382 tag = "questions",
383 security(("session_cookie" = [])),
384 params(("id" = String, Path, description = "Question id")),
385 responses(
386 (status = 200, description = "The question, now approved", body = PoolQuestionResponse),
387 (status = 401, description = "Not authenticated", body = ErrorResponse),
388 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
389 (status = 404, description = "No such question", body = ErrorResponse),
390 (status = 409, description = "Already approved", body = ErrorResponse),
391 ),
392)]
393async fn approve_question(
394 State(st): State<AppState>,
395 RequireTeacher(user): RequireTeacher,
396 Path(id): Path<String>,
397) -> Result<Json<PoolQuestionResponse>, AppError> {
398 let question =
399 pool_question::approve(&st.db, &PoolQuestionId::from_key(&id), user.get_id()).await?;
400 // Both counters moved inside the approval's own transaction; the badges
401 // they may have earned are a decoration on top of it. Losing one to a
402 // transient database error must never fail the approval behind it, and the
403 // next counter move re-runs this and heals it. Two users, because the
404 // transition credits the approver and the asker alike.
405 for earner in [user.get_id(), question.get_asker()] {
406 if let Err(err) = crate::service::badge::sync(&st.db, earner).await {
407 tracing::warn!("failed to sync badges for {}: {err}", earner.key());
408 }
409 }
410 let responses = question_responses(std::slice::from_ref(&question), &st).await?;
411 let response = responses
412 .into_iter()
413 .next()
414 .ok_or_else(|| AppError::Internal("failed to render the approved question".into()))?;
415 Ok(Json(response))
416}
417
418/// Delete a question — the asker withdrawing their own, or teacher+
419/// moderating (this is also how a pending question is rejected). Takes the
420/// question's solutions and every image blob — its own and its solutions' —
421/// with it.
422#[utoipa::path(
423 delete,
424 path = "/{id}",
425 tag = "questions",
426 security(("session_cookie" = [])),
427 params(("id" = String, Path, description = "Question id")),
428 responses(
429 (status = 204, description = "Deleted, solutions included"),
430 (status = 401, description = "Not authenticated", body = ErrorResponse),
431 (status = 403, description = "Not the asker (and not teacher+)", body = ErrorResponse),
432 (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse),
433 ),
434)]
435async fn delete_question(
436 State(st): State<AppState>,
437 RequireStudent(user): RequireStudent,
438 Path(id): Path<String>,
439) -> Result<StatusCode, AppError> {
440 let question = question_or_404(&st, &id).await?;
441 ensure_visible(&question, &user)?;
442 if question.get_asker() != user.get_id() && !user.get_role().at_least(Role::Teacher) {
443 return Err(AppError::Forbidden(
444 "only the asker or a teacher+ may delete a question",
445 ));
446 }
447 let removed = pool_question::delete(&st.db, question.get_id())
448 .await?
449 .ok_or(AppError::NotFound)?;
450 // Rows went first (in one transaction); now every blob they named — the
451 // question's photo and each swept solution's — comes off disk.
452 for file in &removed.image_files {
453 remove_blob(&st.files_path, file).await;
454 }
455 Ok(StatusCode::NO_CONTENT)
456}
457
458// ---- the question's photo ---------------------------------------------------
459// One optional image per question — the snapshot of the problem sheet. Bytes
460// on disk under a server-generated ULID, metadata on the question row itself.
461// Asker-only, and only while pending: an image landing after approval would
462// put unmoderated bytes in the pool, so approval freezes it with the text.
463
464/// Attach (or replace) the question's photo. Asker only, while the question
465/// is still `pending` — approval freezes content, image included.
466/// `multipart/form-data` with the image under a `file` field; the declared
467/// content type must be `image/png`, `image/jpeg`, `image/webp`, or
468/// `image/gif` (rasters only — no SVG), the bytes at most the school's
469/// `max_file_bytes` (settings).
470#[utoipa::path(
471 post,
472 path = "/{id}/image",
473 tag = "questions",
474 security(("session_cookie" = [])),
475 params(("id" = String, Path, description = "Question id")),
476 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
477 responses(
478 (status = 201, description = "Image stored", body = PoolImageMeta),
479 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
480 (status = 401, description = "Not authenticated", body = ErrorResponse),
481 (status = 403, description = "Not the asker", body = ErrorResponse),
482 (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse),
483 (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse),
484 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
485 ),
486)]
487async fn upload_image(
488 State(st): State<AppState>,
489 RequireStudent(user): RequireStudent,
490 Path(id): Path<String>,
491 mut multipart: Multipart,
492) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {
493 let question = question_or_404(&st, &id).await?;
494 ensure_asker_editable(&question, &user)?;
495 let upload = read_image_upload(&st, &mut multipart).await?;
496 let size = upload.size();
497
498 let file = crate::domain::monotonic_id::next_uuid().to_string();
499 store_blob(&st, &file, &upload.data, || async {
500 match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size)
501 .await?
502 {
503 // The guarded UPDATE found the question still pending: point-of-truth
504 // write done; the replaced blob (if any) comes off disk.
505 Some(replaced) => Ok(((), replaced)),
506 // Approved or deleted mid-upload — the fresh blob is an orphan.
507 None => Err(AppError::Conflict("the question is no longer pending")),
508 }
509 })
510 .await?;
511 Ok((
512 StatusCode::CREATED,
513 Json(PoolImageMeta {
514 content_type: upload.content_type.as_str().to_string(),
515 size,
516 }),
517 ))
518}
519
520/// The question's photo bytes. Access follows the question itself: approved →
521/// school-wide, pending → asker and teacher+ only.
522#[utoipa::path(
523 get,
524 path = "/{id}/image",
525 tag = "questions",
526 security(("session_cookie" = [])),
527 params(("id" = String, Path, description = "Question id")),
528 responses(
529 (status = 200, description = "The image bytes", content_type = "image/*"),
530 (status = 401, description = "Not authenticated", body = ErrorResponse),
531 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
532 (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse),
533 ),
534)]
535async fn get_image(
536 State(st): State<AppState>,
537 RequireStudent(user): RequireStudent,
538 Path(id): Path<String>,
539) -> Result<Response, AppError> {
540 let question = question_or_404(&st, &id).await?;
541 ensure_visible(&question, &user)?;
542 let image = pool_question_image::read(&st.db, question.get_id()).await?;
543 match image {
544 Some(image) => {
545 serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
546 }
547 None => Err(AppError::NotFound),
548 }
549}
550
551/// Remove the question's photo. Asker only, while still `pending` — after
552/// approval the content (image included) is frozen.
553#[utoipa::path(
554 delete,
555 path = "/{id}/image",
556 tag = "questions",
557 security(("session_cookie" = [])),
558 params(("id" = String, Path, description = "Question id")),
559 responses(
560 (status = 204, description = "Image removed"),
561 (status = 401, description = "Not authenticated", body = ErrorResponse),
562 (status = 403, description = "Not the asker", body = ErrorResponse),
563 (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse),
564 (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse),
565 ),
566)]
567async fn delete_image(
568 State(st): State<AppState>,
569 RequireStudent(user): RequireStudent,
570 Path(id): Path<String>,
571) -> Result<StatusCode, AppError> {
572 let question = question_or_404(&st, &id).await?;
573 ensure_asker_editable(&question, &user)?;
574 match pool_question::clear_image(&st.db, question.get_id()).await? {
575 // Detached: the blob comes off disk.
576 Some(Some(file)) => {
577 remove_blob(&st.files_path, &file).await;
578 Ok(StatusCode::NO_CONTENT)
579 }
580 // Still pending, but there was no image to remove.
581 Some(None) => Err(AppError::NotFound),
582 // Approved or deleted mid-flight — content is frozen or gone.
583 None => Err(AppError::Conflict("the question is no longer pending")),
584 }
585}
586
587// ---- solutions --------------------------------------------------------------
588
589/// The solution, provided the caller may see the question it hangs on —
590/// visibility never splits below the question (a solution on a question you
591/// can't see must not exist for you either).
592async fn visible_solution(
593 st: &AppState,
594 user: &User,
595 id: &str,
596 sid: &str,
597) -> Result<Solution, AppError> {
598 let question = question_or_404(st, id).await?;
599 ensure_visible(&question, user)?;
600 solution::read_for(&st.db, &SolutionId::from_key(sid), question.get_id())
601 .await?
602 .ok_or(AppError::NotFound)
603}
604
605/// The shared front half of the author-only solution writes (body edit,
606/// image upload/removal): 404 invisible or missing, then 403 not the author.
607/// Teacher+ get no pass here — moderation stays delete-only, a teacher never
608/// rewrites someone else's answer. And unlike a question there is no freeze
609/// gate: solutions are unmoderated, so their authors edit anytime.
610async fn author_solution(
611 st: &AppState,
612 user: &User,
613 id: &str,
614 sid: &str,
615) -> Result<Solution, AppError> {
616 let solution = visible_solution(st, user, id, sid).await?;
617 if solution.get_author() != user.get_id() {
618 return Err(AppError::Forbidden("only the author may edit a solution"));
619 }
620 Ok(solution)
621}
622
623/// Offer a solution on an approved question. Anyone in the school may —
624/// students and staff alike (parents stay read-out). Pending questions take
625/// no solutions (409 for those who can see them, 404 for everyone else).
626#[utoipa::path(
627 post,
628 path = "/{id}/solutions",
629 tag = "questions",
630 security(("session_cookie" = [])),
631 params(("id" = String, Path, description = "Question id")),
632 request_body = OfferSolution,
633 responses(
634 (status = 201, description = "Solution offered", body = SolutionResponse),
635 (status = 400, description = "Invalid body", body = ErrorResponse),
636 (status = 401, description = "Not authenticated", body = ErrorResponse),
637 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
638 (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse),
639 (status = 409, description = "The question is not approved yet", body = ErrorResponse),
640 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
641 ),
642)]
643async fn offer_solution(
644 State(st): State<AppState>,
645 RequireStudent(user): RequireStudent,
646 Path(id): Path<String>,
647 Json(req): Json<OfferSolution>,
648) -> Result<(StatusCode, Json<SolutionResponse>), AppError> {
649 let question = question_or_404(&st, &id).await?;
650 ensure_visible(&question, &user)?;
651 if !question.is_approved() {
652 return Err(AppError::Conflict(
653 "the question is not approved yet — solutions open with the pool",
654 ));
655 }
656 let body = SolutionBody::try_new(&req.body)?;
657 let solution = solution::insert(
658 &st.db,
659 Solution::new(question.get_id(), user.get_id(), body),
660 )
661 .await?;
662 let people = person_map([*user.get_id()], &st.db).await?;
663 Ok((
664 StatusCode::CREATED,
665 Json(SolutionResponse::new(&solution, &people, None)),
666 ))
667}
668
669/// The question's solutions, oldest first (a discussion reads downward).
670/// Visibility follows the question. Paged via `?limit=&offset=`.
671#[utoipa::path(
672 get,
673 path = "/{id}/solutions",
674 tag = "questions",
675 security(("session_cookie" = [])),
676 params(("id" = String, Path, description = "Question id"), PageParams),
677 responses(
678 (status = 200, description = "A page of the question's solutions", body = Page<SolutionResponse>),
679 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
680 (status = 401, description = "Not authenticated", body = ErrorResponse),
681 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
682 (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse),
683 ),
684)]
685async fn list_solutions(
686 State(st): State<AppState>,
687 RequireStudent(user): RequireStudent,
688 Path(id): Path<String>,
689 Query(page): Query<PageParams>,
690) -> Result<Json<Page<SolutionResponse>>, AppError> {
691 let (limit, offset) = page.resolve()?;
692 let question = question_or_404(&st, &id).await?;
693 ensure_visible(&question, &user)?;
694 let (solutions, total) = solution::list_for(&st.db, question.get_id(), limit, offset).await?;
695 let slice = solutions.as_slice();
696 let people = person_map(slice.iter().map(|solution| *solution.get_author()), &st.db).await?;
697 let solution_refs: Vec<&SolutionId> = slice.iter().map(|s| s.get_id()).collect();
698 let mut images: HashMap<String, SolutionImage> = HashMap::new();
699 for image in solution_image::list_for_solutions(&st.db, &solution_refs).await? {
700 images.insert(image.get_solution().key(), image);
701 }
702 let items = slice
703 .iter()
704 .map(|solution| {
705 let image = images.get(solution.get_id().key().as_str());
706 SolutionResponse::new(solution, &people, image)
707 })
708 .collect();
709 Ok(Json(Page::new(items, total, limit, offset)))
710}
711
712/// Delete a solution — its author withdrawing it, or teacher+ moderating.
713/// Takes the solution's image blob with it.
714#[utoipa::path(
715 delete,
716 path = "/{id}/solutions/{sid}",
717 tag = "questions",
718 security(("session_cookie" = [])),
719 params(
720 ("id" = String, Path, description = "Question id"),
721 ("sid" = String, Path, description = "Solution id"),
722 ),
723 responses(
724 (status = 204, description = "Solution deleted"),
725 (status = 401, description = "Not authenticated", body = ErrorResponse),
726 (status = 403, description = "Not the author (and not teacher+)", body = ErrorResponse),
727 (status = 404, description = "No such question or solution", body = ErrorResponse),
728 ),
729)]
730async fn delete_solution(
731 State(st): State<AppState>,
732 RequireStudent(user): RequireStudent,
733 Path((id, sid)): Path<(String, String)>,
734) -> Result<StatusCode, AppError> {
735 let solution = visible_solution(&st, &user, &id, &sid).await?;
736 if solution.get_author() != user.get_id() && !user.get_role().at_least(Role::Teacher) {
737 return Err(AppError::Forbidden(
738 "only the author or a teacher+ may delete a solution",
739 ));
740 }
741 // Row first, blob after — a crash in between strands at worst an
742 // unreachable file.
743 let (_, image) = solution::delete(&st.db, solution)
744 .await?
745 .ok_or(AppError::NotFound)?;
746 if let Some(file) = image {
747 remove_blob(&st.files_path, &file).await;
748 }
749 Ok(StatusCode::NO_CONTENT)
750}
751
752/// Edit a solution's body — its author reworking their own answer. Author
753/// only, teacher+ included out: moderation stays delete-only (a moderator
754/// removes a bad solution, never rewrites someone else's words under their
755/// name). No freeze either — solutions are unmoderated, so editing stays
756/// open for as long as the solution lives.
757#[utoipa::path(
758 patch,
759 path = "/{id}/solutions/{sid}",
760 tag = "questions",
761 security(("session_cookie" = [])),
762 params(
763 ("id" = String, Path, description = "Question id"),
764 ("sid" = String, Path, description = "Solution id"),
765 ),
766 request_body = OfferSolution,
767 responses(
768 (status = 200, description = "The updated solution", body = SolutionResponse),
769 (status = 400, description = "Invalid body", body = ErrorResponse),
770 (status = 401, description = "Not authenticated", body = ErrorResponse),
771 (status = 403, description = "Not the author", body = ErrorResponse),
772 (status = 404, description = "No such question or solution", body = ErrorResponse),
773 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
774 ),
775)]
776async fn edit_solution(
777 State(st): State<AppState>,
778 RequireStudent(user): RequireStudent,
779 Path((id, sid)): Path<(String, String)>,
780 Json(req): Json<OfferSolution>,
781) -> Result<Json<SolutionResponse>, AppError> {
782 let solution = author_solution(&st, &user, &id, &sid).await?;
783 let body = SolutionBody::try_new(&req.body)?;
784 let updated = solution::set_body(&st.db, solution.get_id(), &body)
785 .await?
786 .ok_or(AppError::NotFound)?;
787 let people = person_map([*user.get_id()], &st.db).await?;
788 let image = solution_image::read(&st.db, updated.get_id()).await?;
789 Ok(Json(SolutionResponse::new(
790 &updated,
791 &people,
792 image.as_ref(),
793 )))
794}
795
796// ---- the solution's photo ---------------------------------------------------
797// One optional image per solution — the photographed worked steps or diagram.
798// Same blob discipline as the question's photo (bytes on disk under a
799// server-generated ULID, metadata on the row), but author-only *anytime*:
800// solutions carry no moderation state, so there is no approval to freeze
801// them.
802
803/// Attach (or replace) the solution's photo. Author only — and at any time,
804/// since solutions are never frozen. `multipart/form-data` with the image
805/// under a `file` field; the declared content type must be `image/png`,
806/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the
807/// bytes at most the school's `max_file_bytes` (settings).
808#[utoipa::path(
809 post,
810 path = "/{id}/solutions/{sid}/image",
811 tag = "questions",
812 security(("session_cookie" = [])),
813 params(
814 ("id" = String, Path, description = "Question id"),
815 ("sid" = String, Path, description = "Solution id"),
816 ),
817 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
818 responses(
819 (status = 201, description = "Image stored", body = PoolImageMeta),
820 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
821 (status = 401, description = "Not authenticated", body = ErrorResponse),
822 (status = 403, description = "Not the author", body = ErrorResponse),
823 (status = 404, description = "No such question or solution", body = ErrorResponse),
824 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
825 ),
826)]
827async fn upload_solution_image(
828 State(st): State<AppState>,
829 RequireStudent(user): RequireStudent,
830 Path((id, sid)): Path<(String, String)>,
831 mut multipart: Multipart,
832) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {
833 let solution = author_solution(&st, &user, &id, &sid).await?;
834 let upload = read_image_upload(&st, &mut multipart).await?;
835 let size = upload.size();
836
837 let file = crate::domain::monotonic_id::next_uuid().to_string();
838 store_blob(&st, &file, &upload.data, || async {
839 match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size)
840 .await?
841 {
842 // Row write done; the replaced blob (if any) comes off disk.
843 Some(replaced) => Ok(((), replaced)),
844 // Deleted mid-upload — the fresh blob is an orphan.
845 None => Err(AppError::NotFound),
846 }
847 })
848 .await?;
849 Ok((
850 StatusCode::CREATED,
851 Json(PoolImageMeta {
852 content_type: upload.content_type.as_str().to_string(),
853 size,
854 }),
855 ))
856}
857
858/// The solution photo's bytes. Access follows the question the solution
859/// hangs on — in practice school-wide, since solutions exist only on
860/// approved questions.
861#[utoipa::path(
862 get,
863 path = "/{id}/solutions/{sid}/image",
864 tag = "questions",
865 security(("session_cookie" = [])),
866 params(
867 ("id" = String, Path, description = "Question id"),
868 ("sid" = String, Path, description = "Solution id"),
869 ),
870 responses(
871 (status = 200, description = "The image bytes", content_type = "image/*"),
872 (status = 401, description = "Not authenticated", body = ErrorResponse),
873 (status = 403, description = "Requires student role or higher", body = ErrorResponse),
874 (status = 404, description = "No such question, solution, or image", body = ErrorResponse),
875 ),
876)]
877async fn get_solution_image(
878 State(st): State<AppState>,
879 RequireStudent(user): RequireStudent,
880 Path((id, sid)): Path<(String, String)>,
881) -> Result<Response, AppError> {
882 let solution = visible_solution(&st, &user, &id, &sid).await?;
883 let image = solution_image::read(&st.db, solution.get_id()).await?;
884 match image {
885 Some(image) => {
886 serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
887 }
888 None => Err(AppError::NotFound),
889 }
890}
891
892/// Remove the solution's photo. Author only, anytime — solutions are never
893/// frozen.
894#[utoipa::path(
895 delete,
896 path = "/{id}/solutions/{sid}/image",
897 tag = "questions",
898 security(("session_cookie" = [])),
899 params(
900 ("id" = String, Path, description = "Question id"),
901 ("sid" = String, Path, description = "Solution id"),
902 ),
903 responses(
904 (status = 204, description = "Image removed"),
905 (status = 401, description = "Not authenticated", body = ErrorResponse),
906 (status = 403, description = "Not the author", body = ErrorResponse),
907 (status = 404, description = "No such question, solution, or image", body = ErrorResponse),
908 ),
909)]
910async fn delete_solution_image(
911 State(st): State<AppState>,
912 RequireStudent(user): RequireStudent,
913 Path((id, sid)): Path<(String, String)>,
914) -> Result<StatusCode, AppError> {
915 let solution = author_solution(&st, &user, &id, &sid).await?;
916 match solution::clear_image(&st.db, solution.get_id()).await? {
917 // Detached: the blob comes off disk.
918 Some(Some(file)) => {
919 remove_blob(&st.files_path, &file).await;
920 Ok(StatusCode::NO_CONTENT)
921 }
922 // Gone, or there was no image to remove.
923 _ => Err(AppError::NotFound),
924 }
925}