diff --git a/.sqlx/query-2577d62a94114c67d37fed2a9dd48c4396bbe0cc51a34b91a5d9ab9e066df099.json b/.sqlx/query-2577d62a94114c67d37fed2a9dd48c4396bbe0cc51a34b91a5d9ab9e066df099.json new file mode 100644 index 0000000..aabd3a2 --- /dev/null +++ b/.sqlx/query-2577d62a94114c67d37fed2a9dd48c4396bbe0cc51a34b91a5d9ab9e066df099.json @@ -0,0 +1,76 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT class_course AS \"class_course: ClassCourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"\n FROM enrollment WHERE app_user = $1 ORDER BY class_course", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "class_course: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "class_course" + } + } + }, + { + "ordinal": 1, + "name": "user: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "app_user" + } + } + }, + { + "ordinal": 2, + "name": "enrolled_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "enrolled_by" + } + } + }, + { + "ordinal": 3, + "name": "source: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "source" + } + } + }, + { + "ordinal": 4, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "enrollment", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + false + ] + }, + "hash": "2577d62a94114c67d37fed2a9dd48c4396bbe0cc51a34b91a5d9ab9e066df099" +} diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index eac613a..0daa8d8 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -224,6 +224,29 @@ pub async fn read_for_user( Ok(row) } +/// Every instance `user` holds an enrollment row on, in one statement for the +/// whole set — the read behind the surfaces that must list a section a **hand** +/// enrollment reaches. A hand-placed row (and a class row an operator later +/// disowned, `source` NULL) is on no class roster, so +/// [`crate::service::instance::visible_instances`] — keyed on the class — never +/// sees it; `/courses/me` and the profile course block listed it before the +/// section split, so they union this in. Ordered by instance id for a stable +/// answer; a user with no enrollment reads an empty list, and the caller +/// resolves the ids through [`crate::db::class_course`] (one batch read). +pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { + let rows = sqlx::query_as!( + Enrollment, + r#"SELECT class_course AS "class_course: ClassCourseId", app_user AS "user: UserId", + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId", + created_at AS "created_at: Timestamp" + FROM enrollment WHERE app_user = $1 ORDER BY class_course"#, + user.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows) +} + /// The roster an exam is sat by: every enrollment of every instance the exam /// is addressed to (`exam_audience`, D2), deduped by student — the live /// monitor's roster read, and the one that makes an announced-to section's diff --git a/src/service/course_session.rs b/src/service/course_session.rs index 6e0d51a..b2e035c 100644 --- a/src/service/course_session.rs +++ b/src/service/course_session.rs @@ -178,16 +178,18 @@ pub async fn materialize( // the generated rows are written on that same connection: a rival // materialize run waits here instead of racing the existence read, and a // refusal rolls back whatever it had collected. + let pool = db.clone(); + let instance = instance.clone(); tx_with_retry(db, false, async move |tx| { // The archived-year wall every instance write passes: a past year is // read-only, and this run mints lesson rows. - crate::service::class_course::require_open(db, &instance_id).await?; + crate::service::class_course::require_open(&pool, &instance_id).await?; // The serialization point. `FOR NO KEY UPDATE` rather than // `FOR UPDATE`: the batch insert below takes this same row's // foreign-key `FOR KEY SHARE`, which `FOR UPDATE` would block on. crate::db::weekly_slot::lock_class_tx(tx, &instance_id).await?; - let slots = crate::service::weekly_slot::resolved_for_instance(db, instance).await?; + let slots = crate::service::weekly_slot::resolved_for_instance(&pool, &instance).await?; if slots.is_empty() { return Err(AppError::ConflictCoded { code: "instance_has_no_weekly_plan", @@ -195,7 +197,7 @@ pub async fn materialize( }); } let teachers = - crate::db::class_course_teacher::list_for_instance(db, &instance_id).await?; + crate::db::class_course_teacher::list_for_instance(&pool, &instance_id).await?; let Some(teacher) = teachers.first().copied() else { return Err(AppError::ConflictCoded { code: "instance_has_no_teacher", @@ -207,7 +209,8 @@ pub async fn materialize( // title second (the one display chain every surface rides), the // literal `"Ders"` last. The resolved title is bounded by // `MAX_COURSE_TITLE_LEN`, so it always fits a `SessionTopic`. - let resolved = crate::service::instance_resolve::resolved_content(db, &[instance]).await?; + let resolved = + crate::service::instance_resolve::resolved_content(&pool, &[&instance]).await?; let fallback_topic = resolved .get(&instance_id.key()) .map(|content| content.title.as_str()) @@ -215,8 +218,8 @@ pub async fn materialize( .and_then(|title| SessionTopic::try_new(title).ok()) .unwrap_or(SessionTopic::try_new("Ders")?); - let holidays = crate::service::holiday::blocked_days(db, from, to).await?; - let existing = course_session::existing_starts(db, &instance_id).await?; + let holidays = crate::service::holiday::blocked_days(&pool, from, to).await?; + let existing = course_session::existing_starts(&pool, &instance_id).await?; let mut rows: Vec = Vec::new(); let mut blocked: Vec = Vec::new(); diff --git a/src/web/courses.rs b/src/web/courses.rs index 8975ffe..23d1fc1 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -7,8 +7,14 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use std::collections::{HashMap, HashSet}; + +use crate::constant::MAX_COURSE_SECTIONS; use crate::database::Database; +use crate::domain::class_course::{ClassCourse, DersSaati}; +use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; +use crate::domain::course_offering::CourseOfferingId; use crate::domain::role::Role; use crate::domain::subject::{SubjectDescription, SubjectName}; use crate::domain::user::{User, UserId}; @@ -17,6 +23,7 @@ use crate::service; use crate::service::course::{can_manage_course, can_view_course}; use crate::state::AppState; +use super::dto::CourseSectionRef; use super::{ CourseResponse, CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SubjectResponse, course_people, paginate, person_map, remove_blob, @@ -150,6 +157,198 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, +) -> Result>, AppError> { + let mut by_course: HashMap> = HashMap::new(); + if courses.is_empty() { + return Ok(by_course); + } + let ids: Vec = courses.iter().map(|course| course.get_id().clone()).collect(); + let mut instances = crate::db::class_course::list_for_course_ids(db, &ids).await?; + if let Some(viewer) = viewer { + let reachable: HashSet = reached_instances(db, viewer) + .await? + .into_iter() + .map(|instance| instance.get_id().key()) + .collect(); + instances.retain(|instance| reachable.contains(&instance.get_id().key())); + } + let with_teachers = crate::db::class_course_teacher::into_instances(db, instances).await?; + for section in section_refs(db, with_teachers).await? { + by_course + .entry(section.course.clone()) + .or_default() + .push(section); + } + for sections in by_course.values_mut() { + sections.truncate(MAX_COURSE_SECTIONS); + } + Ok(by_course) +} + +/// The class sections the caller is reached by, one flat list — the shape +/// `/courses/me` serves (it lists sections, not catalog rows, so there is no +/// grouping to do). Rides [`reached_instances`] (class roster, homeroom, +/// taught, or their own enrollment) and [`section_refs`] like [`sections_of`] +/// does, so the surfaces cannot disagree about a section's resolved title or +/// hours. +pub(crate) async fn reached_sections( + db: &Database, + user: &User, +) -> Result, AppError> { + let instances = reached_instances(db, user).await?; + let with_teachers = crate::db::class_course_teacher::into_instances(db, instances).await?; + section_refs(db, with_teachers).await +} + +/// The instances `user` reaches, as rows: the class-roster / homeroom / taught +/// set ([`crate::service::instance::visible_instances`]) unioned with the +/// instances their own **enrollment** rows place them on, de-duplicated by +/// instance id and kept newest-first. +/// +/// The second half is not redundant. An enrollment row is the *instance* +/// roster, and a hand-placed one carries no class membership at all (a class +/// row an operator later disowned is the same shape), so the class-keyed +/// visibility set never sees it — yet that section is theirs, and both +/// `/courses/me` and the profile course block listed it before the section +/// split. Two reads for the union (the enrollment list plus one batched +/// instance read of whatever it added), never one per row. +pub(crate) async fn reached_instances( + db: &Database, + user: &User, +) -> Result, AppError> { + let mut instances: Vec = crate::service::instance::visible_instances(user, db) + .await? + .into_iter() + .map(|(instance, _)| instance) + .collect(); + let known: HashSet = instances + .iter() + .map(|instance| instance.get_id().key()) + .collect(); + let missing: Vec = + crate::db::enrollment::list_for_user(db, user.get_id()) + .await? + .iter() + .map(|enrollment| enrollment.get_class_course().clone()) + .filter(|id| !known.contains(&id.key())) + .collect(); + // `list_by_ids` orders `attached_at DESC, id DESC` — the same order the + // class arm of `visible_instances` produces, so the union reads newest-first + // end to end. + instances.extend(crate::db::class_course::list_by_ids(db, &missing).await?); + Ok(instances) +} + +/// Build one [`CourseSectionRef`] per `(instance, teachers)` pair — the shared +/// tail of [`sections_of`] and [`reached_sections`]: the classes, offerings, +/// resolved titles and people are read once for the whole batch, then each +/// section is assembled in memory. +pub(crate) async fn section_refs( + db: &Database, + rows: Vec<(ClassCourse, Vec)>, +) -> Result, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let mut class_ids: Vec = Vec::new(); + let mut offering_ids: Vec = Vec::new(); + for (instance, _) in &rows { + if !class_ids.contains(instance.get_class()) { + class_ids.push(instance.get_class().clone()); + } + if !offering_ids.contains(instance.get_offering()) { + offering_ids.push(instance.get_offering().clone()); + } + } + let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?; + let class_by_key: HashMap = classes + .iter() + .map(|class| (class.get_id().key(), class)) + .collect(); + // The resolved weekly hours chain is `resolve_policy`'s — instance + // override, else the offering's default, else the floor — but its offering + // half is read once for the batch instead of once per section. + let offerings = crate::db::course_offering::list_by_ids(db, &offering_ids).await?; + let hours_by_offering: HashMap> = offerings + .iter() + .map(|offering| { + ( + offering.get_id().key(), + offering.get_default_ders_saati(), + ) + }) + .collect(); + let refs: Vec<&ClassCourse> = + rows.iter().map(|(instance, _)| instance).collect(); + let content = crate::service::instance_resolve::resolved_content(db, &refs).await?; + let people = person_map( + rows.iter() + .flat_map(|(_, teachers)| teachers.iter().cloned()), + db, + ) + .await?; + let mut sections = Vec::with_capacity(rows.len()); + for (instance, teachers) in &rows { + let key = instance.get_id().key(); + let resolved = content + .get(&key) + .expect("resolved_content covers every instance it is given"); + let class = class_by_key + .get(&instance.get_class().key()) + .expect("every section's class is in the batch read"); + let ders_saati = instance + .get_ders_saati() + .or_else(|| { + hours_by_offering + .get(&instance.get_offering().key()) + .copied() + .flatten() + }) + .unwrap_or_else(|| { + DersSaati::try_new(crate::constant::MIN_DERS_SAATI) + .expect("the floor is a valid weekly-hours count") + }); + sections.push(CourseSectionRef { + id: key, + course: instance.get_course().key(), + class: instance.get_class().key(), + class_name: class.get_name().as_str().to_string(), + title: resolved.title.clone(), + grade_level: class.get_grade_level().get(), + ders_saati: ders_saati.as_i64(), + teachers: teachers + .iter() + .map(|teacher| PersonRef::resolve(&people, teacher)) + .collect(), + enrollment_count: instance.get_enrollment_count(), + }); + } + Ok(sections) +} + // ---- courses ------------------------------------------------------------ /// Create a catalog course owned by the current user. Requires the `teacher` @@ -220,14 +419,23 @@ async fn list_courses( let window = paginate(&courses, limit, offset); // Join creators onto the page alone — the lookup shrinks with the window. let people = person_map(window.iter().flat_map(course_people), &st.db).await?; + // The sections of every row on the page, batched: one round of queries for + // the whole page, never one per row. A non-manager sees only the sections + // they already reach (their şubeler, what they teach, their enrollments). + let viewer = (!user.get_role().at_least(Role::Manager)).then_some(&user); + let mut sections = sections_of(&st.db, window, viewer).await?; // Deliberate exception to the instance-resolved display rule: this - // surface IS the ders catalog, so it shows each row's own catalog - // title/description. The grade templates (`/offerings`) and the - // per-class instances (`/instances`) resolve from it — they never edit - // it. + // surface IS the ders catalog, so each *row* shows its own catalog + // title/description — but every row now carries the class sections + // teaching it, each with the section's own resolved title and hours (the + // grade templates (`/offerings`) and the per-class instances + // (`/instances`) resolve from it; they never edit it). let items = window .iter() - .map(|course| CourseResponse::new(course, &people)) + .map(|course| { + let own = sections.remove(&course.get_id().key()).unwrap_or_default(); + CourseResponse::with_sections(course, &people, own) + }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -236,9 +444,12 @@ async fn list_courses( /// `?limit=&offset=` (omit `limit` for all of them); returns a /// `{items, total, limit, offset}` envelope. /// -/// Both membership tiers are here: a student's enrollments in the instances -/// their class sections teach, and an individual club/study membership. The -/// *instances* themselves are `GET /instances/me`. +/// One row per **class section** the caller is reached by — the resolved +/// title, hours, class and teachers of that section, with the *instance* id. +/// The set is `GET /instances/me`'s (class roster, homeroom, taught) unioned +/// with the caller's own enrollment rows, so a section is listed exactly when +/// they reach it at all: by their şube, by running it, or by being placed on +/// its roster by hand. #[utoipa::path( get, path = "/me", @@ -246,7 +457,7 @@ async fn list_courses( security(("session_cookie" = [])), params(PageParams), responses( - (status = 200, description = "A page of the caller's courses (all of them when unpaged)", body = Page), + (status = 200, description = "A page of the caller's sections (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), @@ -255,38 +466,14 @@ async fn my_courses( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, -) -> Result>, AppError> { +) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - // Two sources, one list: the courses reached through the instances the - // caller is enrolled in, and the ones they joined individually. Either - // read is unpaged — the union is a Rust list, so it is paged here (the - // `visible_courses` shape). - let mut courses = service::course::list_enrolled(&st.db, user.get_id(), None, 0) - .await? - .0; - let (joined, _) = - crate::db::course_membership::list_for_user(&st.db, user.get_id(), None, 0).await?; - let known: Vec = courses - .iter() - .map(|course| course.get_id().clone()) - .collect(); - let mut missing: Vec = joined - .iter() - .map(|membership| membership.get_course().clone()) - .filter(|id| !known.contains(id)) - .collect(); - missing.sort_by_key(|id| std::cmp::Reverse(id.key())); - missing.dedup(); - courses.extend(service::course::list_by_ids(&st.db, &missing).await?); - courses.sort_by_key(|course| std::cmp::Reverse(course.get_id().key())); - let total = courses.len() as i64; - let window = paginate(&courses, limit, offset); - let people = person_map(window.iter().flat_map(course_people), &st.db).await?; - let items = window - .iter() - .map(|course| CourseResponse::new(course, &people)) - .collect(); - Ok(Json(Page::new(items, total, limit, offset))) + // The section set is a live Rust list (the visibility union), so it is + // paged here — the `visible_courses` shape. + let sections = reached_sections(&st.db, &user).await?; + let total = sections.len() as i64; + let window = paginate(§ions, limit, offset); + Ok(Json(Page::new(window.to_vec(), total, limit, offset))) } /// Fetch a single catalog course by id. Visible to the people it reaches — @@ -320,7 +507,12 @@ async fn get_course( )); } let people = person_map(course_people(&course), &st.db).await?; - Ok(Json(CourseResponse::new(&course, &people))) + let viewer = (!user.get_role().at_least(Role::Manager)).then_some(&user); + let mut sections = sections_of(&st.db, std::slice::from_ref(&course), viewer).await?; + let own = sections + .remove(&course.get_id().key()) + .unwrap_or_default(); + Ok(Json(CourseResponse::with_sections(&course, &people, own))) } /// Update a catalog course. Requires teacher+ and catalog rights — its diff --git a/src/web/dto.rs b/src/web/dto.rs index 9aa072c..4606e45 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -276,6 +276,51 @@ pub struct CourseResponse { /// How many individual club/study memberships the course carries. #[schema(example = 12)] pub course_membership_count: i64, + /// The class sections teaching this course right now — one entry per + /// instance, each with its own resolved title and hours. Populated by the + /// catalogue reads (`GET /courses`, `GET /courses/{id}`); `[]` everywhere + /// else, including the CRUD responses and every report that embeds a + /// course row. Truncated to `MAX_COURSE_SECTIONS`; `class_course_count` is + /// the untruncated total. + pub sections: Vec, +} + +/// One class section teaching a catalog course. Shared by the catalogue rows +/// and the profile course block; `id` is the **instance** id +/// (`GET /instances/{id}`), never the catalog row's — the 9-A and 12-A +/// sections of one ders are two entries here, with their own resolved titles +/// and weekly hours. +#[derive(Serialize, Clone, ToSchema)] +pub struct CourseSectionRef { + /// The instance id (`GET /instances/{id}`). + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + pub id: String, + /// The catalog course this section teaches (`GET /courses/{id}`). + #[schema(example = "019732e3-7b00-7000-8000-00000000beef")] + pub course: String, + /// The class this section belongs to (`GET /classes/{id}`). + #[schema(example = "019732e3-7b00-7000-8000-00000000cafe")] + pub class: String, + /// The class's own name, e.g. `9-A`. + #[schema(example = "9-A")] + pub class_name: String, + /// The **resolved** display title of this section: its own override, else + /// its offering's, else the catalog course's — the same chain every + /// instance-scoped surface shows. + #[schema(example = "Matematik")] + pub title: String, + /// The class's rung on the grade ladder (`0` = anaokulu). + #[schema(example = 9)] + pub grade_level: i16, + /// The **resolved** weekly lesson hours of this section: its own override, + /// else its offering's default, else the floor. + #[schema(example = 5)] + pub ders_saati: i64, + /// The staff assigned to run this section. + pub teachers: Vec, + /// How many students are enrolled in this section right now. + #[schema(example = 28)] + pub enrollment_count: i64, } /// Every person a [`CourseResponse`] names: its creator. Feed this into @@ -295,6 +340,21 @@ impl CourseResponse { kind: course.get_kind().as_str().to_string(), class_course_count: course.get_class_course_count(), course_membership_count: course.get_course_membership_count(), + sections: Vec::new(), + } + } + + /// The same row plus its sections — the catalogue reads' constructor + /// (`GET /courses`, `GET /courses/{id}`), where every row carries the + /// class sections teaching it. + pub fn with_sections( + course: &Course, + people: &HashMap, + sections: Vec, + ) -> Self { + Self { + sections, + ..Self::new(course, people) } } } diff --git a/src/web/users.rs b/src/web/users.rs index 2e06e55..feaa197 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -964,10 +964,12 @@ struct ProfileResponse { /// At most `max_profile_classes` sections — the full list is at /// `GET /classes/me`. classes: Vec, - /// At most `max_profile_courses` courses, and only the ones the *reader* - /// may already read at `GET /courses/{id}` — a stranger sees an empty - /// block, the owner and manager+ see it whole. The full list is at - /// `GET /courses/me`. + /// At most `max_profile_courses` **sections** the person is reached by — + /// `GET /instances/me`'s set unioned with their own enrollment rows — each + /// with its own resolved title, and only the ones the *reader* may already + /// read the catalog course of at `GET /courses/{id}`, so a stranger sees an + /// empty block while the owner and manager+ see it whole. The full list is + /// at `GET /courses/me`. courses: Vec, /// Every badge this account has earned, oldest first. Ids and stamps only — /// the label and the icon are the client's, keyed by id off the `badges` @@ -1013,13 +1015,32 @@ struct ProfileClassRef { grade_level: i16, } -/// A course as a profile shows it — a label, nothing more. +/// A course as a profile shows it — one row per **class section** the person +/// is reached by, never the catalog row: the 9-A and 12-A sections of one ders +/// carry their own resolved titles and hours, and the profile lists both. `id` +/// is the instance id (`GET /instances/{id}`); `kind` is the catalog row's, +/// which is the same for every section of one course. #[derive(Serialize, ToSchema)] struct ProfileCourseRef { + /// The instance id (`GET /instances/{id}`). #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, + /// The catalog course this section teaches (`GET /courses/{id}`). + #[schema(example = "019732e3-7b00-7000-8000-00000000beef")] + course: String, + /// The class this section belongs to (`GET /classes/{id}`). + #[schema(example = "019732e3-7b00-7000-8000-00000000cafe")] + class: String, + /// The class's own name, e.g. `9-A`. + #[schema(example = "9-A")] + class_name: String, + /// The **resolved** display title of this section: its own override, else + /// its offering's, else the catalog course's. #[schema(example = "Matematik")] title: String, + /// The class's rung on the grade ladder (`0` = anaokulu). + #[schema(example = 9)] + grade_level: i16, /// `course`, `study` (supervised study), or `club`. #[schema(example = "course")] kind: String, @@ -1054,7 +1075,7 @@ struct ProfileStatsResponse { pomodoro_sessions: i64, /// Total focused milliseconds across those stints. pomodoro_focus_ms: i64, - /// Every course behind the `courses` block, not just the embedded window. + /// Every section behind the `courses` block, not just the embedded window. courses: i64, /// Every class behind the `classes` block, not just the embedded window. classes: i64, @@ -1100,11 +1121,15 @@ struct ProfileStatsResponse { /// Build one profile as `viewer` may see it. The course block is chosen off the /// owner's **live** role, not off the `creator`/`teachers` columns: those are -/// historical and no demotion sweeps them, so a demoted ex-teacher lists what -/// they are enrolled in, like any other student. +/// historical and no demotion sweeps them, so a demoted ex-teacher lists the +/// sections they are reached by, like any other student. It lists one row per +/// *section* and rides [`crate::web::courses::reached_instances`] — the class +/// roster / homeroom / taught set `GET /instances/me` serves, unioned with the +/// owner's own enrollment rows — so a section that is theirs to sit or run is +/// the only thing that appears. /// -/// A course carries a title, and `GET /courses/{id}` hands that title only to -/// the enrolled, the staff who run it, and manager+ — so the block is +/// A section carries a resolved title, and `GET /courses/{id}` hands that title +/// only to the enrolled, the staff who run it, and manager+ — so the block is /// intersected with [`visible_courses`], the same catalog `GET /courses` /// serves. Reading your own profile, or reading as manager+, needs no /// intersection: both already see the whole list. @@ -1150,25 +1175,33 @@ async fn profile_of( .collect::>(), ), }; + // The class sections the person is reached by — the same set + // `GET /instances/me` serves, each with its own resolved title and hours. + // The block is one row per section, and `stats.courses` counts sections. + let mut sections = super::courses::reached_sections(&st.db, user).await?; + let course_total = sections.len() as i64; // The window is cut after the intersection, so a filtered viewer still gets - // up to `MAX_PROFILE_COURSES` courses they can actually see. - let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { - // The teacher read is unpaged, so the total is what came back. - true => { - let courses = crate::service::course::list_for_teacher(&st.db, id).await?; - let total = courses.len() as i64; - (courses, total) - } - // Unfiltered readers can take the window from the database. - false => { - let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); - crate::service::course::list_enrolled(&st.db, id, window, 0).await? - } - }; + // up to `MAX_PROFILE_COURSES` sections they can actually see. if let Some(readable) = &readable { - courses.retain(|course| readable.contains(course.get_id())); + sections.retain(|section| readable.iter().any(|id| id.key() == section.course)); } - courses.truncate(MAX_PROFILE_COURSES); + sections.truncate(MAX_PROFILE_COURSES); + // The catalog row's `kind` — one read for the window, not one per row. + let course_ids: Vec = sections + .iter() + .map(|section| crate::domain::course::CourseId::from_key(§ion.course)) + .collect(); + let kinds: std::collections::HashMap = + crate::service::course::list_by_ids(&st.db, &course_ids) + .await? + .iter() + .map(|course| { + ( + course.get_id().key(), + course.get_kind().as_str().to_string(), + ) + }) + .collect(); let (mut members, class_total) = crate::service::class_member::list_for_user( &st.db, id, @@ -1211,16 +1244,16 @@ async fn profile_of( grade_level: class.get_grade_level().get(), }) .collect(), - courses: courses + courses: sections .iter() - .map(|course| ProfileCourseRef { - id: course.get_id().key().to_string(), - // Catalog-tier surface, like `GET /courses`: a profile lists - // the person's courses by their catalog identity (a person - // may sit two sections of one ders), so the catalog title is - // the deliberate exception to the instance-resolved display. - title: course.get_title().as_str().to_string(), - kind: course.get_kind().as_str().to_string(), + .map(|section| ProfileCourseRef { + id: section.id.clone(), + course: section.course.clone(), + class: section.class.clone(), + class_name: section.class_name.clone(), + title: section.title.clone(), + grade_level: section.grade_level, + kind: kinds.get(§ion.course).cloned().unwrap_or_default(), }) .collect(), badges: badges