diff --git a/README.md b/README.md index d3e5c89..ff4f062 100644 --- a/README.md +++ b/README.md @@ -694,6 +694,17 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | +| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label | +| GET | `/classes` | teacher | List classes, newest first · paged | +| GET | `/classes/{id}` | teacher | Get one class | +| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`) | +| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses | +| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, or if already a member) | +| GET | `/classes/{id}/members` | teacher | List the class roster · paged | +| DELETE | `/classes/{id}/members/{user}` | manager | Remove a student and sweep the enrollments the class pumped for them | +| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, or if already attached) | +| GET | `/classes/{id}/courses` | teacher | List the class's attached courses · paged | +| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) and sweep the enrollments the class pumped | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) · paged | | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` — add a curriculum subject (course manager) | @@ -2877,7 +2888,7 @@ src/ courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs - boards.rs + boards.rs classes.rs limits.rs GET /limits: every constant.rs bound served as JSON ``` diff --git a/src/lib.rs b/src/lib.rs index ca30871..6607f0c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,7 @@ use crate::state::AppState; (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), + (name = "classes", description = "Classes (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments. A course with too few seats takes none of the class (409, naming the course), a student already enrolled by hand keeps their own row (never adopted, never swept), and a class still holding students or courses refuses deletion (409). The class itself and its roster are manager+; attaching or detaching a course takes management rights on *that course*, since it writes that course's roster"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), @@ -103,6 +104,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/events", web::events::routes()) .nest("/appointments", web::appointments::routes()) .nest("/courses", web::courses::routes()) + .nest("/classes", web::classes::routes()) .nest("/sessions", web::sessions::routes()) .nest("/exams", web::exams::routes()) .nest("/marks", web::marks::routes()) diff --git a/src/web/classes.rs b/src/web/classes.rs new file mode 100644 index 0000000..8a1c484 --- /dev/null +++ b/src/web/classes.rs @@ -0,0 +1,612 @@ +//! Classes (şube): a named set of students the school moves as one. +//! +//! Nothing here is a second kind of membership — adding a student to a class +//! enrolls them into every course the class carries, and attaching a course +//! enrolls the whole roster into it, as real `enrollment` rows. So the two +//! write axes are gated exactly like the writes they stand in for: the class +//! and its roster are the office's (manager+), while attaching a course writes +//! *that course's* roster and takes the same right enrolling into it does. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::class_course::ClassCourse; +use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::class_member::ClassMember; +use crate::domain::course::{Course, CourseId}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::courses::can_manage_course; +use super::terms::resolve_term; +use super::{ + Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, set_or_clear, +}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_class, list_classes)) + .routes(routes!(get_class, update_class, delete_class)) + .routes(routes!(add_member, list_members)) + .routes(routes!(remove_member)) + .routes(routes!(attach_course, list_class_courses)) + .routes(routes!(detach_course)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateClass { + #[schema(max_length = 200, example = "9-A")] + name: String, + /// The school's own label for the year this class sits in ("9", "10-A", + /// "anaokulu"). Free text; omit (or send `""`) for a class with no grade. + #[schema(max_length = 20, example = "9")] + grade: Option, + /// The academic term this class belongs to (`GET /terms`). Optional. + term_id: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateClass { + #[schema(max_length = 200)] + name: Option, + /// Omit to keep the current grade, send `null` (or `""`) to clear it, or + /// send a label to (re)set it. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, max_length = 20)] + grade: Option>, + /// Omit to keep the current term, send `null` to unlink, or send a term id + /// to (re)assign. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + term_id: Option>, +} + +#[derive(Deserialize, ToSchema)] +struct AddMember { + /// The student to put in the class. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + user_id: String, +} + +#[derive(Deserialize, ToSchema)] +struct AttachCourse { + /// The course the whole class takes. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + course_id: String, +} + +#[derive(Serialize, ToSchema)] +struct ClassResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + id: String, + /// Who created the class. + creator: PersonRef, + #[schema(example = "9-A")] + name: String, + /// The school's own free-text grade label; `null` when the class has none. + #[schema(example = "9")] + grade: Option, + /// The academic term this class belongs to (`GET /terms`); `null` when + /// unassigned. + term: Option, +} + +impl ClassResponse { + fn new(class: &ClassGroup, people: &std::collections::HashMap) -> Self { + Self { + id: class.get_id().key().to_string(), + creator: PersonRef::resolve(people, class.get_creator()), + name: class.get_name().as_str().to_string(), + grade: class.get_grade().map(|g| g.as_str().to_string()), + term: class.get_term().map(|term| term.key().to_string()), + } + } +} + +#[derive(Serialize, ToSchema)] +struct ClassMemberResponse { + id: String, + class: String, + /// The student in the class. + user: PersonRef, + /// Who put them there. + added_by: PersonRef, +} + +impl ClassMemberResponse { + fn new(member: &ClassMember, people: &std::collections::HashMap) -> Self { + Self { + id: member.get_id().key().to_string(), + class: member.get_class().key().to_string(), + user: PersonRef::resolve(people, member.get_user()), + added_by: PersonRef::resolve(people, member.get_added_by()), + } + } +} + +#[derive(Serialize, ToSchema)] +struct ClassCourseResponse { + id: String, + class: String, + /// The course the class takes. + course: String, + /// Who attached it. + attached_by: PersonRef, +} + +impl ClassCourseResponse { + fn new(link: &ClassCourse, people: &std::collections::HashMap) -> Self { + Self { + id: link.get_id().key().to_string(), + class: link.get_class().key().to_string(), + course: link.get_course().key().to_string(), + attached_by: PersonRef::resolve(people, link.get_attached_by()), + } + } +} + +/// The class a path id names, or a 404 — every route under `/classes/{id}` +/// gates on it, so a missing class never reads as an empty roster. +async fn class_or_404(id: &str, db: &Database) -> Result { + ClassGroup::read(&ClassGroupId::from_key(id), db) + .await? + .ok_or(AppError::NotFound) +} + +/// An empty grade is *no* grade: the column is nullable, so a client that omits +/// it and one that sends `""` must land on the same stored row. +fn grade_or_none(text: Option<&str>) -> Result, AppError> { + match text { + None | Some("") => Ok(None), + Some(text) => Ok(Some(ClassGrade::try_new(text)?)), + } +} + +/// Create a class. Requires manager+ — a class is school structure, not a +/// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), +/// `term_id` links the school calendar; both optional. +#[utoipa::path( + post, + path = "/", + tag = "classes", + security(("session_cookie" = [])), + request_body = CreateClass, + responses( + (status = 201, description = "Class created", body = ClassResponse), + (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + ), +)] +async fn create_class( + State(st): State, + RequireManager(user): RequireManager, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let name = ClassName::try_new(&req.name)?; + let grade = grade_or_none(req.grade.as_deref())?; + // Pre-flight only: `ClassGroup::create` claims a reference on the term + // before it writes the link, and a term deleted in between fails that claim + // with this very error — so an unknown id reads the same whichever side wins. + let term = resolve_term(req.term_id.as_deref(), &st.db).await?; + let class = ClassGroup::create(user.get_id(), name, grade, term, &st.db).await?; + // The creator is the caller — already loaded, no extra lookup. + let people = PersonRef::map_of(&[&user]); + Ok(( + StatusCode::CREATED, + Json(ClassResponse::new(&class, &people)), + )) +} + +/// List every class, newest first. Requires teacher+. Paged via `?limit=&offset=` +/// (omit `limit` for the full list); returns a `{items, total, limit, offset}` +/// envelope. +#[utoipa::path( + get, + path = "/", + tag = "classes", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of classes (the full list when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn list_classes( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let (classes, total) = ClassGroup::list_all(limit, offset, &st.db).await?; + // Join creators onto the page alone — the lookup shrinks with the window. + let people = person_map( + classes.iter().map(|class| class.get_creator().clone()), + &st.db, + ) + .await?; + let items = classes + .iter() + .map(|class| ClassResponse::new(class, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch a single class by id. Requires teacher+. +#[utoipa::path( + get, + path = "/{id}", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id")), + responses( + (status = 200, description = "The class", body = ClassResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_class( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + let class = class_or_404(&id, &st.db).await?; + let people = person_map(std::iter::once(class.get_creator().clone()), &st.db).await?; + Ok(Json(ClassResponse::new(&class, &people))) +} + +/// Update a class. Requires manager+. Omitted fields keep their value; `grade` +/// and `term_id` are nullable, so an explicit `null` clears them. +#[utoipa::path( + patch, + path = "/{id}", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id")), + request_body = UpdateClass, + responses( + (status = 200, description = "Updated class", body = ClassResponse), + (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_class( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let class = class_or_404(&id, &st.db).await?; + + // Only what the request actually carried is validated and written — an + // omitted field stays `None` so the save never re-sends this snapshot's + // value over a concurrent PATCH of that field. + let name = req.name.as_deref().map(ClassName::try_new).transpose()?; + let grade = match req.grade { + Some(ref update) => Some(grade_or_none(update.as_deref())?), + None => None, + }; + let term = match req.term_id { + // Explicit `null` clears the link; a value must name a real term. + Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), + None => None, + }; + + let updated = class.update(name, grade, term, &st.db).await?; + let people = person_map(std::iter::once(updated.get_creator().clone()), &st.db).await?; + Ok(Json(ClassResponse::new(&updated, &people))) +} + +/// Delete a class. Requires manager+. Refused with a 409 while it still holds +/// students or courses — nothing cascades, because dropping the class silently +/// would leave the enrollments it pumped with nothing left to sweep them. +#[utoipa::path( + delete, + path = "/{id}", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "Students or courses are still on this class", body = ErrorResponse), + ), +)] +async fn delete_class( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result { + let class = class_or_404(&id, &st.db).await?; + if !class.delete(&st.db).await? { + return Err(AppError::Conflict( + "this class still holds students or courses — remove its members and detach its courses first", + )); + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- members --------------------------------------------------------------- + +/// Put a student in a class. Requires manager+. They are enrolled into every +/// course the class already carries, in one go: a course with no free seat +/// refuses the whole join with a 409 naming it, and a student already enrolled +/// by hand keeps the row they have (no second seat, and it survives their +/// removal from the class). Adding the same student twice is a 409. +#[utoipa::path( + post, + path = "/{id}/members", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id")), + request_body = AddMember, + responses( + (status = 201, description = "Student added to the class", body = ClassMemberResponse), + (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Class not found", body = ErrorResponse), + (status = 409, description = "Already in this class, or one of its courses is full", body = ErrorResponse), + ), +)] +async fn add_member( + State(st): State, + RequireManager(user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let class = class_or_404(&id, &st.db).await?; + + let target = UserId::from_key(&req.user_id); + let Some(target_user) = User::read(&target, &st.db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + // A class membership is enrollment in bulk, and enrollment is student + // membership — the same bar `POST /courses/{id}/enrollments` holds. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be added to a class", + })); + } + + let member = ClassMember::add(class.get_id(), &target, user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&target_user, &user]); + Ok(( + StatusCode::CREATED, + Json(ClassMemberResponse::new(&member, &people)), + )) +} + +/// List a class's roster, newest first, paged via `?limit=&offset=` (omit +/// `limit` for the whole roster). Requires teacher+. Returns a +/// `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/{id}/members", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id"), PageParams), + responses( + (status = 200, description = "A page of class members (the whole roster when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Class not found", body = ErrorResponse), + ), +)] +async fn list_members( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let class = class_or_404(&id, &st.db).await?; + let (rows, total) = ClassMember::list_for_class(class.get_id(), limit, offset, &st.db).await?; + // Join people onto the page alone — the lookup shrinks with the window. + let people = person_map( + rows.iter() + .flat_map(|row| [row.get_user().clone(), row.get_added_by().clone()]), + &st.db, + ) + .await?; + let items = rows + .iter() + .map(|row| ClassMemberResponse::new(row, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Take a student out of a class. Requires manager+. The enrollments the class +/// pumped for them are swept with it — except rows another attached class still +/// claims (re-tagged to it) and rows placed by hand (left standing). A student +/// who was not in the class is a 404. +#[utoipa::path( + delete, + path = "/{id}/members/{user}", + tag = "classes", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Class id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse), + ), +)] +async fn remove_member( + State(st): State, + RequireManager(_user): RequireManager, + Path((id, target)): Path<(String, String)>, +) -> Result { + let class = class_or_404(&id, &st.db).await?; + ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- attached courses ------------------------------------------------------ + +/// Attach a course to a class. Requires teacher+ and management rights **on +/// that course** — attaching writes its roster, so it takes exactly the right +/// enrolling into it does. The class's whole roster is enrolled in one go: a +/// course that cannot hold all of them takes none (409), and students already +/// enrolled by hand keep their own rows. Attaching the same course twice is a +/// 409. +#[utoipa::path( + post, + path = "/{id}/courses", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id")), + request_body = AttachCourse, + responses( + (status = 201, description = "Course attached to the class", body = ClassCourseResponse), + (status = 400, description = "Unknown course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Class not found", body = ErrorResponse), + (status = 409, description = "Already attached, or the course cannot hold the whole class", body = ErrorResponse), + ), +)] +async fn attach_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let class = class_or_404(&id, &st.db).await?; + let Some(course) = Course::read(&CourseId::from_key(&req.course_id), &st.db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "course_id", + reason: "course does not exist", + })); + }; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can attach this course to a class", + )); + } + + let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + Ok(( + StatusCode::CREATED, + Json(ClassCourseResponse::new(&link, &people)), + )) +} + +/// List the courses a class is attached to, newest first, paged via +/// `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns +/// a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/{id}/courses", + tag = "classes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Class id"), PageParams), + responses( + (status = 200, description = "A page of the class's courses (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Class not found", body = ErrorResponse), + ), +)] +async fn list_class_courses( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let class = class_or_404(&id, &st.db).await?; + let (rows, total) = ClassCourse::list_for_class(class.get_id(), limit, offset, &st.db).await?; + let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?; + let items = rows + .iter() + .map(|row| ClassCourseResponse::new(row, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Detach a course from a class. Requires teacher+ and management rights on +/// that course, like attaching. The enrollments the class pumped into it are +/// swept — except rows another attached class still claims (re-tagged to it) +/// and rows placed by hand (left standing). A course that was not attached is a +/// 404. +#[utoipa::path( + delete, + path = "/{id}/courses/{course}", + tag = "classes", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Class id"), + ("course" = String, Path, description = "Course id"), + ), + responses( + (status = 204, description = "Detached"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Class or course not found, or that course was not attached", body = ErrorResponse), + ), +)] +async fn detach_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, course)): Path<(String, String)>, +) -> Result { + let class = class_or_404(&id, &st.db).await?; + let course = Course::read(&CourseId::from_key(&course), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class", + )); + } + ClassCourse::detach(class.get_id(), course.get_id(), &st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The nullable-grade rule both write paths share: absent and `""` are the + /// same *no grade*, so a PATCH clearing with `""` cannot store a blank + /// label a create could never make. + #[test] + fn an_empty_grade_is_no_grade() { + assert!(grade_or_none(None).unwrap().is_none()); + assert!(grade_or_none(Some("")).unwrap().is_none()); + assert_eq!( + grade_or_none(Some("9")) + .unwrap() + .map(|g| g.as_str().to_string()), + Some("9".to_string()) + ); + assert!(grade_or_none(Some(&"x".repeat(1000))).is_err()); + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs index badf464..e4f4a66 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -11,6 +11,7 @@ pub mod bank_questions; pub mod board_ws; pub mod boards; pub mod chatbot; +pub mod classes; pub mod courses; pub mod etag; pub mod events; diff --git a/tests/integration.rs b/tests/integration.rs index 161ad36..da44ae8 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -24955,3 +24955,201 @@ async fn a_burst_of_strokes_comes_back_in_mint_order() { assert_eq!(payloads[0], "{\"p\":[0]}"); assert_eq!(payloads[59], "{\"p\":[59]}"); } + +// --- classes (şube) --------------------------------------------------------- + +/// The class routes' own gates, end to end: who may write, who may not, and +/// that the writes really are enrollments. The pump itself is proven in the +/// domain unit tests — what only the router can prove is that the two axes are +/// gated differently (roster = manager+, attach = *that course's* manager) and +/// that a class is enrollment in bulk rather than a parallel roster. +#[tokio::test] +async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mgr", "manager").await; + let teacher = login_as(&app, &db, "tch", "teacher").await; + let other = login_as(&app, &db, "other", "teacher").await; + let student = login_as(&app, &db, "stu", "student").await; + let student_id = me_id(&app, &student).await; + let teacher_id = me_id(&app, &teacher).await; + let course = create_course(&app, &teacher, "algebra").await; + + // Creating a class is the office's call — a teacher may read, not write. + let res = send( + &app, + "POST", + "/classes", + Some(&teacher), + Some(json!({"name": "9-A"})), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "class create is manager+" + ); + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({"name": "9-A", "grade": ""})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert!(res.body["grade"].is_null(), "an empty grade is no grade"); + let class = id_of(&res.body); + assert_eq!( + send(&app, "GET", "/classes", Some(&teacher), None) + .await + .status, + StatusCode::OK, + "teachers read the class list" + ); + + // Only students go in a roster, and only real users. + for (body, who) in [ + (json!({"user_id": "nobody"}), "an unknown user"), + (json!({"user_id": teacher_id}), "a teacher"), + ] { + let res = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(body), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{who} is a 400"); + } + let res = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + + // Attaching writes the course's roster, so it takes the course's own bar — + // a teacher who does not manage it is refused even though they are teacher+. + let attach = json!({ "course_id": course }); + let res = send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&other), + Some(attach.clone()), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "attach needs course rights" + ); + let res = send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&teacher), + Some(attach.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let res = send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&teacher), + Some(attach), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "a second attach is a 409"); + + // The membership is a real enrollment: it shows up on the course roster. + let res = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + common::total(&res.body), + 1, + "the class must have enrolled its member" + ); + assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id); + + // A class carrying either is undeletable until both ends are cleared. + let res = send( + &app, + "DELETE", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + assert_eq!( + send( + &app, + "DELETE", + &format!("/classes/{class}/courses/{course}"), + Some(&manager), + None, + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/classes/{class}/members/{student_id}"), + Some(&manager), + None, + ) + .await + .status, + StatusCode::NO_CONTENT + ); + let res = send( + &app, + "DELETE", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::NO_CONTENT, + "empty on both axes, it goes" + ); + // And the pumped enrollment left with the detach. + let res = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!(common::total(&res.body), 0); + assert_eq!( + send( + &app, + "GET", + &format!("/classes/{class}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index b8ed39d..9fde8b5 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -207,6 +207,30 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_COURSE_DESCRIPTION_LEN as i64, ), + ( + "CreateClass", + "name", + "maxLength", + MAX_CLASS_NAME_LEN as i64, + ), + ( + "CreateClass", + "grade", + "maxLength", + MAX_CLASS_GRADE_LEN as i64, + ), + ( + "UpdateClass", + "name", + "maxLength", + MAX_CLASS_NAME_LEN as i64, + ), + ( + "UpdateClass", + "grade", + "maxLength", + MAX_CLASS_GRADE_LEN as i64, + ), ( "CreateExamInCourse", "title",