forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB914d095Ahmet Kaan Gümüş2 months ago454 commits

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