| 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 = 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)] |
| 70 | struct 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)] |
| 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 = service::course_note::create(&st.db, course.get_id(), user.get_id(), title, content) |
| 145 | .await?; |
| 146 | |
| 147 | |
| 148 | |
| 149 | spawn_index(&st, &tenant, note.clone()); |
| 150 | Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(¬e)))) |
| 151 | } |
| 152 | |
| 153 | #[derive(Deserialize, IntoParams)] |
| 154 | struct CourseFilter { |
| 155 | |
| 156 | #[param(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 157 | course: String, |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 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 | )] |
| 177 | async 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 | |
| 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 | )] |
| 212 | async 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(¬e))) |
| 224 | } |
| 225 | |
| 226 | |
| 227 | |
| 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 | )] |
| 245 | async 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 | |
| 273 | spawn_index(&st, &tenant, updated.clone()); |
| 274 | Ok(Json(CourseNoteResponse::new(&updated))) |
| 275 | } |
| 276 | |
| 277 | |
| 278 | |
| 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 | )] |
| 293 | async 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 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | service::rag_output::delete_for_note(&st.db, note.get_id()).await?; |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 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 | |
| 322 | |
| 323 | #[derive(Serialize, ToSchema)] |
| 324 | struct CourseNoteFileResponse { |
| 325 | id: String, |
| 326 | |
| 327 | #[schema(example = "recap.pdf")] |
| 328 | name: String, |
| 329 | |
| 330 | #[schema(example = "application/pdf")] |
| 331 | content_type: String, |
| 332 | |
| 333 | #[schema(example = 24_576)] |
| 334 | size: i64, |
| 335 | } |
| 336 | |
| 337 | impl 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 | |
| 349 | |
| 350 | |
| 351 | |
| 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 | )] |
| 369 | async 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 | |
| 384 | |
| 385 | |
| 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 | |
| 393 | |
| 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 | |
| 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 | |
| 417 | |
| 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 | )] |
| 432 | async 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 | |
| 452 | |
| 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 | )] |
| 469 | async 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 | |
| 491 | |
| 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 | |
| 512 | |
| 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 | )] |
| 530 | async 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 | |
| 551 | |
| 552 | |
| 553 | |
| 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 | |
| 562 | |
| 563 | #[derive(Serialize, ToSchema)] |
| 564 | struct RagOutputResponse { |
| 565 | id: String, |
| 566 | course_note: String, |
| 567 | course: String, |
| 568 | |
| 569 | sources: Vec<String>, |
| 570 | |
| 571 | #[schema(value_type = Object)] |
| 572 | payload: serde_json::Value, |
| 573 | |
| 574 | #[schema(example = 1_735_689_600_000i64)] |
| 575 | generated_at: i64, |
| 576 | } |
| 577 | |
| 578 | impl 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 | |
| 596 | |
| 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 | )] |
| 611 | async 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 | |
| 631 | |
| 632 | |
| 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 | )] |
| 650 | async 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 | |
| 663 | |
| 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 | } |