| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use crate::web::tenant_state::{ResolvedTenant, State}; |
| 9 | use axum::Json; |
| 10 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 11 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| 12 | use axum::http::{HeaderValue, StatusCode}; |
| 13 | use axum::response::{IntoResponse, Response}; |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use utoipa::{IntoParams, ToSchema}; |
| 16 | use utoipa_axum::router::OpenApiRouter; |
| 17 | use utoipa_axum::routes; |
| 18 | |
| 19 | use crate::ai::rag::spawn_index; |
| 20 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 21 | use crate::database::Database; |
| 22 | use crate::domain::course::{Course, CourseId}; |
| 23 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; |
| 24 | use crate::domain::course_note_file::{ |
| 25 | CourseNoteFile, CourseNoteFileId, FileContentType, FileName, |
| 26 | }; |
| 27 | use crate::domain::rag_output::{RagOutput, RagOutputId}; |
| 28 | use crate::error::{AppError, ErrorResponse}; |
| 29 | use crate::service; |
| 30 | use crate::state::AppState; |
| 31 | |
| 32 | use super::courses::{can_manage_course, can_view_course}; |
| 33 | use super::notes::content_disposition; |
| 34 | use super::{ |
| 35 | CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, read_upload, |
| 36 | remove_blob, |
| 37 | }; |
| 38 | |
| 39 | pub fn routes() -> OpenApiRouter<AppState> { |
| 40 | |
| 41 | |
| 42 | |
| 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 | |
| 58 | |
| 59 | async 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)] |
| 70 | struct 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)] |
| 83 | struct 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)] |
| 91 | struct CourseNoteResponse { |
| 92 | id: String, |
| 93 | course: String, |
| 94 | title: String, |
| 95 | content: String, |
| 96 | } |
| 97 | |
| 98 | impl 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 | |
| 110 | |
| 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 | )] |
| 127 | async 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 | |
| 146 | |
| 147 | |
| 148 | spawn_index(&st, &tenant, note.clone()); |
| 149 | Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(¬e)))) |
| 150 | } |
| 151 | |
| 152 | #[derive(Deserialize, IntoParams)] |
| 153 | struct CourseFilter { |
| 154 | |
| 155 | #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| 156 | course: String, |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 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 | )] |
| 176 | async 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 | |
| 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 | )] |
| 211 | async 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(¬e))) |
| 223 | } |
| 224 | |
| 225 | |
| 226 | |
| 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 | )] |
| 244 | async 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 | |
| 272 | spawn_index(&st, &tenant, updated.clone()); |
| 273 | Ok(Json(CourseNoteResponse::new(&updated))) |
| 274 | } |
| 275 | |
| 276 | |
| 277 | |
| 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 | )] |
| 292 | async 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 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | service::rag_output::delete_for_note(&st.db, note.get_id()).await?; |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 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 | |
| 321 | |
| 322 | #[derive(Serialize, ToSchema)] |
| 323 | struct CourseNoteFileResponse { |
| 324 | id: String, |
| 325 | |
| 326 | #[schema(example = "recap.pdf")] |
| 327 | name: String, |
| 328 | |
| 329 | #[schema(example = "application/pdf")] |
| 330 | content_type: String, |
| 331 | |
| 332 | #[schema(example = 24_576)] |
| 333 | size: i64, |
| 334 | } |
| 335 | |
| 336 | impl 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 | |
| 348 | |
| 349 | |
| 350 | |
| 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 | )] |
| 368 | async 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 | |
| 383 | |
| 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 | |
| 391 | |
| 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 | |
| 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 | |
| 415 | |
| 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 | )] |
| 430 | async 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 | |
| 449 | |
| 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 | )] |
| 466 | async 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 | |
| 485 | |
| 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 | |
| 506 | |
| 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 | )] |
| 524 | async 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 | |
| 542 | |
| 543 | |
| 544 | |
| 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 | |
| 553 | |
| 554 | #[derive(Serialize, ToSchema)] |
| 555 | struct RagOutputResponse { |
| 556 | id: String, |
| 557 | course_note: String, |
| 558 | course: String, |
| 559 | |
| 560 | sources: Vec<String>, |
| 561 | |
| 562 | #[schema(value_type = Object)] |
| 563 | payload: serde_json::Value, |
| 564 | |
| 565 | #[schema(example = 1_735_689_600_000i64)] |
| 566 | generated_at: i64, |
| 567 | } |
| 568 | |
| 569 | impl 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 | |
| 587 | |
| 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 | )] |
| 602 | async 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 | |
| 622 | |
| 623 | |
| 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 | )] |
| 641 | async 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 | |
| 654 | |
| 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 | } |