forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

course_notes.rs661 lines, 27.9 KiBHistoryRawDownload
1//! Course notes: a teacher-authored note attached to a course, with file
2//! attachments. Mirrors [`super::notes`] (personal notes) handler for
3//! handler, with authorization swapped for the course-management wall:
4//! writes need [`super::courses::can_manage_course`] (creator, an assigned
5//! teacher, or manager+), reads need [`super::courses::can_view_course`]
6//! (management rights, or enrollment).
7
8use crate::web::tenant_state::{ResolvedTenant, State};
9use axum::Json;
10use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
11use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
12use axum::http::{HeaderValue, StatusCode};
13use axum::response::{IntoResponse, Response};
14use serde::{Deserialize, Serialize};
15use utoipa::{IntoParams, ToSchema};
16use utoipa_axum::router::OpenApiRouter;
17use utoipa_axum::routes;
18
19use crate::ai::rag::spawn_index;
20use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
21use crate::database::Database;
22use crate::domain::course::{Course, CourseId};
23use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};
24use crate::domain::course_note_file::{
25 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
26};
27use crate::domain::rag_output::{RagOutput, RagOutputId};
28use crate::error::{AppError, ErrorResponse};
29use crate::service;
30use crate::state::AppState;
31
32use super::courses::{can_manage_course, can_view_course};
33use super::notes::content_disposition;
34use super::{
35 CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, read_upload,
36 remove_blob,
37};
38
39pub fn routes() -> OpenApiRouter<AppState> {
40 // Same body-cap split as `notes`' file routes: the server-wide hard
41 // ceiling plus multipart framing headroom, with the school's actual
42 // (usually smaller) limit enforced while the stream is read.
43 let files = OpenApiRouter::new()
44 .routes(routes!(upload_file, list_files))
45 .routes(routes!(download_file, delete_file))
46 .layer(DefaultBodyLimit::max(
47 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
48 ));
49 OpenApiRouter::new()
50 .routes(routes!(create, list))
51 .routes(routes!(get_one, update, delete_one))
52 .routes(routes!(list_rag))
53 .routes(routes!(delete_rag))
54 .merge(files)
55}
56
57/// The note plus its course, or a 404 — every entity handler here gates on
58/// the parent course, so they always travel together.
59async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> {
60 let note = CourseNote::read(&CourseNoteId::from_key(id), db)
61 .await?
62 .ok_or(AppError::NotFound)?;
63 let course = crate::service::course::read(db, note.get_course())
64 .await?
65 .ok_or(AppError::NotFound)?;
66 Ok((note, course))
67}
68
69#[derive(Deserialize, ToSchema)]
70struct CreateCourseNote {
71 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
72 course: String,
73 #[schema(example = "Chapter 3 recap", max_length = 200)]
74 title: String,
75 #[schema(
76 example = "Covered quadratics; homework due Friday",
77 max_length = 10000
78 )]
79 content: Option<String>,
80}
81
82#[derive(Deserialize, ToSchema)]
83struct UpdateCourseNote {
84 #[schema(max_length = 200)]
85 title: Option<String>,
86 #[schema(max_length = 10000)]
87 content: Option<String>,
88}
89
90#[derive(Serialize, ToSchema)]
91struct CourseNoteResponse {
92 id: String,
93 course: String,
94 title: String,
95 content: String,
96}
97
98impl CourseNoteResponse {
99 fn new(note: &CourseNote) -> Self {
100 Self {
101 id: note.get_id().key().to_string(),
102 course: note.get_course().key().to_string(),
103 title: note.get_title().as_str().to_string(),
104 content: note.get_content().as_str().to_string(),
105 }
106 }
107}
108
109/// Create a note on a course. Requires teacher+ and management rights over
110/// the course (its creator, an assigned teacher, or a manager/admin).
111#[utoipa::path(
112 post,
113 path = "/",
114 tag = "course-notes",
115 security(("session_cookie" = [])),
116 request_body = CreateCourseNote,
117 responses(
118 (status = 201, description = "Note created", body = CourseNoteResponse),
119 (status = 400, description = "Invalid title or content", body = ErrorResponse),
120 (status = 401, description = "Not authenticated", body = ErrorResponse),
121 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
122 (status = 404, description = "Course not found", body = ErrorResponse),
123 (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse),
124 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
125 ),
126)]
127async fn create(
128 State(st): State<AppState>,
129 tenant: ResolvedTenant,
130 RequireTeacher(user): RequireTeacher,
131 Json(req): Json<CreateCourseNote>,
132) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {
133 let course = crate::service::course::read(&st.db, &CourseId::from_key(&req.course))
134 .await?
135 .ok_or(AppError::NotFound)?;
136 if !can_manage_course(&course, &user) {
137 return Err(AppError::Forbidden(
138 "only the course creator, an assigned teacher, or a manager/admin can add a course note",
139 ));
140 }
141 crate::service::course::require_open(&st.db, &course).await?;
142 let title = CourseNoteTitle::try_new(&req.title)?;
143 let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?;
144 let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?;
145 // Indexing is a background bonus, never a condition of storing the note:
146 // the dispatch runs in its own task, so a slow or absent AI service cannot
147 // delay or fail this 201.
148 spawn_index(&st, &tenant, note.clone());
149 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))
150}
151
152#[derive(Deserialize, IntoParams)]
153struct CourseFilter {
154 /// The course to list notes for (required).
155 #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
156 course: String,
157}
158
159/// List a course's notes, newest first. Visible to whoever can view the
160/// course (its enrolled users, creator, assigned teachers, and
161/// managers/admins). Paged via `?limit=&offset=`.
162#[utoipa::path(
163 get,
164 path = "/",
165 tag = "course-notes",
166 security(("session_cookie" = [])),
167 params(CourseFilter, PageParams),
168 responses(
169 (status = 200, description = "A page of the course's notes (all of them when unpaged)", body = Page<CourseNoteResponse>),
170 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
171 (status = 401, description = "Not authenticated", body = ErrorResponse),
172 (status = 403, description = "Not enrolled in the course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
173 (status = 404, description = "Course not found", body = ErrorResponse),
174 ),
175)]
176async fn list(
177 State(st): State<AppState>,
178 CurrentUser(user): CurrentUser,
179 Query(filter): Query<CourseFilter>,
180 Query(page): Query<PageParams>,
181) -> Result<Json<Page<CourseNoteResponse>>, AppError> {
182 let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course))
183 .await?
184 .ok_or(AppError::NotFound)?;
185 if !can_view_course(&course, &user, &st.db).await? {
186 return Err(AppError::Forbidden(
187 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course's notes",
188 ));
189 }
190 let (limit, offset) = page.resolve()?;
191 let (notes, total) =
192 CourseNote::list_for_course(course.get_id(), limit, offset, &st.db).await?;
193 let items = notes.iter().map(CourseNoteResponse::new).collect();
194 Ok(Json(Page::new(items, total, limit, offset)))
195}
196
197/// Fetch a single course note by id. Visible to whoever can view its course.
198#[utoipa::path(
199 get,
200 path = "/{id}",
201 tag = "course-notes",
202 security(("session_cookie" = [])),
203 params(("id" = String, Path, description = "Course note id")),
204 responses(
205 (status = 200, description = "The note", body = CourseNoteResponse),
206 (status = 401, description = "Not authenticated", body = ErrorResponse),
207 (status = 403, description = "Not enrolled in the course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
208 (status = 404, description = "Not found", body = ErrorResponse),
209 ),
210)]
211async fn get_one(
212 State(st): State<AppState>,
213 CurrentUser(user): CurrentUser,
214 Path(id): Path<String>,
215) -> Result<Json<CourseNoteResponse>, AppError> {
216 let (note, course) = note_with_course(&id, &st.db).await?;
217 if !can_view_course(&course, &user, &st.db).await? {
218 return Err(AppError::Forbidden(
219 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note",
220 ));
221 }
222 Ok(Json(CourseNoteResponse::new(&note)))
223}
224
225/// Update a course note's title and/or content. Omitted fields keep their
226/// value. Requires teacher+ and management rights over the course.
227#[utoipa::path(
228 patch,
229 path = "/{id}",
230 tag = "course-notes",
231 security(("session_cookie" = [])),
232 params(("id" = String, Path, description = "Course note id")),
233 request_body = UpdateCourseNote,
234 responses(
235 (status = 200, description = "Updated note", body = CourseNoteResponse),
236 (status = 400, description = "Invalid title or content", body = ErrorResponse),
237 (status = 401, description = "Not authenticated", body = ErrorResponse),
238 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
239 (status = 404, description = "Not found", body = ErrorResponse),
240 (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse),
241 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
242 ),
243)]
244async fn update(
245 State(st): State<AppState>,
246 tenant: ResolvedTenant,
247 RequireTeacher(user): RequireTeacher,
248 Path(id): Path<String>,
249 Json(req): Json<UpdateCourseNote>,
250) -> Result<Json<CourseNoteResponse>, AppError> {
251 let (note, course) = note_with_course(&id, &st.db).await?;
252 if !can_manage_course(&course, &user) {
253 return Err(AppError::Forbidden(
254 "only the course creator, an assigned teacher, or a manager/admin can edit this course note",
255 ));
256 }
257 crate::service::course::require_open(&st.db, &course).await?;
258
259 let title = req
260 .title
261 .as_deref()
262 .map(CourseNoteTitle::try_new)
263 .transpose()?;
264 let content = req
265 .content
266 .as_deref()
267 .map(CourseNoteContent::try_new)
268 .transpose()?;
269
270 let updated = note.update(title, content, &st.db).await?;
271 // The stored index describes the old text — refresh it.
272 spawn_index(&st, &tenant, updated.clone());
273 Ok(Json(CourseNoteResponse::new(&updated)))
274}
275
276/// Delete a course note, along with its files. Requires teacher+ and
277/// management rights over the course.
278#[utoipa::path(
279 delete,
280 path = "/{id}",
281 tag = "course-notes",
282 security(("session_cookie" = [])),
283 params(("id" = String, Path, description = "Course note id")),
284 responses(
285 (status = 204, description = "Deleted"),
286 (status = 401, description = "Not authenticated", body = ErrorResponse),
287 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
288 (status = 404, description = "Not found", body = ErrorResponse),
289 (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse),
290 ),
291)]
292async fn delete_one(
293 State(st): State<AppState>,
294 RequireTeacher(user): RequireTeacher,
295 Path(id): Path<String>,
296) -> Result<StatusCode, AppError> {
297 let (note, course) = note_with_course(&id, &st.db).await?;
298 if !can_manage_course(&course, &user) {
299 return Err(AppError::Forbidden(
300 "only the course creator, an assigned teacher, or a manager/admin can delete this course note",
301 ));
302 }
303 crate::service::course::require_open(&st.db, &course).await?;
304 // Derived rows first, outside the note's own cascade transaction: they are
305 // disposable, so failing here leaves the note intact and the 500 truthful,
306 // whereas dropping them after the note would strand every blob on an error
307 // — and if the note delete then fails, the next change regenerates them.
308 service::rag_output::delete_for_note(&st.db, note.get_id()).await?;
309 // Rows go first (the note delete cascades them), blobs after: a crash in
310 // between strands at worst an unreachable blob, never a row whose blob is
311 // already gone. The files to unlink come from the delete itself, not a
312 // pre-read list — an upload that landed in between is in the cascade too.
313 let (_, files) = note.delete(&st.db).await?;
314 for file in &files {
315 remove_blob(&st.files_path, file.get_id().key()).await;
316 }
317 Ok(StatusCode::NO_CONTENT)
318}
319
320/// A course note file's stored metadata; the bytes themselves come from the
321/// download endpoint.
322#[derive(Serialize, ToSchema)]
323struct CourseNoteFileResponse {
324 id: String,
325 /// The uploader's original filename.
326 #[schema(example = "recap.pdf")]
327 name: String,
328 /// MIME type as declared on upload.
329 #[schema(example = "application/pdf")]
330 content_type: String,
331 /// File size in bytes.
332 #[schema(example = 24_576)]
333 size: i64,
334}
335
336impl CourseNoteFileResponse {
337 fn new(file: &CourseNoteFile) -> Self {
338 Self {
339 id: file.get_id().key().to_string(),
340 name: file.get_name().as_str().to_string(),
341 content_type: file.get_content_type().as_str().to_string(),
342 size: file.get_size(),
343 }
344 }
345}
346
347/// Attach a file to a course note. `multipart/form-data` with the file under
348/// a `file` field; its `filename` is required. At most 10 files per note,
349/// each at most the school's `max_file_bytes` (settings, default 5 MiB).
350/// Requires teacher+ and management rights over the course.
351#[utoipa::path(
352 post,
353 path = "/{id}/files",
354 tag = "course-notes",
355 security(("session_cookie" = [])),
356 params(("id" = String, Path, description = "Course note id")),
357 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
358 responses(
359 (status = 201, description = "File stored", body = CourseNoteFileResponse),
360 (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse),
361 (status = 401, description = "Not authenticated", body = ErrorResponse),
362 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
363 (status = 404, description = "Note not found", body = ErrorResponse),
364 (status = 409, description = "The note already holds the maximum number of files, or this course's term is archived — past years are read-only", body = ErrorResponse),
365 (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse),
366 ),
367)]
368async fn upload_file(
369 State(st): State<AppState>,
370 tenant: ResolvedTenant,
371 RequireTeacher(user): RequireTeacher,
372 Path(id): Path<String>,
373 mut multipart: Multipart,
374) -> Result<(StatusCode, Json<CourseNoteFileResponse>), AppError> {
375 let (note, course) = note_with_course(&id, &st.db).await?;
376 if !can_manage_course(&course, &user) {
377 return Err(AppError::Forbidden(
378 "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note",
379 ));
380 }
381 crate::service::course::require_open(&st.db, &course).await?;
382 // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and
383 // create under one lock) — checking it here too would just race.
384 let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
385
386 let upload = read_upload(&mut multipart, limit).await?;
387 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
388 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
389
390 // Blob first, row second — a stored row always points at a real blob. If
391 // the row insert fails, take the fresh blob back out.
392 let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
393 let path = blob_path(&st.files_path, file.get_id().key());
394 crate::web::ensure_files_dir(&st.files_path).await?;
395 tokio::fs::write(&path, &upload.data)
396 .await
397 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
398 match file.insert(&st.db).await {
399 Ok(created) => {
400 // The note now holds one more source than the stored index knows.
401 spawn_index(&st, &tenant, note);
402 Ok((
403 StatusCode::CREATED,
404 Json(CourseNoteFileResponse::new(&created)),
405 ))
406 }
407 Err(err) => {
408 let _ = tokio::fs::remove_file(&path).await;
409 Err(err)
410 }
411 }
412}
413
414/// List a course note's files (metadata only), newest first. Paged via
415/// `?limit=&offset=`.
416#[utoipa::path(
417 get,
418 path = "/{id}/files",
419 tag = "course-notes",
420 security(("session_cookie" = [])),
421 params(("id" = String, Path, description = "Course note id"), PageParams),
422 responses(
423 (status = 200, description = "A page of the note's files", body = Page<CourseNoteFileResponse>),
424 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
425 (status = 401, description = "Not authenticated", body = ErrorResponse),
426 (status = 403, description = "Not enrolled in the course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
427 (status = 404, description = "Note not found", body = ErrorResponse),
428 ),
429)]
430async fn list_files(
431 State(st): State<AppState>,
432 CurrentUser(user): CurrentUser,
433 Path(id): Path<String>,
434 Query(page): Query<PageParams>,
435) -> Result<Json<Page<CourseNoteFileResponse>>, AppError> {
436 let (limit, offset) = page.resolve()?;
437 let (note, course) = note_with_course(&id, &st.db).await?;
438 if !can_view_course(&course, &user, &st.db).await? {
439 return Err(AppError::Forbidden(
440 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files",
441 ));
442 }
443 let (files, total) = CourseNoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;
444 let items = files.iter().map(CourseNoteFileResponse::new).collect();
445 Ok(Json(Page::new(items, total, limit, offset)))
446}
447
448/// Download a course note file's bytes. `Content-Type` is the one declared on
449/// upload; `Content-Disposition` carries the original filename.
450#[utoipa::path(
451 get,
452 path = "/{id}/files/{file_id}",
453 tag = "course-notes",
454 security(("session_cookie" = [])),
455 params(
456 ("id" = String, Path, description = "Course note id"),
457 ("file_id" = String, Path, description = "File id"),
458 ),
459 responses(
460 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
461 (status = 401, description = "Not authenticated", body = ErrorResponse),
462 (status = 403, description = "Not enrolled in the course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
463 (status = 404, description = "Note or file not found", body = ErrorResponse),
464 ),
465)]
466async fn download_file(
467 State(st): State<AppState>,
468 CurrentUser(user): CurrentUser,
469 Path((id, file_id)): Path<(String, String)>,
470) -> Result<Response, AppError> {
471 let (note, course) = note_with_course(&id, &st.db).await?;
472 if !can_view_course(&course, &user, &st.db).await? {
473 return Err(AppError::Forbidden(
474 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files",
475 ));
476 }
477 let file =
478 CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db)
479 .await?
480 .ok_or(AppError::NotFound)?;
481 let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key()))
482 .await
483 .map_err(|err| {
484 // The row exists but its blob doesn't — that's server-side damage
485 // (a lost volume path), not a client 404.
486 AppError::Internal(format!(
487 "missing blob for course note file {}: {err}",
488 file.get_id().key()
489 ))
490 })?;
491 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
492 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
493 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
494 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
495 Ok((
496 [
497 (CONTENT_TYPE, content_type),
498 (CONTENT_DISPOSITION, disposition),
499 ],
500 bytes,
501 )
502 .into_response())
503}
504
505/// Delete a course note file (row first, then its blob). Requires teacher+
506/// and management rights over the course.
507#[utoipa::path(
508 delete,
509 path = "/{id}/files/{file_id}",
510 tag = "course-notes",
511 security(("session_cookie" = [])),
512 params(
513 ("id" = String, Path, description = "Course note id"),
514 ("file_id" = String, Path, description = "File id"),
515 ),
516 responses(
517 (status = 204, description = "Deleted"),
518 (status = 401, description = "Not authenticated", body = ErrorResponse),
519 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
520 (status = 404, description = "Note or file not found", body = ErrorResponse),
521 (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse),
522 ),
523)]
524async fn delete_file(
525 State(st): State<AppState>,
526 tenant: ResolvedTenant,
527 RequireTeacher(user): RequireTeacher,
528 Path((id, file_id)): Path<(String, String)>,
529) -> Result<StatusCode, AppError> {
530 let (note, course) = note_with_course(&id, &st.db).await?;
531 if !can_manage_course(&course, &user) {
532 return Err(AppError::Forbidden(
533 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files",
534 ));
535 }
536 crate::service::course::require_open(&st.db, &course).await?;
537 let file =
538 CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db)
539 .await?
540 .ok_or(AppError::NotFound)?;
541 // Drop every output built from this file before the file itself, so a
542 // stale index cannot outlive its source in a deployment with no AI service
543 // at all, and a failure here leaves the file whole instead of stranding its
544 // blob; the re-index rebuilds from what is left, if a service is connected.
545 service::rag_output::delete_with_source(&st.db, file.get_id()).await?;
546 let file = file.delete(&st.db).await?;
547 remove_blob(&st.files_path, file.get_id().key()).await;
548 spawn_index(&st, &tenant, note);
549 Ok(StatusCode::NO_CONTENT)
550}
551
552/// One AI service output stored against a course note. `payload` is the
553/// service's own shape — the backend stores and serves it unread.
554#[derive(Serialize, ToSchema)]
555struct RagOutputResponse {
556 id: String,
557 course_note: String,
558 course: String,
559 /// The note's file attachments the output was built from.
560 sources: Vec<String>,
561 /// The service's answer, verbatim.
562 #[schema(value_type = Object)]
563 payload: serde_json::Value,
564 /// When the backend stored it, epoch milliseconds.
565 #[schema(example = 1_735_689_600_000i64)]
566 generated_at: i64,
567}
568
569impl RagOutputResponse {
570 fn new(output: &RagOutput) -> Self {
571 Self {
572 id: output.get_id().key().to_string(),
573 course_note: output.get_course_note().key().to_string(),
574 course: output.get_course().key().to_string(),
575 sources: output
576 .get_sources()
577 .iter()
578 .map(|file| file.key().to_string())
579 .collect(),
580 payload: output.get_payload().clone(),
581 generated_at: output.get_generated_at().as_millis(),
582 }
583 }
584}
585
586/// List a course note's AI outputs, newest first. Visible to whoever can view
587/// the course. Paged via `?limit=&offset=`.
588#[utoipa::path(
589 get,
590 path = "/{id}/rag",
591 tag = "course-notes",
592 security(("session_cookie" = [])),
593 params(("id" = String, Path, description = "Course note id"), PageParams),
594 responses(
595 (status = 200, description = "A page of the note's stored AI outputs", body = Page<RagOutputResponse>),
596 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
597 (status = 401, description = "Not authenticated", body = ErrorResponse),
598 (status = 403, description = "Not enrolled in the course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
599 (status = 404, description = "Note not found", body = ErrorResponse),
600 ),
601)]
602async fn list_rag(
603 State(st): State<AppState>,
604 CurrentUser(user): CurrentUser,
605 Path(id): Path<String>,
606 Query(page): Query<PageParams>,
607) -> Result<Json<Page<RagOutputResponse>>, AppError> {
608 let (limit, offset) = page.resolve()?;
609 let (note, course) = note_with_course(&id, &st.db).await?;
610 if !can_view_course(&course, &user, &st.db).await? {
611 return Err(AppError::Forbidden(
612 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs",
613 ));
614 }
615 let (outputs, total) =
616 service::rag_output::list_for(&st.db, note.get_id(), limit, offset).await?;
617 let items = outputs.iter().map(RagOutputResponse::new).collect();
618 Ok(Json(Page::new(items, total, limit, offset)))
619}
620
621/// Delete one stored AI output. Requires teacher+ and management rights over
622/// the course. Dropping an output does not stop the next note or file change
623/// from regenerating one.
624#[utoipa::path(
625 delete,
626 path = "/{id}/rag/{output_id}",
627 tag = "course-notes",
628 security(("session_cookie" = [])),
629 params(
630 ("id" = String, Path, description = "Course note id"),
631 ("output_id" = String, Path, description = "AI output id"),
632 ),
633 responses(
634 (status = 204, description = "Deleted"),
635 (status = 401, description = "Not authenticated", body = ErrorResponse),
636 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
637 (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse),
638 (status = 404, description = "Note or output not found", body = ErrorResponse),
639 ),
640)]
641async fn delete_rag(
642 State(st): State<AppState>,
643 RequireTeacher(user): RequireTeacher,
644 Path((id, output_id)): Path<(String, String)>,
645) -> Result<StatusCode, AppError> {
646 let (note, course) = note_with_course(&id, &st.db).await?;
647 if !can_manage_course(&course, &user) {
648 return Err(AppError::Forbidden(
649 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs",
650 ));
651 }
652 crate::service::course::require_open(&st.db, &course).await?;
653 // Scoped to the note in the path, like `CourseNoteFile::read_for`: an
654 // output of another note is a 404 here, never a cross-note delete.
655 let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id))
656 .await?
657 .filter(|output| output.get_course_note() == note.get_id())
658 .ok_or(AppError::NotFound)?;
659 service::rag_output::delete(&st.db, output.get_id()).await?;
660 Ok(StatusCode::NO_CONTENT)
661}