| 1 | use crate::web::tenant_state::State; |
| 2 | use axum::Json; |
| 3 | use axum::extract::{Path, Query}; |
| 4 | use axum::http::StatusCode; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use utoipa::{IntoParams, ToSchema}; |
| 7 | use utoipa_axum::router::OpenApiRouter; |
| 8 | use utoipa_axum::routes; |
| 9 | |
| 10 | use std::collections::{HashMap, HashSet}; |
| 11 | |
| 12 | use crate::constant::MAX_COURSE_SECTIONS; |
| 13 | use crate::database::Database; |
| 14 | use crate::domain::class_course::{ClassCourse, DersSaati}; |
| 15 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 16 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 17 | use crate::domain::course_offering::CourseOfferingId; |
| 18 | use crate::domain::role::Role; |
| 19 | use crate::domain::subject::{SubjectDescription, SubjectName}; |
| 20 | use crate::domain::text_fold::search_fold; |
| 21 | use crate::domain::user::{User, UserId}; |
| 22 | use crate::error::{AppError, ErrorResponse}; |
| 23 | use crate::service; |
| 24 | use crate::service::course::{can_manage_course, can_view_course}; |
| 25 | use crate::state::AppState; |
| 26 | |
| 27 | use super::dto::CourseSectionRef; |
| 28 | use super::{ |
| 29 | CourseResponse, CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SubjectResponse, |
| 30 | course_people, paginate, person_map, remove_blob, |
| 31 | }; |
| 32 | |
| 33 | pub fn routes() -> OpenApiRouter<AppState> { |
| 34 | OpenApiRouter::new() |
| 35 | .routes(routes!(create_course, list_courses)) |
| 36 | .routes(routes!(my_courses)) |
| 37 | .routes(routes!(get_course, update_course, delete_course)) |
| 38 | .routes(routes!(join_member, list_members)) |
| 39 | .routes(routes!(leave_member)) |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | pub fn subject_routes() -> OpenApiRouter<AppState> { |
| 50 | OpenApiRouter::new().routes(routes!(create_subject_in_course, list_course_subjects)) |
| 51 | } |
| 52 | |
| 53 | #[derive(Deserialize, ToSchema)] |
| 54 | struct CreateCourse { |
| 55 | #[schema(max_length = 200, example = "Algebra")] |
| 56 | title: String, |
| 57 | #[schema(max_length = 2000)] |
| 58 | description: Option<String>, |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | #[schema(example = "course")] |
| 64 | kind: Option<String>, |
| 65 | } |
| 66 | |
| 67 | #[derive(Deserialize, ToSchema)] |
| 68 | struct JoinMember { |
| 69 | |
| 70 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 71 | user_id: String, |
| 72 | } |
| 73 | |
| 74 | |
| 75 | |
| 76 | #[derive(Serialize, ToSchema)] |
| 77 | struct MembershipResponse { |
| 78 | #[schema( |
| 79 | example = "019732e3-7b00-7000-8000-00000000dead_019732e3-7b00-7000-8000-00000000dead" |
| 80 | )] |
| 81 | id: String, |
| 82 | |
| 83 | course: String, |
| 84 | user: PersonRef, |
| 85 | |
| 86 | added_by: PersonRef, |
| 87 | |
| 88 | created_at: i64, |
| 89 | } |
| 90 | |
| 91 | impl MembershipResponse { |
| 92 | fn new( |
| 93 | membership: &crate::domain::course_membership::CourseMembership, |
| 94 | people: &std::collections::HashMap<String, PersonRef>, |
| 95 | ) -> Self { |
| 96 | Self { |
| 97 | id: membership.get_id().key(), |
| 98 | course: membership.get_course().key().to_string(), |
| 99 | user: PersonRef::resolve(people, membership.get_user()), |
| 100 | added_by: PersonRef::resolve(people, membership.get_added_by()), |
| 101 | created_at: membership.get_created_at().as_millis(), |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | #[derive(Deserialize, ToSchema)] |
| 107 | struct UpdateCourse { |
| 108 | #[schema(max_length = 200)] |
| 109 | title: Option<String>, |
| 110 | #[schema(max_length = 2000)] |
| 111 | description: Option<String>, |
| 112 | |
| 113 | |
| 114 | kind: Option<String>, |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | fn owns_course(course: &Course, user: &User) -> bool { |
| 122 | can_manage_course(course, user) |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> { |
| 137 | visible_courses_filtered(user, db, None, None, None).await |
| 138 | } |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | pub(crate) async fn visible_courses_filtered( |
| 147 | user: &User, |
| 148 | db: &Database, |
| 149 | kind: Option<CourseKind>, |
| 150 | q: Option<&str>, |
| 151 | taught: Option<bool>, |
| 152 | ) -> Result<Vec<Course>, AppError> { |
| 153 | if user.get_role().at_least(Role::Manager) { |
| 154 | return service::course::list_filtered(db, kind, q, taught).await; |
| 155 | } |
| 156 | let mut courses = if user.get_role().at_least(Role::Teacher) { |
| 157 | service::course::list_for_teacher(db, user.get_id()).await? |
| 158 | } else { |
| 159 | Vec::new() |
| 160 | }; |
| 161 | for course in service::course::list_enrolled(db, user.get_id(), None, 0) |
| 162 | .await? |
| 163 | .0 |
| 164 | { |
| 165 | if !courses |
| 166 | .iter() |
| 167 | .any(|known| known.get_id() == course.get_id()) |
| 168 | { |
| 169 | courses.push(course); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | courses.sort_by_key(|course| std::cmp::Reverse(course.get_id().key())); |
| 174 | |
| 175 | |
| 176 | let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); |
| 177 | courses.retain(|course| { |
| 178 | kind.as_ref().is_none_or(|want| course.get_kind() == want) |
| 179 | && taught.is_none_or(|taught| (course.get_class_course_count() > 0) == taught) |
| 180 | && needle.as_deref().is_none_or(|needle| { |
| 181 | search_fold(course.get_title().as_str()).contains(needle) |
| 182 | || search_fold(course.get_description().as_str()).contains(needle) |
| 183 | }) |
| 184 | }); |
| 185 | Ok(courses) |
| 186 | } |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | pub(crate) async fn sections_of( |
| 208 | db: &Database, |
| 209 | courses: &[Course], |
| 210 | viewer: Option<&User>, |
| 211 | ) -> Result<HashMap<String, Vec<CourseSectionRef>>, AppError> { |
| 212 | let mut by_course: HashMap<String, Vec<CourseSectionRef>> = HashMap::new(); |
| 213 | if courses.is_empty() { |
| 214 | return Ok(by_course); |
| 215 | } |
| 216 | let ids: Vec<CourseId> = courses.iter().map(|course| course.get_id().clone()).collect(); |
| 217 | let mut instances = crate::db::class_course::list_for_course_ids(db, &ids).await?; |
| 218 | if let Some(viewer) = viewer { |
| 219 | let reachable: HashSet<String> = reached_instances(db, viewer) |
| 220 | .await? |
| 221 | .into_iter() |
| 222 | .map(|instance| instance.get_id().key()) |
| 223 | .collect(); |
| 224 | instances.retain(|instance| reachable.contains(&instance.get_id().key())); |
| 225 | } |
| 226 | let with_teachers = crate::db::class_course_teacher::into_instances(db, instances).await?; |
| 227 | for section in section_refs(db, with_teachers).await? { |
| 228 | by_course |
| 229 | .entry(section.course.clone()) |
| 230 | .or_default() |
| 231 | .push(section); |
| 232 | } |
| 233 | for sections in by_course.values_mut() { |
| 234 | sections.truncate(MAX_COURSE_SECTIONS); |
| 235 | } |
| 236 | Ok(by_course) |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | pub(crate) async fn reached_sections( |
| 246 | db: &Database, |
| 247 | user: &User, |
| 248 | ) -> Result<Vec<CourseSectionRef>, AppError> { |
| 249 | let instances = reached_instances(db, user).await?; |
| 250 | let with_teachers = crate::db::class_course_teacher::into_instances(db, instances).await?; |
| 251 | section_refs(db, with_teachers).await |
| 252 | } |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | pub(crate) async fn reached_instances( |
| 267 | db: &Database, |
| 268 | user: &User, |
| 269 | ) -> Result<Vec<ClassCourse>, AppError> { |
| 270 | let mut instances: Vec<ClassCourse> = crate::service::instance::visible_instances(user, db) |
| 271 | .await? |
| 272 | .into_iter() |
| 273 | .map(|(instance, _)| instance) |
| 274 | .collect(); |
| 275 | let known: HashSet<String> = instances |
| 276 | .iter() |
| 277 | .map(|instance| instance.get_id().key()) |
| 278 | .collect(); |
| 279 | let missing: Vec<crate::domain::class_course::ClassCourseId> = |
| 280 | crate::db::enrollment::list_for_user(db, user.get_id()) |
| 281 | .await? |
| 282 | .iter() |
| 283 | .map(|enrollment| enrollment.get_class_course().clone()) |
| 284 | .filter(|id| !known.contains(&id.key())) |
| 285 | .collect(); |
| 286 | |
| 287 | |
| 288 | |
| 289 | instances.extend(crate::db::class_course::list_by_ids(db, &missing).await?); |
| 290 | Ok(instances) |
| 291 | } |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | pub(crate) async fn section_refs( |
| 298 | db: &Database, |
| 299 | rows: Vec<(ClassCourse, Vec<UserId>)>, |
| 300 | ) -> Result<Vec<CourseSectionRef>, AppError> { |
| 301 | if rows.is_empty() { |
| 302 | return Ok(Vec::new()); |
| 303 | } |
| 304 | let mut class_ids: Vec<ClassGroupId> = Vec::new(); |
| 305 | let mut offering_ids: Vec<CourseOfferingId> = Vec::new(); |
| 306 | for (instance, _) in &rows { |
| 307 | if !class_ids.contains(instance.get_class()) { |
| 308 | class_ids.push(instance.get_class().clone()); |
| 309 | } |
| 310 | if !offering_ids.contains(instance.get_offering()) { |
| 311 | offering_ids.push(instance.get_offering().clone()); |
| 312 | } |
| 313 | } |
| 314 | let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?; |
| 315 | let class_by_key: HashMap<String, &ClassGroup> = classes |
| 316 | .iter() |
| 317 | .map(|class| (class.get_id().key(), class)) |
| 318 | .collect(); |
| 319 | |
| 320 | |
| 321 | |
| 322 | let offerings = crate::db::course_offering::list_by_ids(db, &offering_ids).await?; |
| 323 | let hours_by_offering: HashMap<String, Option<DersSaati>> = offerings |
| 324 | .iter() |
| 325 | .map(|offering| { |
| 326 | ( |
| 327 | offering.get_id().key(), |
| 328 | offering.get_default_ders_saati(), |
| 329 | ) |
| 330 | }) |
| 331 | .collect(); |
| 332 | let refs: Vec<&ClassCourse> = |
| 333 | rows.iter().map(|(instance, _)| instance).collect(); |
| 334 | let content = crate::service::instance_resolve::resolved_content(db, &refs).await?; |
| 335 | let people = person_map( |
| 336 | rows.iter() |
| 337 | .flat_map(|(_, teachers)| teachers.iter().cloned()), |
| 338 | db, |
| 339 | ) |
| 340 | .await?; |
| 341 | let mut sections = Vec::with_capacity(rows.len()); |
| 342 | for (instance, teachers) in &rows { |
| 343 | let key = instance.get_id().key(); |
| 344 | let resolved = content |
| 345 | .get(&key) |
| 346 | .expect("resolved_content covers every instance it is given"); |
| 347 | let class = class_by_key |
| 348 | .get(&instance.get_class().key()) |
| 349 | .expect("every section's class is in the batch read"); |
| 350 | let ders_saati = instance |
| 351 | .get_ders_saati() |
| 352 | .or_else(|| { |
| 353 | hours_by_offering |
| 354 | .get(&instance.get_offering().key()) |
| 355 | .copied() |
| 356 | .flatten() |
| 357 | }) |
| 358 | .unwrap_or_else(|| { |
| 359 | DersSaati::try_new(crate::constant::MIN_DERS_SAATI) |
| 360 | .expect("the floor is a valid weekly-hours count") |
| 361 | }); |
| 362 | sections.push(CourseSectionRef { |
| 363 | id: key, |
| 364 | course: instance.get_course().key(), |
| 365 | class: instance.get_class().key(), |
| 366 | class_name: class.get_name().as_str().to_string(), |
| 367 | title: resolved.title.clone(), |
| 368 | grade_level: class.get_grade_level().get(), |
| 369 | ders_saati: ders_saati.as_i64(), |
| 370 | teachers: teachers |
| 371 | .iter() |
| 372 | .map(|teacher| PersonRef::resolve(&people, teacher)) |
| 373 | .collect(), |
| 374 | enrollment_count: instance.get_enrollment_count(), |
| 375 | }); |
| 376 | } |
| 377 | Ok(sections) |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | #[utoipa::path( |
| 389 | post, |
| 390 | path = "/", |
| 391 | tag = "courses", |
| 392 | security(("session_cookie" = [])), |
| 393 | request_body = CreateCourse, |
| 394 | responses( |
| 395 | (status = 201, description = "Course created", body = CourseResponse), |
| 396 | (status = 400, description = "Invalid fields or kind", body = ErrorResponse), |
| 397 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 398 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 399 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 400 | ), |
| 401 | )] |
| 402 | async fn create_course( |
| 403 | State(st): State<AppState>, |
| 404 | RequireTeacher(user): RequireTeacher, |
| 405 | Json(req): Json<CreateCourse>, |
| 406 | ) -> Result<(StatusCode, Json<CourseResponse>), AppError> { |
| 407 | let title = CourseTitle::try_new(&req.title)?; |
| 408 | let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; |
| 409 | let kind = match req.kind { |
| 410 | Some(ref kind) => CourseKind::try_new(kind)?, |
| 411 | None => CourseKind::course(), |
| 412 | }; |
| 413 | let course = service::course::create(&st.db, user.get_id(), title, description, kind).await?; |
| 414 | |
| 415 | let people = PersonRef::map_of(&[&user]); |
| 416 | Ok(( |
| 417 | StatusCode::CREATED, |
| 418 | Json(CourseResponse::new(&course, &people)), |
| 419 | )) |
| 420 | } |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | #[derive(Debug, Deserialize, IntoParams)] |
| 426 | struct CourseListFilter { |
| 427 | |
| 428 | |
| 429 | #[param(example = "course")] |
| 430 | kind: Option<String>, |
| 431 | |
| 432 | |
| 433 | #[param(example = "matematik")] |
| 434 | q: Option<String>, |
| 435 | |
| 436 | |
| 437 | #[param(example = true)] |
| 438 | taught: Option<bool>, |
| 439 | } |
| 440 | |
| 441 | |
| 442 | |
| 443 | #[derive(Debug)] |
| 444 | struct ResolvedCourseFilter { |
| 445 | kind: Option<CourseKind>, |
| 446 | q: Option<String>, |
| 447 | taught: Option<bool>, |
| 448 | } |
| 449 | |
| 450 | impl CourseListFilter { |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | fn resolve(self) -> Result<ResolvedCourseFilter, AppError> { |
| 457 | let kind = match self.kind { |
| 458 | Some(kind) => Some(CourseKind::try_new(&kind)?), |
| 459 | None => None, |
| 460 | }; |
| 461 | Ok(ResolvedCourseFilter { |
| 462 | kind, |
| 463 | q: self.q, |
| 464 | taught: self.taught, |
| 465 | }) |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | #[utoipa::path( |
| 481 | get, |
| 482 | path = "/", |
| 483 | tag = "courses", |
| 484 | security(("session_cookie" = [])), |
| 485 | params(CourseListFilter, PageParams), |
| 486 | responses( |
| 487 | (status = 200, description = "A page of the caller's visible courses (all of them when unpaged)", body = Page<CourseResponse>), |
| 488 | (status = 400, description = "Unknown or empty kind, a `taught` that is not true/false, or invalid limit or offset", body = ErrorResponse), |
| 489 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 490 | ), |
| 491 | )] |
| 492 | async fn list_courses( |
| 493 | State(st): State<AppState>, |
| 494 | CurrentUser(user): CurrentUser, |
| 495 | Query(filter): Query<CourseListFilter>, |
| 496 | Query(page): Query<PageParams>, |
| 497 | ) -> Result<Json<Page<CourseResponse>>, AppError> { |
| 498 | let (limit, offset) = page.resolve()?; |
| 499 | let filters = filter.resolve()?; |
| 500 | |
| 501 | |
| 502 | |
| 503 | let courses = |
| 504 | visible_courses_filtered(&user, &st.db, filters.kind, filters.q.as_deref(), filters.taught) |
| 505 | .await?; |
| 506 | let total = courses.len() as i64; |
| 507 | |
| 508 | let window = paginate(&courses, limit, offset); |
| 509 | |
| 510 | let people = person_map(window.iter().flat_map(course_people), &st.db).await?; |
| 511 | |
| 512 | |
| 513 | |
| 514 | let viewer = (!user.get_role().at_least(Role::Manager)).then_some(&user); |
| 515 | let mut sections = sections_of(&st.db, window, viewer).await?; |
| 516 | |
| 517 | |
| 518 | |
| 519 | |
| 520 | |
| 521 | |
| 522 | let items = window |
| 523 | .iter() |
| 524 | .map(|course| { |
| 525 | let own = sections.remove(&course.get_id().key()).unwrap_or_default(); |
| 526 | CourseResponse::with_sections(course, &people, own) |
| 527 | }) |
| 528 | .collect(); |
| 529 | Ok(Json(Page::new(items, total, limit, offset))) |
| 530 | } |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | #[utoipa::path( |
| 543 | get, |
| 544 | path = "/me", |
| 545 | tag = "courses", |
| 546 | security(("session_cookie" = [])), |
| 547 | params(PageParams), |
| 548 | responses( |
| 549 | (status = 200, description = "A page of the caller's sections (all of them when unpaged)", body = Page<CourseSectionRef>), |
| 550 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 551 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 552 | ), |
| 553 | )] |
| 554 | async fn my_courses( |
| 555 | State(st): State<AppState>, |
| 556 | CurrentUser(user): CurrentUser, |
| 557 | Query(page): Query<PageParams>, |
| 558 | ) -> Result<Json<Page<CourseSectionRef>>, AppError> { |
| 559 | let (limit, offset) = page.resolve()?; |
| 560 | |
| 561 | |
| 562 | let sections = reached_sections(&st.db, &user).await?; |
| 563 | let total = sections.len() as i64; |
| 564 | let window = paginate(§ions, limit, offset); |
| 565 | Ok(Json(Page::new(window.to_vec(), total, limit, offset))) |
| 566 | } |
| 567 | |
| 568 | |
| 569 | |
| 570 | |
| 571 | |
| 572 | #[utoipa::path( |
| 573 | get, |
| 574 | path = "/{id}", |
| 575 | tag = "courses", |
| 576 | security(("session_cookie" = [])), |
| 577 | params(("id" = String, Path, description = "Course id")), |
| 578 | responses( |
| 579 | (status = 200, description = "The course", body = CourseResponse), |
| 580 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 581 | (status = 403, description = "Not reached by this course, and not a still-`teacher`+ course creator or manager/admin", body = ErrorResponse), |
| 582 | (status = 404, description = "Not found", body = ErrorResponse), |
| 583 | ), |
| 584 | )] |
| 585 | async fn get_course( |
| 586 | State(st): State<AppState>, |
| 587 | CurrentUser(user): CurrentUser, |
| 588 | Path(id): Path<String>, |
| 589 | ) -> Result<Json<CourseResponse>, AppError> { |
| 590 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 591 | .await? |
| 592 | .ok_or(AppError::NotFound)?; |
| 593 | if !can_view_course(&course, &user, &st.db).await? { |
| 594 | return Err(AppError::Forbidden( |
| 595 | "only a student enrolled in one of this course's instances, a member of it, its creator, or a manager/admin can view this course", |
| 596 | )); |
| 597 | } |
| 598 | let people = person_map(course_people(&course), &st.db).await?; |
| 599 | let viewer = (!user.get_role().at_least(Role::Manager)).then_some(&user); |
| 600 | let mut sections = sections_of(&st.db, std::slice::from_ref(&course), viewer).await?; |
| 601 | let own = sections |
| 602 | .remove(&course.get_id().key()) |
| 603 | .unwrap_or_default(); |
| 604 | Ok(Json(CourseResponse::with_sections(&course, &people, own))) |
| 605 | } |
| 606 | |
| 607 | |
| 608 | |
| 609 | #[utoipa::path( |
| 610 | patch, |
| 611 | path = "/{id}", |
| 612 | tag = "courses", |
| 613 | security(("session_cookie" = [])), |
| 614 | params(("id" = String, Path, description = "Course id")), |
| 615 | request_body = UpdateCourse, |
| 616 | responses( |
| 617 | (status = 200, description = "Updated course", body = CourseResponse), |
| 618 | (status = 400, description = "Invalid fields or kind", body = ErrorResponse), |
| 619 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 620 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 621 | (status = 404, description = "Not found", body = ErrorResponse), |
| 622 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 623 | ), |
| 624 | )] |
| 625 | async fn update_course( |
| 626 | State(st): State<AppState>, |
| 627 | RequireTeacher(user): RequireTeacher, |
| 628 | Path(id): Path<String>, |
| 629 | Json(req): Json<UpdateCourse>, |
| 630 | ) -> Result<Json<CourseResponse>, AppError> { |
| 631 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 632 | .await? |
| 633 | .ok_or(AppError::NotFound)?; |
| 634 | if !can_manage_course(&course, &user) { |
| 635 | return Err(AppError::Forbidden( |
| 636 | "only the course creator or a manager/admin can edit this course", |
| 637 | )); |
| 638 | } |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | let title = req.title.as_deref().map(CourseTitle::try_new).transpose()?; |
| 644 | let description = req |
| 645 | .description |
| 646 | .as_deref() |
| 647 | .map(CourseDescription::try_new) |
| 648 | .transpose()?; |
| 649 | let kind = req.kind.as_deref().map(CourseKind::try_new).transpose()?; |
| 650 | |
| 651 | let updated = service::course::update(&st.db, course, title, description, kind).await?; |
| 652 | let people = person_map(course_people(&updated), &st.db).await?; |
| 653 | Ok(Json(CourseResponse::new(&updated, &people))) |
| 654 | } |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | #[utoipa::path( |
| 669 | delete, |
| 670 | path = "/{id}", |
| 671 | tag = "courses", |
| 672 | security(("session_cookie" = [])), |
| 673 | params(("id" = String, Path, description = "Course id")), |
| 674 | responses( |
| 675 | (status = 204, description = "Deleted"), |
| 676 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 677 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 678 | (status = 404, description = "Not found", body = ErrorResponse), |
| 679 | (status = 409, description = "A class still teaches this course, or students still hold an individual membership in it", body = ErrorResponse), |
| 680 | ), |
| 681 | )] |
| 682 | async fn delete_course( |
| 683 | State(st): State<AppState>, |
| 684 | RequireTeacher(user): RequireTeacher, |
| 685 | Path(id): Path<String>, |
| 686 | ) -> Result<StatusCode, AppError> { |
| 687 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 688 | .await? |
| 689 | .ok_or(AppError::NotFound)?; |
| 690 | if !owns_course(&course, &user) { |
| 691 | return Err(AppError::Forbidden( |
| 692 | "only the course creator or a manager/admin can delete this course", |
| 693 | )); |
| 694 | } |
| 695 | |
| 696 | |
| 697 | |
| 698 | let outcome = service::course::delete(&st.db, &course).await?; |
| 699 | if !outcome.deleted { |
| 700 | return Err(AppError::Conflict( |
| 701 | "a class still teaches this course, or students still hold an individual \ |
| 702 | membership in it — detach the classes and remove the members first", |
| 703 | )); |
| 704 | } |
| 705 | for file in outcome |
| 706 | .image_files |
| 707 | .iter() |
| 708 | .chain(&outcome.answer_image_files) |
| 709 | .chain(&outcome.homework_files) |
| 710 | .chain(&outcome.course_note_files) |
| 711 | { |
| 712 | remove_blob(&st.files_path, file).await; |
| 713 | } |
| 714 | Ok(StatusCode::NO_CONTENT) |
| 715 | } |
| 716 | |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 723 | |
| 724 | |
| 725 | |
| 726 | #[utoipa::path( |
| 727 | post, |
| 728 | path = "/{id}/members", |
| 729 | tag = "courses", |
| 730 | security(("session_cookie" = [])), |
| 731 | params(("id" = String, Path, description = "Course id")), |
| 732 | request_body = JoinMember, |
| 733 | responses( |
| 734 | (status = 200, description = "Member added (or already a member)", body = MembershipResponse), |
| 735 | (status = 400, description = "Unknown user, user is not a student, or the course is a class-delivered ders", body = ErrorResponse), |
| 736 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 737 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 738 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 739 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 740 | ), |
| 741 | )] |
| 742 | async fn join_member( |
| 743 | State(st): State<AppState>, |
| 744 | RequireTeacher(user): RequireTeacher, |
| 745 | Path(id): Path<String>, |
| 746 | Json(req): Json<JoinMember>, |
| 747 | ) -> Result<Json<MembershipResponse>, AppError> { |
| 748 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 749 | .await? |
| 750 | .ok_or(AppError::NotFound)?; |
| 751 | if !can_manage_course(&course, &user) { |
| 752 | return Err(AppError::Forbidden( |
| 753 | "only the course creator or a manager/admin can add members to this course", |
| 754 | )); |
| 755 | } |
| 756 | let target = UserId::from_key(&req.user_id); |
| 757 | let membership = |
| 758 | service::enrollment::join_activity(&st.db, course.get_id(), &target, user.get_id()).await?; |
| 759 | let people = person_map([target, *user.get_id()], &st.db).await?; |
| 760 | Ok(Json(MembershipResponse::new(&membership, &people))) |
| 761 | } |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | #[utoipa::path( |
| 768 | get, |
| 769 | path = "/{id}/members", |
| 770 | tag = "courses", |
| 771 | security(("session_cookie" = [])), |
| 772 | params(("id" = String, Path, description = "Course id"), PageParams), |
| 773 | responses( |
| 774 | (status = 200, description = "A page of members (the whole list when unpaged)", body = Page<MembershipResponse>), |
| 775 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 776 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 777 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 778 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 779 | ), |
| 780 | )] |
| 781 | async fn list_members( |
| 782 | State(st): State<AppState>, |
| 783 | RequireTeacher(user): RequireTeacher, |
| 784 | Path(id): Path<String>, |
| 785 | Query(page): Query<PageParams>, |
| 786 | ) -> Result<Json<Page<MembershipResponse>>, AppError> { |
| 787 | let (limit, offset) = page.resolve()?; |
| 788 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 789 | .await? |
| 790 | .ok_or(AppError::NotFound)?; |
| 791 | if !can_manage_course(&course, &user) { |
| 792 | return Err(AppError::Forbidden( |
| 793 | "only the course creator or a manager/admin can list this course's members", |
| 794 | )); |
| 795 | } |
| 796 | let (rows, total) = |
| 797 | crate::db::course_membership::list_for_course(&st.db, course.get_id(), limit, offset) |
| 798 | .await?; |
| 799 | |
| 800 | let people = person_map( |
| 801 | rows.iter() |
| 802 | .flat_map(|row| [*row.get_user(), *row.get_added_by()]), |
| 803 | &st.db, |
| 804 | ) |
| 805 | .await?; |
| 806 | let items = rows |
| 807 | .iter() |
| 808 | .map(|row| MembershipResponse::new(row, &people)) |
| 809 | .collect(); |
| 810 | Ok(Json(Page::new(items, total, limit, offset))) |
| 811 | } |
| 812 | |
| 813 | |
| 814 | |
| 815 | |
| 816 | |
| 817 | #[utoipa::path( |
| 818 | delete, |
| 819 | path = "/{id}/members/{user}", |
| 820 | tag = "courses", |
| 821 | security(("session_cookie" = [])), |
| 822 | params( |
| 823 | ("id" = String, Path, description = "Course id"), |
| 824 | ("user" = String, Path, description = "User id"), |
| 825 | ), |
| 826 | responses( |
| 827 | (status = 204, description = "Removed"), |
| 828 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 829 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 830 | (status = 404, description = "Course not found, or that user held no membership", body = ErrorResponse), |
| 831 | ), |
| 832 | )] |
| 833 | async fn leave_member( |
| 834 | State(st): State<AppState>, |
| 835 | RequireTeacher(user): RequireTeacher, |
| 836 | Path((id, target)): Path<(String, String)>, |
| 837 | ) -> Result<StatusCode, AppError> { |
| 838 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 839 | .await? |
| 840 | .ok_or(AppError::NotFound)?; |
| 841 | if !can_manage_course(&course, &user) { |
| 842 | return Err(AppError::Forbidden( |
| 843 | "only the course creator or a manager/admin can remove members from this course", |
| 844 | )); |
| 845 | } |
| 846 | service::enrollment::leave_activity(&st.db, course.get_id(), &UserId::from_key(&target)) |
| 847 | .await?; |
| 848 | Ok(StatusCode::NO_CONTENT) |
| 849 | } |
| 850 | |
| 851 | |
| 852 | |
| 853 | |
| 854 | |
| 855 | #[derive(Deserialize, ToSchema)] |
| 856 | struct CreateSubject { |
| 857 | #[schema(max_length = 200, example = "Limits and continuity")] |
| 858 | name: String, |
| 859 | #[schema(max_length = 2000)] |
| 860 | description: Option<String>, |
| 861 | } |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | #[utoipa::path( |
| 868 | post, |
| 869 | path = "/{id}/subjects", |
| 870 | tag = "subjects", |
| 871 | security(("session_cookie" = [])), |
| 872 | params(("id" = String, Path, description = "Course id")), |
| 873 | request_body = CreateSubject, |
| 874 | responses( |
| 875 | (status = 201, description = "Subject created", body = SubjectResponse), |
| 876 | (status = 400, description = "Invalid name or description", body = ErrorResponse), |
| 877 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 878 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 879 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 880 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 881 | ), |
| 882 | )] |
| 883 | async fn create_subject_in_course( |
| 884 | State(st): State<AppState>, |
| 885 | RequireTeacher(user): RequireTeacher, |
| 886 | Path(id): Path<String>, |
| 887 | Json(req): Json<CreateSubject>, |
| 888 | ) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { |
| 889 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 890 | .await? |
| 891 | .ok_or(AppError::NotFound)?; |
| 892 | if !can_manage_course(&course, &user) { |
| 893 | return Err(AppError::Forbidden( |
| 894 | "only the course creator or a manager/admin can add subjects to this course", |
| 895 | )); |
| 896 | } |
| 897 | |
| 898 | let name = SubjectName::try_new(&req.name)?; |
| 899 | let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; |
| 900 | let subject = service::subject::create(&st.db, course.get_id(), name, description).await?; |
| 901 | Ok((StatusCode::CREATED, Json(SubjectResponse::new(&subject)))) |
| 902 | } |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | |
| 909 | #[utoipa::path( |
| 910 | get, |
| 911 | path = "/{id}/subjects", |
| 912 | tag = "subjects", |
| 913 | security(("session_cookie" = [])), |
| 914 | params(("id" = String, Path, description = "Course id"), PageParams), |
| 915 | responses( |
| 916 | (status = 200, description = "A page of the course's subjects (all of them when unpaged)", body = Page<SubjectResponse>), |
| 917 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 918 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 919 | (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse), |
| 920 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 921 | ), |
| 922 | )] |
| 923 | async fn list_course_subjects( |
| 924 | State(st): State<AppState>, |
| 925 | CurrentUser(user): CurrentUser, |
| 926 | Path(id): Path<String>, |
| 927 | Query(page): Query<PageParams>, |
| 928 | ) -> Result<Json<Page<SubjectResponse>>, AppError> { |
| 929 | let (limit, offset) = page.resolve()?; |
| 930 | |
| 931 | let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 932 | .await? |
| 933 | .ok_or(AppError::NotFound)?; |
| 934 | if !can_view_course(&course, &user, &st.db).await? { |
| 935 | return Err(AppError::Forbidden( |
| 936 | "only a user this course reaches, its creator, or a manager/admin can view this course", |
| 937 | )); |
| 938 | } |
| 939 | let (subjects, total) = |
| 940 | service::subject::list_for_course(&st.db, course.get_id(), limit, offset).await?; |
| 941 | let items = subjects.iter().map(SubjectResponse::new).collect(); |
| 942 | Ok(Json(Page::new(items, total, limit, offset))) |
| 943 | } |
| 944 | |
| 945 | #[cfg(test)] |
| 946 | mod tests { |
| 947 | use super::*; |
| 948 | use crate::database::init_test_db; |
| 949 | use crate::domain::user::Username; |
| 950 | |
| 951 | |
| 952 | async fn user(username: &str, role: Role, db: &Database) -> User { |
| 953 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) |
| 954 | .await |
| 955 | .unwrap(); |
| 956 | crate::service::user::set_role(db, user.get_id(), role) |
| 957 | .await |
| 958 | .unwrap() |
| 959 | .0 |
| 960 | } |
| 961 | |
| 962 | |
| 963 | async fn course(creator: &User, db: &Database) -> Course { |
| 964 | service::course::create( |
| 965 | db, |
| 966 | creator.get_id(), |
| 967 | CourseTitle::try_new("Matematik").unwrap(), |
| 968 | CourseDescription::try_new("").unwrap(), |
| 969 | CourseKind::try_new("course").unwrap(), |
| 970 | ) |
| 971 | .await |
| 972 | .unwrap() |
| 973 | } |
| 974 | |
| 975 | |
| 976 | |
| 977 | async fn shaped_course( |
| 978 | creator: &User, |
| 979 | db: &Database, |
| 980 | title: &str, |
| 981 | description: &str, |
| 982 | kind: &str, |
| 983 | ) -> Course { |
| 984 | service::course::create( |
| 985 | db, |
| 986 | creator.get_id(), |
| 987 | CourseTitle::try_new(title).unwrap(), |
| 988 | CourseDescription::try_new(description).unwrap(), |
| 989 | CourseKind::try_new(kind).unwrap(), |
| 990 | ) |
| 991 | .await |
| 992 | .unwrap() |
| 993 | } |
| 994 | |
| 995 | fn titles(courses: &[Course]) -> Vec<&str> { |
| 996 | courses |
| 997 | .iter() |
| 998 | .map(|course| course.get_title().as_str()) |
| 999 | .collect() |
| 1000 | } |
| 1001 | |
| 1002 | fn a_kind(kind: &str) -> CourseKind { |
| 1003 | CourseKind::try_new(kind).unwrap() |
| 1004 | } |
| 1005 | |
| 1006 | |
| 1007 | |
| 1008 | #[tokio::test] |
| 1009 | async fn the_kind_filter_parses_through_the_write_path() { |
| 1010 | for kind in ["nope", ""] { |
| 1011 | let err = CourseListFilter { |
| 1012 | kind: Some(kind.to_string()), |
| 1013 | q: None, |
| 1014 | taught: None, |
| 1015 | } |
| 1016 | .resolve() |
| 1017 | .unwrap_err(); |
| 1018 | assert!( |
| 1019 | matches!( |
| 1020 | &err, |
| 1021 | AppError::Validation(crate::error::ValidationError::Invalid { field, .. }) |
| 1022 | if *field == "kind" |
| 1023 | ), |
| 1024 | "{kind:?}: {err:?}" |
| 1025 | ); |
| 1026 | } |
| 1027 | let resolved = CourseListFilter { |
| 1028 | kind: Some("club".to_string()), |
| 1029 | q: Some(" ".to_string()), |
| 1030 | taught: None, |
| 1031 | } |
| 1032 | .resolve() |
| 1033 | .unwrap(); |
| 1034 | assert_eq!(resolved.kind.as_ref().map(CourseKind::as_str), Some("club")); |
| 1035 | assert_eq!(resolved.q.as_deref(), Some(" ")); |
| 1036 | assert_eq!(resolved.taught, None); |
| 1037 | } |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | #[tokio::test] |
| 1042 | async fn kind_and_q_narrow_the_manager_catalog() { |
| 1043 | let (db, _leases) = init_test_db().await; |
| 1044 | let boss = user("boss", Role::Manager, &db).await; |
| 1045 | shaped_course(&boss, &db, "Matematik", "Cebir ve Geometri", "course").await; |
| 1046 | shaped_course(&boss, &db, "Satranç Kulübü", "", "club").await; |
| 1047 | shaped_course(&boss, &db, "Biyoloji Etüdü", "canlı yayın", "study").await; |
| 1048 | |
| 1049 | |
| 1050 | let class = crate::db::class_group::create( |
| 1051 | &db, |
| 1052 | boss.get_id(), |
| 1053 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), |
| 1054 | crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 1055 | None, |
| 1056 | None, |
| 1057 | ) |
| 1058 | .await |
| 1059 | .unwrap(); |
| 1060 | let matematik = visible_courses_filtered(&boss, &db, None, None, None) |
| 1061 | .await |
| 1062 | .unwrap() |
| 1063 | .into_iter() |
| 1064 | .find(|course| course.get_title().as_str() == "Matematik") |
| 1065 | .unwrap(); |
| 1066 | service::class_course::attach(&db, class.get_id(), matematik.get_id(), boss.get_id()) |
| 1067 | .await |
| 1068 | .unwrap(); |
| 1069 | |
| 1070 | |
| 1071 | |
| 1072 | let all = visible_courses_filtered(&boss, &db, None, None, None) |
| 1073 | .await |
| 1074 | .unwrap(); |
| 1075 | assert_eq!( |
| 1076 | titles(&all), |
| 1077 | vec!["Biyoloji Etüdü", "Satranç Kulübü", "Matematik"] |
| 1078 | ); |
| 1079 | |
| 1080 | |
| 1081 | let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, None) |
| 1082 | .await |
| 1083 | .unwrap(); |
| 1084 | assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]); |
| 1085 | |
| 1086 | |
| 1087 | let q = visible_courses_filtered(&boss, &db, None, Some("SATRANÇ"), None) |
| 1088 | .await |
| 1089 | .unwrap(); |
| 1090 | assert_eq!(titles(&q), vec!["Satranç Kulübü"]); |
| 1091 | |
| 1092 | let q = visible_courses_filtered(&boss, &db, None, Some("canlı"), None) |
| 1093 | .await |
| 1094 | .unwrap(); |
| 1095 | assert_eq!(titles(&q), vec!["Biyoloji Etüdü"]); |
| 1096 | |
| 1097 | for wildcard in ["%", "_"] { |
| 1098 | let q = visible_courses_filtered(&boss, &db, None, Some(wildcard), None) |
| 1099 | .await |
| 1100 | .unwrap(); |
| 1101 | assert!(q.is_empty(), "{wildcard:?} acted as a wildcard"); |
| 1102 | } |
| 1103 | |
| 1104 | |
| 1105 | let miss = |
| 1106 | visible_courses_filtered(&boss, &db, Some(a_kind("course")), Some("satranç"), None) |
| 1107 | .await |
| 1108 | .unwrap(); |
| 1109 | assert!(miss.is_empty()); |
| 1110 | let hit = visible_courses_filtered(&boss, &db, Some(a_kind("study")), Some("CANLI"), None) |
| 1111 | .await |
| 1112 | .unwrap(); |
| 1113 | assert_eq!(titles(&hit), vec!["Biyoloji Etüdü"]); |
| 1114 | |
| 1115 | |
| 1116 | let blank = visible_courses_filtered(&boss, &db, None, Some(" "), None) |
| 1117 | .await |
| 1118 | .unwrap(); |
| 1119 | assert_eq!(titles(&blank), titles(&all)); |
| 1120 | |
| 1121 | |
| 1122 | |
| 1123 | let taught = visible_courses_filtered(&boss, &db, None, None, Some(true)) |
| 1124 | .await |
| 1125 | .unwrap(); |
| 1126 | assert_eq!(titles(&taught), vec!["Matematik"]); |
| 1127 | let untaught = visible_courses_filtered(&boss, &db, None, None, Some(false)) |
| 1128 | .await |
| 1129 | .unwrap(); |
| 1130 | assert_eq!(titles(&untaught), vec!["Biyoloji Etüdü", "Satranç Kulübü"]); |
| 1131 | let clubs = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(false)) |
| 1132 | .await |
| 1133 | .unwrap(); |
| 1134 | assert_eq!(titles(&clubs), vec!["Satranç Kulübü"]); |
| 1135 | let miss = visible_courses_filtered(&boss, &db, Some(a_kind("club")), None, Some(true)) |
| 1136 | .await |
| 1137 | .unwrap(); |
| 1138 | assert!(miss.is_empty()); |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | let dersler = visible_courses_filtered(&boss, &db, Some(a_kind("course")), None, None) |
| 1144 | .await |
| 1145 | .unwrap(); |
| 1146 | assert_eq!(dersler.len(), 1); |
| 1147 | assert_eq!(paginate(&dersler, Some(1), 0).len(), 1); |
| 1148 | } |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | #[tokio::test] |
| 1153 | async fn filters_narrow_but_never_widen_a_students_visible_set() { |
| 1154 | let (db, _leases) = init_test_db().await; |
| 1155 | let boss = user("boss2", Role::Manager, &db).await; |
| 1156 | let student = user("ogrenci", Role::Student, &db).await; |
| 1157 | let (instance, _ders) = crate::db::course::a_test_instance(&db).await; |
| 1158 | shaped_course(&boss, &db, "Satranç Kulübü", "zeka oyunu", "club").await; |
| 1159 | service::enrollment::enroll(&db, &instance, student.get_id(), boss.get_id()) |
| 1160 | .await |
| 1161 | .unwrap(); |
| 1162 | |
| 1163 | |
| 1164 | let mine = visible_courses_filtered(&student, &db, None, None, None) |
| 1165 | .await |
| 1166 | .unwrap(); |
| 1167 | assert_eq!(titles(&mine), vec!["test course"]); |
| 1168 | |
| 1169 | |
| 1170 | let clubs = visible_courses_filtered(&student, &db, Some(a_kind("club")), None, None) |
| 1171 | .await |
| 1172 | .unwrap(); |
| 1173 | assert!(clubs.is_empty()); |
| 1174 | |
| 1175 | let q = visible_courses_filtered(&student, &db, None, Some("satranç"), None) |
| 1176 | .await |
| 1177 | .unwrap(); |
| 1178 | assert!(q.is_empty()); |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | let taught = visible_courses_filtered(&student, &db, None, None, Some(true)) |
| 1183 | .await |
| 1184 | .unwrap(); |
| 1185 | assert_eq!(titles(&taught), vec!["test course"]); |
| 1186 | let untaught = visible_courses_filtered(&student, &db, None, None, Some(false)) |
| 1187 | .await |
| 1188 | .unwrap(); |
| 1189 | assert!(untaught.is_empty()); |
| 1190 | |
| 1191 | |
| 1192 | let dersler = visible_courses_filtered(&student, &db, Some(a_kind("course")), None, None) |
| 1193 | .await |
| 1194 | .unwrap(); |
| 1195 | assert_eq!(titles(&dersler), vec!["test course"]); |
| 1196 | let q = visible_courses_filtered(&student, &db, None, Some("TEST"), None) |
| 1197 | .await |
| 1198 | .unwrap(); |
| 1199 | assert_eq!(titles(&q), vec!["test course"]); |
| 1200 | } |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn an_empty_taught_is_rejected_naming_the_field() { |
| 1206 | let uri = axum::http::Uri::from_static("/courses?taught="); |
| 1207 | let err = Query::<CourseListFilter>::try_from_uri(&uri).unwrap_err(); |
| 1208 | assert!(err.to_string().contains("taught"), "{err}"); |
| 1209 | for ok in [ |
| 1210 | "/courses?taught=true", |
| 1211 | "/courses?taught=false", |
| 1212 | "/courses?q=x", |
| 1213 | "/courses", |
| 1214 | ] { |
| 1215 | let uri = axum::http::Uri::from_static(ok); |
| 1216 | assert!( |
| 1217 | Query::<CourseListFilter>::try_from_uri(&uri).is_ok(), |
| 1218 | "{ok:?} refused" |
| 1219 | ); |
| 1220 | } |
| 1221 | } |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | #[tokio::test] |
| 1226 | async fn demoted_creator_loses_management_and_ownership() { |
| 1227 | let (db, _leases) = init_test_db().await; |
| 1228 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1229 | let course = course(&creator, &db).await; |
| 1230 | assert!(can_manage_course(&course, &creator)); |
| 1231 | assert!(owns_course(&course, &creator)); |
| 1232 | |
| 1233 | for role in [Role::Student, Role::Parent] { |
| 1234 | let demoted = crate::service::user::set_role(&db, creator.get_id(), role) |
| 1235 | .await |
| 1236 | .unwrap() |
| 1237 | .0; |
| 1238 | assert!( |
| 1239 | !can_manage_course(&course, &demoted), |
| 1240 | "{role:?} creator still manages the course" |
| 1241 | ); |
| 1242 | assert!( |
| 1243 | !owns_course(&course, &demoted), |
| 1244 | "{role:?} creator still owns the course" |
| 1245 | ); |
| 1246 | } |
| 1247 | } |
| 1248 | |
| 1249 | |
| 1250 | |
| 1251 | #[tokio::test] |
| 1252 | async fn manager_still_manages_a_demoted_creators_course() { |
| 1253 | let (db, _leases) = init_test_db().await; |
| 1254 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1255 | let course = course(&creator, &db).await; |
| 1256 | crate::service::user::set_role(&db, creator.get_id(), Role::Student) |
| 1257 | .await |
| 1258 | .unwrap(); |
| 1259 | |
| 1260 | for role in [Role::Manager, Role::Admin] { |
| 1261 | let boss = user(&format!("boss{}", role.as_str()), role, &db).await; |
| 1262 | assert!(can_manage_course(&course, &boss), "{role:?} locked out"); |
| 1263 | assert!(owns_course(&course, &boss), "{role:?} cannot delete"); |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | |
| 1271 | #[tokio::test] |
| 1272 | async fn an_instance_teacher_holds_no_catalog_rights() { |
| 1273 | let (db, _leases) = init_test_db().await; |
| 1274 | let creator = user("owner", Role::Manager, &db).await; |
| 1275 | let assigned = user("assigned", Role::Teacher, &db).await; |
| 1276 | let course = course(&creator, &db).await; |
| 1277 | assert!(!can_manage_course(&course, &assigned)); |
| 1278 | assert!(!owns_course(&course, &assigned)); |
| 1279 | } |
| 1280 | } |