forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

courses.rs1280 lines, 53.5 KiBHistoryRawDownload
1use crate::web::tenant_state::State;
2use axum::Json;
3use axum::extract::{Path, Query};
4use axum::http::StatusCode;
5use serde::{Deserialize, Serialize};
6use utoipa::{IntoParams, ToSchema};
7use utoipa_axum::router::OpenApiRouter;
8use utoipa_axum::routes;
9
10use std::collections::{HashMap, HashSet};
11
12use crate::constant::MAX_COURSE_SECTIONS;
13use crate::database::Database;
14use crate::domain::class_course::{ClassCourse, DersSaati};
15use crate::domain::class_group::{ClassGroup, ClassGroupId};
16use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
17use crate::domain::course_offering::CourseOfferingId;
18use crate::domain::role::Role;
19use crate::domain::subject::{SubjectDescription, SubjectName};
20use crate::domain::text_fold::search_fold;
21use crate::domain::user::{User, UserId};
22use crate::error::{AppError, ErrorResponse};
23use crate::service;
24use crate::service::course::{can_manage_course, can_view_course};
25use crate::state::AppState;
26
27use super::dto::CourseSectionRef;
28use super::{
29 CourseResponse, CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SubjectResponse,
30 course_people, paginate, person_map, remove_blob,
31};
32
33pub 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// The route pair below is mounted under `/courses` but *belongs* to another
43// module, so it is split out to carry that module's gate as well as the course
44// one — see `crate::web::module_gate`. It is merged back in `build_router`, so
45// the URL space is unchanged. The exam, session and homework pairs that used to
46// sit here moved to `/instances/{id}/...` (see [`super::instances`]), because
47// they hang off the instance, not off the catalog row.
48
49pub fn subject_routes() -> OpenApiRouter<AppState> {
50 OpenApiRouter::new().routes(routes!(create_subject_in_course, list_course_subjects))
51}
52
53#[derive(Deserialize, ToSchema)]
54struct CreateCourse {
55 #[schema(max_length = 200, example = "Algebra")]
56 title: String,
57 #[schema(max_length = 2000)]
58 description: Option<String>,
59 /// `course` (a regular class — the default), `study` (a supervised study
60 /// session), or `club` (a student club). Only a `course` is taught through
61 /// class-section instances (and carries exams, sessions and homework); a
62 /// `study`/`club` is joined school-wide.
63 #[schema(example = "course")]
64 kind: Option<String>,
65}
66
67#[derive(Deserialize, ToSchema)]
68struct JoinMember {
69 /// The user to add to the club or study.
70 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
71 user_id: String,
72}
73
74/// Public shape of one individual membership in a club or study — the
75/// school-scoped tier, distinct from a class instance's roster.
76#[derive(Serialize, ToSchema)]
77struct MembershipResponse {
78 #[schema(
79 example = "019732e3-7b00-7000-8000-00000000dead_019732e3-7b00-7000-8000-00000000dead"
80 )]
81 id: String,
82 /// The course joined (`GET /courses/{id}`).
83 course: String,
84 user: PersonRef,
85 /// Who placed the membership.
86 added_by: PersonRef,
87 /// When, UTC unix-milliseconds.
88 created_at: i64,
89}
90
91impl 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)]
107struct UpdateCourse {
108 #[schema(max_length = 200)]
109 title: Option<String>,
110 #[schema(max_length = 2000)]
111 description: Option<String>,
112 /// `course`, `study` (supervised study), or `club`. Omit to keep the current
113 /// kind.
114 kind: Option<String>,
115}
116
117/// Who may destroy a catalog row: its creator, or anyone `manager` and above.
118/// Carries the same live-`teacher` floor as
119/// [`crate::service::course::can_manage_course`], and for the same reason: a
120/// demoted creator owns nothing.
121fn owns_course(course: &Course, user: &User) -> bool {
122 can_manage_course(course, user)
123}
124
125/// The catalog as one user sees it: every course for manager+, otherwise the
126/// courses they are assigned to teach somewhere plus the ones they're enrolled
127/// in, newest first.
128///
129/// The taught half carries the same live-`teacher` floor as
130/// [`crate::service::course::can_manage_course`], and for the same reason:
131/// `creator` is a historical column no demotion sweeps, so without it a
132/// demoted creator kept seeing the course — and, through the `/exams` and
133/// `/homework` catalogs that build on this list, its published exams and
134/// homework. Below `teacher` a course is visible only the way it is to any
135/// other student: by enrollment.
136pub(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/// [`visible_courses`] narrowed by the `GET /courses` filters. The filters
141/// ride *after* the visibility union and *before* any paging, so a filter can
142/// only ever narrow what the caller already reaches and `total` is the
143/// filtered length. For a manager the filters go into the catalog query
144/// itself ([`crate::service::course::list_filtered`]); below manager the
145/// union is Rust, so the same text fold filters the merged list in memory.
146pub(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 // Both sources come newest-first; re-sort so the merged list is too.
173 courses.sort_by_key(|course| std::cmp::Reverse(course.get_id().key()));
174 // The same fold both sides of the manager arm's SQL uses, so a `q`
175 // matches identically above and below manager; blank means no filter.
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/// The class sections teaching each of `courses`, keyed by course id — the
189/// builder every catalogue row and every `/courses/me` row rides.
190///
191/// Batched end to end: one query per resource for the *whole* page, never one
192/// per row and never one per section — the instance read
193/// ([`crate::db::class_course::list_for_course_ids`]), the teacher links
194/// ([`crate::db::class_course_teacher::into_instances`]), the classes
195/// ([`crate::db::class_group::list_by_ids`]), the offerings behind the resolved
196/// hours ([`crate::db::course_offering::list_by_ids`]), the resolved titles
197/// ([`crate::service::instance_resolve::resolved_content`], itself two queries)
198/// and the teachers' `PersonRef`s ([`person_map`], one query).
199///
200/// `viewer` is the narrowing rule: `Some(user)` for a non-manager keeps only
201/// the sections that caller already reaches — [`reached_instances`], the same
202/// set `GET /instances/me` serves plus their own enrollments — so a section
203/// they cannot reach, and its roster size, teacher and class, never leak here.
204/// `None` (manager+) sees every section. Sections per course are truncated to
205/// [`MAX_COURSE_SECTIONS`]; the course row's own `class_course_count` carries
206/// the untruncated total.
207pub(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/// The class sections the caller is reached by, one flat list — the shape
240/// `/courses/me` serves (it lists sections, not catalog rows, so there is no
241/// grouping to do). Rides [`reached_instances`] (class roster, homeroom,
242/// taught, or their own enrollment) and [`section_refs`] like [`sections_of`]
243/// does, so the surfaces cannot disagree about a section's resolved title or
244/// hours.
245pub(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/// The instances `user` reaches, as rows: the class-roster / homeroom / taught
255/// set ([`crate::service::instance::visible_instances`]) unioned with the
256/// instances their own **enrollment** rows place them on, de-duplicated by
257/// instance id and kept newest-first.
258///
259/// The second half is not redundant. An enrollment row is the *instance*
260/// roster, and a hand-placed one carries no class membership at all (a class
261/// row an operator later disowned is the same shape), so the class-keyed
262/// visibility set never sees it — yet that section is theirs, and both
263/// `/courses/me` and the profile course block listed it before the section
264/// split. Two reads for the union (the enrollment list plus one batched
265/// instance read of whatever it added), never one per row.
266pub(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 // `list_by_ids` orders `attached_at DESC, id DESC` — the same order the
287 // class arm of `visible_instances` produces, so the union reads newest-first
288 // end to end.
289 instances.extend(crate::db::class_course::list_by_ids(db, &missing).await?);
290 Ok(instances)
291}
292
293/// Build one [`CourseSectionRef`] per `(instance, teachers)` pair — the shared
294/// tail of [`sections_of`] and [`reached_sections`]: the classes, offerings,
295/// resolved titles and people are read once for the whole batch, then each
296/// section is assembled in memory.
297pub(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 // The resolved weekly hours chain is `resolve_policy`'s — instance
320 // override, else the offering's default, else the floor — but its offering
321 // half is read once for the batch instead of once per section.
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// ---- courses ------------------------------------------------------------
381
382/// Create a catalog course owned by the current user. Requires the `teacher`
383/// role or higher. `kind` picks the flavor — `course` (a regular class, the
384/// default), `study` (a supervised study session), or `club` (a student
385/// club). A catalog row teaches nobody by itself: a class section attaches it
386/// into an instance (`POST /classes/{id}/instances`), and a `study`/`club` is
387/// joined school-wide (`POST /courses/{id}/members`).
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)]
402async 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 // The creator is the caller — already loaded, no extra lookup.
415 let people = PersonRef::map_of(&[&user]);
416 Ok((
417 StatusCode::CREATED,
418 Json(CourseResponse::new(&course, &people)),
419 ))
420}
421
422/// The `GET /courses` filters, both optional and combinable. They narrow the
423/// caller's visible set — they never widen it: a student filtering by `kind`
424/// still sees only the courses they reach.
425#[derive(Debug, Deserialize, IntoParams)]
426struct CourseListFilter {
427 /// Narrow to one kind: `course` (a regular class), `study` (a supervised
428 /// study session), or `club`. Omit for every kind.
429 #[param(example = "course")]
430 kind: Option<String>,
431 /// Case- and diacritic-insensitive fragment of the title or description.
432 /// Omit — or leave blank — to filter nothing; `%` and `_` are literal.
433 #[param(example = "matematik")]
434 q: Option<String>,
435 /// Keep only courses taught somewhere (`true`, `class_course_count > 0`)
436 /// or nowhere yet (`false`, `= 0`). Omit for both.
437 #[param(example = true)]
438 taught: Option<bool>,
439}
440
441/// The parsed [`CourseListFilter`] — one named field per query parameter,
442/// ready for [`visible_courses_filtered`].
443#[derive(Debug)]
444struct ResolvedCourseFilter {
445 kind: Option<CourseKind>,
446 q: Option<String>,
447 taught: Option<bool>,
448}
449
450impl CourseListFilter {
451 /// `kind` parses through the write-path validator, so an unknown or empty
452 /// spelling is the same 400 a create/PATCH gets; `taught` needs no parse —
453 /// the query extractor itself 400s a `?taught=` that is not `true`/`false`,
454 /// naming the field; `q` passes through raw — each arm trims, folds and
455 /// blanks it identically.
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/// List the catalog courses visible to the caller: every course for manager+,
470/// otherwise the courses they teach somewhere plus the ones they're enrolled
471/// in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a
472/// `{items, total, limit, offset}` envelope.
473///
474/// `kind` narrows to one flavor, `q` filters by a case- and
475/// diacritic-insensitive fragment of the title or description (blank =
476/// unfiltered), and `taught` keeps only the courses a class section teaches
477/// (`true`) or none yet (`false`). All apply to the caller's visible set
478/// only — after the visibility gate and before the window is cut — so
479/// `total` is the filtered length.
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)]
492async 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 // The filters ride inside the visible set — SQL for a manager, the
501 // union's tail in Rust below one — so total is the filtered length
502 // before the window is cut.
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 // Paged in the web layer: the visible set is a Rust union of two lists.
508 let window = paginate(&courses, limit, offset);
509 // Join creators onto the page alone — the lookup shrinks with the window.
510 let people = person_map(window.iter().flat_map(course_people), &st.db).await?;
511 // The sections of every row on the page, batched: one round of queries for
512 // the whole page, never one per row. A non-manager sees only the sections
513 // they already reach (their şubeler, what they teach, their enrollments).
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 // Deliberate exception to the instance-resolved display rule: this
517 // surface IS the ders catalog, so each *row* shows its own catalog
518 // title/description — but every row now carries the class sections
519 // teaching it, each with the section's own resolved title and hours (the
520 // grade templates (`/offerings`) and the per-class instances
521 // (`/instances`) resolve from it; they never edit it).
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/// The catalog courses the current user is reached by, paged via
533/// `?limit=&offset=` (omit `limit` for all of them); returns a
534/// `{items, total, limit, offset}` envelope.
535///
536/// One row per **class section** the caller is reached by — the resolved
537/// title, hours, class and teachers of that section, with the *instance* id.
538/// The set is `GET /instances/me`'s (class roster, homeroom, taught) unioned
539/// with the caller's own enrollment rows, so a section is listed exactly when
540/// they reach it at all: by their şube, by running it, or by being placed on
541/// its roster by hand.
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)]
554async 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 // The section set is a live Rust list (the visibility union), so it is
561 // paged here — the `visible_courses` shape.
562 let sections = reached_sections(&st.db, &user).await?;
563 let total = sections.len() as i64;
564 let window = paginate(&sections, limit, offset);
565 Ok(Json(Page::new(window.to_vec(), total, limit, offset)))
566}
567
568/// Fetch a single catalog course by id. Visible to the people it reaches —
569/// students enrolled in any of its instances, members of the course itself —
570/// and to its creator and managers/admins while those accounts are still
571/// `teacher`+.
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)]
585async 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/// Update a catalog course. Requires teacher+ and catalog rights — its
608/// creator, or a manager/admin. Omitted fields keep their value.
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)]
625async 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 // Only what the request actually carried is validated and written — an
641 // omitted field stays `None` so the save never re-sends this snapshot's
642 // value over a concurrent PATCH of that field.
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/// Delete a catalog course. Requires teacher+; only its creator or a
657/// manager/admin may delete it. Refused with a 409 while the course is still
658/// taught anywhere — detach it from every class section (`DELETE
659/// /classes/{id}/instances/{instance}`) and remove its individual members
660/// first, so a course that carries teaching is never dropped by accident.
661/// Once free, it cascades the instances' exams (with their results, questions,
662/// answers, and question images), homework (with submissions, submission
663/// files, and grades), sessions and roll call, its individual memberships, its
664/// subjects, and the teacher links. It also strikes its id out of every class
665/// blueprint that named it — a template holding a course nothing can resolve
666/// is a stocking run that skips it and a `PATCH` that refuses the very list
667/// the template already holds.
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)]
682async 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 // The workflow — blob-key collection and the guarded cascade — is
696 // [`service::course::delete`]'s.
697 // Blob unlinking stays here because only the web layer knows `files_path`.
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// ---- club/study membership -------------------------------------------------
718
719/// Add a user to a club or study — the **school-scoped** membership tier.
720/// Requires teacher+ and catalog rights (its creator, or a manager/admin).
721/// Only students can be added, and only to a `study` (supervised study) or
722/// `club`: a regular course (`kind` `course`) has no school-wide roster — its
723/// students come from the class sections that teach it, and that join is
724/// `POST /instances/{id}/enrollments` (400 here). Idempotent: a pair that
725/// already holds a membership is returned as-is.
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)]
742async 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/// List a club/study's members, newest first, paged via `?limit=&offset=`
764/// (omit `limit` for the whole list). Requires teacher+ and catalog rights.
765/// Returns a `{items, total, limit, offset}` envelope. An instance's roster
766/// is `GET /instances/{id}/enrollments`.
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)]
781async 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 // Join people onto the page alone — the lookup shrinks with the window.
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/// Remove a user from a club or study. Requires teacher+ and catalog rights.
814/// Existing exam results and badges are untouched — the membership is a door,
815/// not a record of what happened inside. A pair holding no membership is a
816/// 404.
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)]
833async 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// ---- subjects in a course ---------------------------------------------------
852// The course's curriculum topics. Every exam question links to one, so the
853// list doubles as the tag picker when authoring questions.
854
855#[derive(Deserialize, ToSchema)]
856struct 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/// Create a subject inside a course. Requires teacher+ and catalog rights
864/// (its creator, or a manager/admin). Subjects are the curriculum topics of the
865/// *catalog* row — every exam of every instance teaching it tags its questions
866/// with one of them.
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)]
883async 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/// List a course's subjects in creation order, paged via `?limit=&offset=`
905/// (omit `limit` for all of them). Visible to its creator, to managers/admins,
906/// and to anyone the course reaches (a student enrolled in one of its
907/// instances, or a member of it). Returns a `{items, total, limit, offset}`
908/// envelope.
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)]
923async 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 // Course must exist — a missing course is a 404, not an empty list.
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)]
946mod tests {
947 use super::*;
948 use crate::database::init_test_db;
949 use crate::domain::user::Username;
950
951 /// A user at `role`, minted through the real create path.
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 /// A catalog course `creator` made.
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 /// A catalog course with caller-chosen fields, minted through the real
976 /// create path.
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 /// An unknown or empty `kind` is the write path's own 400, naming the
1007 /// field; `q` passes through verbatim (each arm folds it).
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 /// Manager arm: kind and q narrow the catalog, total is the filtered
1040 /// length, a miss is an empty list, and `%`/`_` are literal.
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 // "Matematik" is taught by a real class section; the other two are
1049 // attached nowhere, so the taught axis has both values in play.
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 // No filters: the whole catalog, newest first — today's response,
1071 // taught and untaught alike.
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 // kind: exact flavor only.
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 // q: title fragment, case- and diacritic-insensitive.
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 // q: description fragment too.
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 // q: `position`, not `LIKE` — no wildcard surprises.
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 // Combined filters AND; a miss is 200 empty, not an error.
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 // Blank q is no filter — the unfiltered catalog again.
1116 let blank = visible_courses_filtered(&boss, &db, None, Some(" "), None)
1117 .await
1118 .unwrap();
1119 assert_eq!(titles(&blank), titles(&all));
1120
1121 // taught: true keeps the attached one, false the unattached two, and
1122 // it composes with kind.
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 // The window is cut after the filter: one course per page while the
1141 // total stays the filtered length (the handler's `total` is
1142 // `courses.len()` taken *before* `paginate`).
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 /// Below manager the filters ride the Rust union: they can narrow what a
1151 /// student reaches but never widen it.
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 // Unfiltered: only the enrolled ders — the club is real but not theirs.
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 // kind=club: the club exists in the catalog, the student still sees none.
1170 let clubs = visible_courses_filtered(&student, &db, Some(a_kind("club")), None, None)
1171 .await
1172 .unwrap();
1173 assert!(clubs.is_empty());
1174 // q over the club's own title finds nothing they cannot reach either.
1175 let q = visible_courses_filtered(&student, &db, None, Some("satranç"), None)
1176 .await
1177 .unwrap();
1178 assert!(q.is_empty());
1179
1180 // taught: their ders is taught (the attached instance), the club is
1181 // not — the axis narrows both ways without widening anything.
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 // Their own ders survives both filters.
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 /// `?taught=` present but empty is refused by the query extractor itself —
1203 /// a 400 naming the field; only `true`/`false` parse.
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 /// The leak: `creator` is a historical column that demotion never sweeps,
1224 /// so the grant itself has to re-read the live role on every call.
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 /// No course is left orphaned by the floor: manager+ reaches a course whose
1250 /// creator was demoted.
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 /// The assignment list is off the catalog (D6): a teacher assigned to an
1268 /// instance runs that instance, but holds no rights over the catalog row
1269 /// itself — the gate that grants them the instance is
1270 /// [`super::instances::can_manage_instance`].
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}