forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

course_notes.rs722 lines, 29.5 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`] (its creator or a
5//! manager/admin, while teacher+), reads need
6//! [`super::courses::can_view_course`] (the above, or anyone the course
7//! reaches).
8
9use crate::tenant::ResolvedTenant;
10use crate::web::tenant_state::State;
11use axum::Json;
12use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
13use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
14use axum::http::{HeaderValue, StatusCode};
15use axum::response::{IntoResponse, Response};
16use serde::{Deserialize, Serialize};
17use utoipa::{IntoParams, ToSchema};
18use utoipa_axum::router::OpenApiRouter;
19use utoipa_axum::routes;
20
21use crate::ai::rag::spawn_index;
22use crate::constant::{AI_RAG_INDEX_CAPABILITY, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
23use crate::database::Database;
24use crate::domain::course::{Course, CourseId};
25use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};
26use crate::domain::course_note_file::{
27 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
28};
29use crate::domain::rag_output::{RagOutput, RagOutputId};
30use crate::error::{AppError, ErrorResponse};
31use crate::module::Module;
32use crate::service;
33use crate::service::course::{can_manage_course, can_view_course};
34use crate::state::AppState;
35
36use super::notes::content_disposition;
37use super::{
38 CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path,
39 read_upload, remove_blob,
40};
41
42pub fn routes() -> OpenApiRouter<AppState> {
43 // Same body-cap split as `notes`' file routes: the server-wide hard
44 // ceiling plus multipart framing headroom, with the school's actual
45 // (usually smaller) limit enforced while the stream is read.
46 let files = OpenApiRouter::new()
47 .routes(routes!(upload_file, list_files))
48 .routes(routes!(download_file, delete_file))
49 .layer(DefaultBodyLimit::max(
50 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
51 ));
52 OpenApiRouter::new()
53 .routes(routes!(create, list))
54 .routes(routes!(get_one, update, delete_one))
55 .routes(routes!(list_rag))
56 .routes(routes!(reindex_rag))
57 .routes(routes!(delete_rag))
58 .merge(files)
59}
60
61/// The note plus its course, or a 404 — every entity handler here gates on
62/// the parent course, so they always travel together.
63async fn note_with_course(id: String, db: Database) -> Result<(CourseNote, Course), AppError> {
64 let id = CourseNoteId::from_key(&id);
65 let note = service::course_note::read(&db, &id)
66 .await?
67 .ok_or(AppError::NotFound)?;
68 let course = crate::service::course::read(&db, note.get_course())
69 .await?
70 .ok_or(AppError::NotFound)?;
71 Ok((note, course))
72}
73
74#[derive(Deserialize, ToSchema)]
75struct CreateCourseNote {
76 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
77 course: String,
78 #[schema(example = "Chapter 3 recap", max_length = 200)]
79 title: String,
80 #[schema(
81 example = "Covered quadratics; homework due Friday",
82 max_length = 10000
83 )]
84 content: Option<String>,
85}
86
87#[derive(Deserialize, ToSchema)]
88struct UpdateCourseNote {
89 #[schema(max_length = 200)]
90 title: Option<String>,
91 #[schema(max_length = 10000)]
92 content: Option<String>,
93}
94
95#[derive(Serialize, ToSchema)]
96struct CourseNoteResponse {
97 id: String,
98 course: String,
99 title: String,
100 content: String,
101}
102
103impl CourseNoteResponse {
104 fn new(note: &CourseNote) -> Self {
105 Self {
106 id: note.get_id().key().to_string(),
107 course: note.get_course().key().to_string(),
108 title: note.get_title().as_str().to_string(),
109 content: note.get_content().as_str().to_string(),
110 }
111 }
112}
113
114/// Create a note on a course. Requires teacher+ and catalog rights over the
115/// course (its creator or a manager/admin).
116#[utoipa::path(
117 post,
118 path = "/",
119 tag = "course-notes",
120 security(("session_cookie" = [])),
121 request_body = CreateCourseNote,
122 responses(
123 (status = 201, description = "Note created", body = CourseNoteResponse),
124 (status = 400, description = "Invalid title or content", body = ErrorResponse),
125 (status = 401, description = "Not authenticated", body = ErrorResponse),
126 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
127 (status = 404, description = "Course not found", body = ErrorResponse),
128 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
129 ),
130)]
131async fn create(
132 State(st): State<AppState>,
133 tenant: ResolvedTenant,
134 RequireTeacher(user): RequireTeacher,
135 Json(req): Json<CreateCourseNote>,
136) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {
137 let course = crate::service::course::read(&st.db, &CourseId::from_key(&req.course))
138 .await?
139 .ok_or(AppError::NotFound)?;
140 if !can_manage_course(&course, &user) {
141 return Err(AppError::Forbidden(
142 "only the course creator or a manager/admin can add a course note",
143 ));
144 }
145 let title = CourseNoteTitle::try_new(&req.title)?;
146 let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?;
147 let note = service::course_note::create(&st.db, course.get_id(), user.get_id(), title, content)
148 .await?;
149 // Indexing is a background bonus, never a condition of storing the note:
150 // the dispatch runs in its own task, so a slow or absent AI service cannot
151 // delay or fail this 201.
152 spawn_index(&st, &tenant, note.clone());
153 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))
154}
155
156#[derive(Deserialize, IntoParams)]
157struct CourseFilter {
158 /// The course to list notes for (required).
159 #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
160 course: String,
161}
162
163/// List a course's notes, newest first. Visible to whoever can view the
164/// course (its creator, a manager/admin, or anyone the course reaches).
165/// Paged via `?limit=&offset=`.
166#[utoipa::path(
167 get,
168 path = "/",
169 tag = "course-notes",
170 security(("session_cookie" = [])),
171 params(CourseFilter, PageParams),
172 responses(
173 (status = 200, description = "A page of the course's notes (all of them when unpaged)", body = Page<CourseNoteResponse>),
174 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
175 (status = 401, description = "Not authenticated", body = ErrorResponse),
176 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
177 (status = 404, description = "Course not found", body = ErrorResponse),
178 ),
179)]
180async fn list(
181 State(st): State<AppState>,
182 CurrentUser(user): CurrentUser,
183 Query(filter): Query<CourseFilter>,
184 Query(page): Query<PageParams>,
185) -> Result<Json<Page<CourseNoteResponse>>, AppError> {
186 let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course))
187 .await?
188 .ok_or(AppError::NotFound)?;
189 if !can_view_course(&course, &user, &st.db).await? {
190 return Err(AppError::Forbidden(
191 "only a user this course reaches, its creator, or a manager/admin can view this course's notes",
192 ));
193 }
194 let (limit, offset) = page.resolve()?;
195 let (notes, total) =
196 service::course_note::list_for_course(&st.db, course.get_id(), limit, offset).await?;
197 let items = notes.iter().map(CourseNoteResponse::new).collect();
198 Ok(Json(Page::new(items, total, limit, offset)))
199}
200
201/// Fetch a single course note by id. Visible to whoever can view its course.
202#[utoipa::path(
203 get,
204 path = "/{id}",
205 tag = "course-notes",
206 security(("session_cookie" = [])),
207 params(("id" = String, Path, description = "Course note id")),
208 responses(
209 (status = 200, description = "The note", body = CourseNoteResponse),
210 (status = 401, description = "Not authenticated", body = ErrorResponse),
211 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
212 (status = 404, description = "Not found", body = ErrorResponse),
213 ),
214)]
215async fn get_one(
216 State(st): State<AppState>,
217 CurrentUser(user): CurrentUser,
218 Path(id): Path<String>,
219) -> Result<Json<CourseNoteResponse>, AppError> {
220 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
221 if !can_view_course(&course, &user, &st.db).await? {
222 return Err(AppError::Forbidden(
223 "only a user this course reaches, its creator, or a manager/admin can view this course note",
224 ));
225 }
226 Ok(Json(CourseNoteResponse::new(&note)))
227}
228
229/// Update a course note's title and/or content. Omitted fields keep their
230/// value. Requires teacher+ and management rights over the course.
231#[utoipa::path(
232 patch,
233 path = "/{id}",
234 tag = "course-notes",
235 security(("session_cookie" = [])),
236 params(("id" = String, Path, description = "Course note id")),
237 request_body = UpdateCourseNote,
238 responses(
239 (status = 200, description = "Updated note", body = CourseNoteResponse),
240 (status = 400, description = "Invalid title or content", body = ErrorResponse),
241 (status = 401, description = "Not authenticated", body = ErrorResponse),
242 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
243 (status = 404, description = "Not found", body = ErrorResponse),
244 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
245 ),
246)]
247async fn update(
248 State(st): State<AppState>,
249 tenant: ResolvedTenant,
250 RequireTeacher(user): RequireTeacher,
251 Path(id): Path<String>,
252 Json(req): Json<UpdateCourseNote>,
253) -> Result<Json<CourseNoteResponse>, AppError> {
254 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
255 if !can_manage_course(&course, &user) {
256 return Err(AppError::Forbidden(
257 "only the course creator or a manager/admin can edit this course note",
258 ));
259 }
260
261 let title = req
262 .title
263 .as_deref()
264 .map(CourseNoteTitle::try_new)
265 .transpose()?;
266 let content = req
267 .content
268 .as_deref()
269 .map(CourseNoteContent::try_new)
270 .transpose()?;
271
272 let updated = service::course_note::update(&st.db, note, title, content).await?;
273 // The stored index describes the old text — refresh it.
274 spawn_index(&st, &tenant, updated.clone());
275 Ok(Json(CourseNoteResponse::new(&updated)))
276}
277
278/// Delete a course note, along with its files. Requires teacher+ and
279/// management rights over the course.
280#[utoipa::path(
281 delete,
282 path = "/{id}",
283 tag = "course-notes",
284 security(("session_cookie" = [])),
285 params(("id" = String, Path, description = "Course note id")),
286 responses(
287 (status = 204, description = "Deleted"),
288 (status = 401, description = "Not authenticated", body = ErrorResponse),
289 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
290 (status = 404, description = "Not found", 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.clone(), st.db.clone()).await?;
299 if !can_manage_course(&course, &user) {
300 return Err(AppError::Forbidden(
301 "only the course creator or a manager/admin can delete this course note",
302 ));
303 }
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) = service::course_note::delete(&st.db, note).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 (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", 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.clone(), st.db.clone()).await?;
376 if !can_manage_course(&course, &user) {
377 return Err(AppError::Forbidden(
378 "only the course creator or a manager/admin can add a file to this course note",
379 ));
380 }
381 // The 10-file cap is enforced inside `service::course_note_file::insert`
382 // (count and create in one conditional write) — checking it here too would
383 // 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 service::course_note_file::insert(&st.db, file).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 reached by the course, and not its creator or 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.clone(), st.db.clone()).await?;
438 if !can_view_course(&course, &user, &st.db).await? {
439 return Err(AppError::Forbidden(
440 "only a user this course reaches, its creator, or a manager/admin can view this course note's files",
441 ));
442 }
443 let (files, total) =
444 service::course_note_file::list_for(&st.db, note.get_id(), limit, offset).await?;
445 let items = files.iter().map(CourseNoteFileResponse::new).collect();
446 Ok(Json(Page::new(items, total, limit, offset)))
447}
448
449/// Download a course note file's bytes. `Content-Type` is the one declared on
450/// upload; `Content-Disposition` carries the original filename.
451#[utoipa::path(
452 get,
453 path = "/{id}/files/{file_id}",
454 tag = "course-notes",
455 security(("session_cookie" = [])),
456 params(
457 ("id" = String, Path, description = "Course note id"),
458 ("file_id" = String, Path, description = "File id"),
459 ),
460 responses(
461 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
462 (status = 401, description = "Not authenticated", body = ErrorResponse),
463 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
464 (status = 404, description = "Note or file not found", body = ErrorResponse),
465 ),
466)]
467async fn download_file(
468 State(st): State<AppState>,
469 CurrentUser(user): CurrentUser,
470 Path((id, file_id)): Path<(String, String)>,
471) -> Result<Response, AppError> {
472 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
473 if !can_view_course(&course, &user, &st.db).await? {
474 return Err(AppError::Forbidden(
475 "only a user this course reaches, its creator, or a manager/admin can download this course note's files",
476 ));
477 }
478 let file = service::course_note_file::read_for(
479 &st.db,
480 &CourseNoteFileId::from_key(&file_id),
481 note.get_id(),
482 )
483 .await?
484 .ok_or(AppError::NotFound)?;
485 let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key()))
486 .await
487 .map_err(|err| {
488 // The row exists but its blob doesn't — that's server-side damage
489 // (a lost volume path), not a client 404.
490 AppError::Internal(format!(
491 "missing blob for course note file {}: {err}",
492 file.get_id().key()
493 ))
494 })?;
495 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
496 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
497 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
498 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
499 Ok((
500 [
501 (CONTENT_TYPE, content_type),
502 (CONTENT_DISPOSITION, disposition),
503 ],
504 bytes,
505 )
506 .into_response())
507}
508
509/// Delete a course note file (row first, then its blob). Requires teacher+
510/// and management rights over the course.
511#[utoipa::path(
512 delete,
513 path = "/{id}/files/{file_id}",
514 tag = "course-notes",
515 security(("session_cookie" = [])),
516 params(
517 ("id" = String, Path, description = "Course note id"),
518 ("file_id" = String, Path, description = "File id"),
519 ),
520 responses(
521 (status = 204, description = "Deleted"),
522 (status = 401, description = "Not authenticated", body = ErrorResponse),
523 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
524 (status = 404, description = "Note or file not found", body = ErrorResponse),
525 ),
526)]
527async fn delete_file(
528 State(st): State<AppState>,
529 tenant: ResolvedTenant,
530 RequireTeacher(user): RequireTeacher,
531 Path((id, file_id)): Path<(String, String)>,
532) -> Result<StatusCode, AppError> {
533 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
534 if !can_manage_course(&course, &user) {
535 return Err(AppError::Forbidden(
536 "only the course creator or a manager/admin can delete this course note's files",
537 ));
538 }
539 let file = service::course_note_file::read_for(
540 &st.db,
541 &CourseNoteFileId::from_key(&file_id),
542 note.get_id(),
543 )
544 .await?
545 .ok_or(AppError::NotFound)?;
546 // Drop every link citing this file before the file itself — the file
547 // row refuses to go while one stands — so a failure here leaves the file
548 // whole instead of stranding its blob; the re-index rebuilds the
549 // outputs from what is left, if a service is connected.
550 service::rag_output::delete_with_source(&st.db, file.get_id()).await?;
551 let file = service::course_note_file::delete(&st.db, file).await?;
552 remove_blob(&st.files_path, &file.get_id().key()).await;
553 spawn_index(&st, &tenant, note);
554 Ok(StatusCode::NO_CONTENT)
555}
556
557/// One AI service output stored against a course note. `payload` is the
558/// service's own shape — the backend stores and serves it unread.
559#[derive(Serialize, ToSchema)]
560struct RagOutputResponse {
561 id: String,
562 course_note: String,
563 course: String,
564 /// The note's file attachments the output was built from.
565 sources: Vec<String>,
566 /// The service's answer, verbatim.
567 #[schema(value_type = Object)]
568 payload: serde_json::Value,
569 /// When the backend stored it, epoch milliseconds.
570 #[schema(example = 1_735_689_600_000i64)]
571 generated_at: i64,
572}
573
574impl RagOutputResponse {
575 fn new(output: &RagOutput) -> Self {
576 Self {
577 id: output.get_id().key().to_string(),
578 course_note: output.get_course_note().key().to_string(),
579 course: output.get_course().key().to_string(),
580 sources: output
581 .get_sources()
582 .iter()
583 .map(|file| file.key().to_string())
584 .collect(),
585 payload: output.get_payload().clone(),
586 generated_at: output.get_generated_at().as_millis(),
587 }
588 }
589}
590
591/// List a course note's AI outputs, newest first. Visible to whoever can view
592/// the course. Paged via `?limit=&offset=`.
593#[utoipa::path(
594 get,
595 path = "/{id}/rag",
596 tag = "course-notes",
597 security(("session_cookie" = [])),
598 params(("id" = String, Path, description = "Course note id"), PageParams),
599 responses(
600 (status = 200, description = "A page of the note's stored AI outputs", body = Page<RagOutputResponse>),
601 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
602 (status = 401, description = "Not authenticated", body = ErrorResponse),
603 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
604 (status = 404, description = "Note not found", body = ErrorResponse),
605 ),
606)]
607async fn list_rag(
608 State(st): State<AppState>,
609 CurrentUser(user): CurrentUser,
610 Path(id): Path<String>,
611 Query(page): Query<PageParams>,
612) -> Result<Json<Page<RagOutputResponse>>, AppError> {
613 let (limit, offset) = page.resolve()?;
614 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
615 if !can_view_course(&course, &user, &st.db).await? {
616 return Err(AppError::Forbidden(
617 "only a user this course reaches, its creator, or a manager/admin can view this course note's AI outputs",
618 ));
619 }
620 let (outputs, total) =
621 service::rag_output::list_for(&st.db, note.get_id(), limit, offset).await?;
622 let items = outputs.iter().map(RagOutputResponse::new).collect();
623 Ok(Json(Page::new(items, total, limit, offset)))
624}
625
626/// Delete one stored AI output. Requires teacher+ and management rights over
627/// the course. Dropping an output does not stop the next note or file change
628/// from regenerating one.
629#[utoipa::path(
630 delete,
631 path = "/{id}/rag/{output_id}",
632 tag = "course-notes",
633 security(("session_cookie" = [])),
634 params(
635 ("id" = String, Path, description = "Course note id"),
636 ("output_id" = String, Path, description = "AI output id"),
637 ),
638 responses(
639 (status = 204, description = "Deleted"),
640 (status = 401, description = "Not authenticated", body = ErrorResponse),
641 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
642 (status = 404, description = "Note or output not found", body = ErrorResponse),
643 ),
644)]
645async fn delete_rag(
646 State(st): State<AppState>,
647 RequireTeacher(user): RequireTeacher,
648 Path((id, output_id)): Path<(String, String)>,
649) -> Result<StatusCode, AppError> {
650 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
651 if !can_manage_course(&course, &user) {
652 return Err(AppError::Forbidden(
653 "only the course creator or a manager/admin can delete this course note's AI outputs",
654 ));
655 }
656 // Scoped to the note in the path, like `service::course_note_file::read_for`: an
657 // output of another note is a 404 here, never a cross-note delete.
658 let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id))
659 .await?
660 .filter(|output| output.get_course_note() == note.get_id())
661 .ok_or(AppError::NotFound)?;
662 service::rag_output::delete(&st.db, output.get_id()).await?;
663 Ok(StatusCode::NO_CONTENT)
664}
665
666/// Re-index a course note now, without waiting for its next write.
667///
668/// Indexing otherwise fires only on a note or file write, so a note saved
669/// while no AI service was connected stays unindexed until something touches
670/// it again — this door re-runs the same dispatch on demand. The `202` says
671/// the re-index was *dispatched*, not that it finished: the bridge round trip
672/// runs off the request path ([`spawn_index`]), and an unreachable service
673/// leaves the stored index as it was. Poll `GET /course-notes/{id}/rag` for
674/// the output once it lands.
675#[utoipa::path(
676 post,
677 path = "/{id}/rag/reindex",
678 tag = "course-notes",
679 security(("session_cookie" = [])),
680 params(("id" = String, Path, description = "Course note id")),
681 responses(
682 (status = 202, description = "Re-index dispatched; poll `GET /course-notes/{id}/rag` for the stored output"),
683 (status = 401, description = "Not authenticated", body = ErrorResponse),
684 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
685 (status = 404, description = "Not found", body = ErrorResponse),
686 (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse),
687 ),
688)]
689async fn reindex_rag(
690 State(st): State<AppState>,
691 tenant: ResolvedTenant,
692 RequireTeacher(user): RequireTeacher,
693 Path(id): Path<String>,
694) -> Result<Response, AppError> {
695 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
696 if !can_manage_course(&course, &user) {
697 return Err(AppError::Forbidden(
698 "only the course creator or a manager/admin can re-index this course note",
699 ));
700 }
701 // The same 503 gate `ai::rag::index_course_note` applies internally, lifted
702 // here so the caller learns why nothing will happen instead of getting a
703 // `202` for a dispatch that would silently no-op. `has_capability` is racy
704 // by design and guards no write — the note is untouched either way.
705 if !tenant.modules.contains(Module::Chatbot) {
706 return Ok(ai_unavailable(
707 "the AI service is not enabled on this deployment",
708 ));
709 }
710 let Some(bridge) = st.ai.as_ref() else {
711 return Ok(ai_unavailable(
712 "the AI service is not enabled on this deployment",
713 ));
714 };
715 if !bridge.has_capability(AI_RAG_INDEX_CAPABILITY) {
716 return Ok(ai_unavailable("no AI service is connected right now"));
717 }
718 // `note` was just read through the shared path, so the dispatched payload
719 // is the note as it stands now.
720 spawn_index(&st, &tenant, note);
721 Ok(StatusCode::ACCEPTED.into_response())
722}