From 7864d0a4ce178281ce1020b000a5bb0a7992290b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 19 Jul 2026 18:15:46 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(courses):=20club=20kind=20and?= =?UTF-8?q?=20enroll-time=20roster=20capacity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 24 +++++++----- src/constant.rs | 2 +- src/database.rs | 1 + src/domain/course.rs | 49 +++++++++++++++++++++--- src/domain/enrollment.rs | 28 +++++++++++++- src/lib.rs | 4 +- src/validate.rs | 5 ++- src/web/courses.rs | 64 ++++++++++++++++++++++++++----- src/web/dto.rs | 9 ++++- tests/integration.rs | 81 ++++++++++++++++++++++++++++++++++++++++ 10 files changed, 233 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 0971db7..e923b0d 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,10 @@ closes the moment the event starts (or, for an event with only an end time — a pure signup deadline — the moment that end passes). Every event stays visible to everyone — the audience is a roster, not a wall. Marks are course-shaped (Google Classroom style): a teacher creates a course — kind **`course`** (a -regular class) or **`study`** (a supervised study session — *etüt*; same -behavior, different label) — lays out its **subjects** (curriculum topics — +regular class), **`study`** (a supervised study session — *etüt*), or +**`club`** (a student club — *kulüp*; same behavior, different label), +optionally capped by a `capacity` that refuses new enrolls once the roster is +full — lays out its **subjects** (curriculum topics — every exam question must be tagged with one of its course's subjects, so results can later be read per topic), enrolls students, adds exams inside it, and grades — enrolling, sitting exams, roll call, and marks are @@ -257,10 +259,14 @@ surrealkv path (`./data/hezarfen.db`, namespace/database `hezarfen`). `Auth` is the minimum role; `no` means no session required, `student` means any logged-in user. -A course is either a regular class (kind `course`, the default) or an *etüt* -(kind `study` — a supervised study session). The two kinds behave identically -everywhere — enrollment, exams, sessions, marks — the kind is a label the UI -renders differently, settable at creation and editable later. +A course is a regular class (kind `course`, the default), an *etüt* (kind +`study` — a supervised study session), or a *kulüp* (kind `club` — a student +club). The three kinds behave identically everywhere — enrollment, exams, +sessions, marks — the kind is a label the UI renders differently, settable at +creation and editable later. A course may also carry a `capacity`: once the +roster reaches it, new enrolls are refused with `409` (members already on the +roster are unaffected, even if the cap is later lowered below them; `null` +lifts the cap). Course data is walled per course. A course, its exams, its sessions, and its subjects are @@ -324,13 +330,13 @@ their existing shapes: the student exam-room reads | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | | POST | `/events/{id}/register` | teacher | `{user_id?}` — seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started | | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started | -| POST | `/courses` | teacher | `{title, description?, kind?, term_id?}` — `kind` is `course` (default) or `study` (etüt) (creator manages it) | +| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` — `kind` is `course` (default), `study` (etüt), or `club` (kulüp); `capacity` caps the roster (creator manages it) | | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | -| PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | +| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (creator, or manager+ for any) | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) | -| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | +| 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 | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | diff --git a/src/constant.rs b/src/constant.rs index 423ecb7..bf69f24 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -112,7 +112,7 @@ pub const MAX_TERM_NAME_LEN: usize = 100; /// a supervised study session (etüt). Behaviorally identical — the kind is a /// label for the UI, everything else (enrollment, exams, sessions, marks) /// works the same. -pub const COURSE_KINDS: [&str; 2] = ["course", "study"]; +pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"]; /// The only accepted exam modes. `sync`: everyone sits the exam inside one /// fixed window. `async`: each student starts inside the window and gets their diff --git a/src/database.rs b/src/database.rs index d952f75..b702cb4 100644 --- a/src/database.rs +++ b/src/database.rs @@ -112,6 +112,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS description ON course TYPE string; DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; + DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option; DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; diff --git a/src/domain/course.rs b/src/domain/course.rs index 079a085..a698767 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -60,9 +60,9 @@ impl CourseDescription { } } -/// A validated course kind: `course` (a regular class — ders) or `study` (a -/// supervised study session — etüt). Purely a label; both kinds behave -/// identically. +/// A validated course kind: `course` (a regular class — ders), `study` (a +/// supervised study session — etüt), or `club` (a student club — kulüp). +/// Purely a label; all kinds behave identically. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseKind(String); @@ -84,8 +84,10 @@ impl CourseKind { /// A course: the unit exams and enrollments hang off. Marks are computed per /// course, each exam weighted by its kind's settings weight. May belong to an -/// academic term. Comes in two behaviorally identical kinds: `course` and -/// `study` (etüt). +/// academic term. Comes in three behaviorally identical kinds: `course`, +/// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster +/// at enroll time (`None` = unlimited); rows written before the field existed +/// decode as uncapped. #[derive(Debug, Clone, SurrealValue)] pub struct Course { id: CourseId, @@ -94,6 +96,7 @@ pub struct Course { description: CourseDescription, kind: CourseKind, term: Option, + capacity: Option, } impl Course { @@ -121,6 +124,11 @@ impl Course { self.term.as_ref() } + /// The seat cap enforced at enroll time; `None` = unlimited. + pub fn get_capacity(&self) -> Option { + self.capacity + } + pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } @@ -131,6 +139,7 @@ impl Course { description: CourseDescription, kind: CourseKind, term: Option, + capacity: Option, db: &Database, ) -> Result { let course = Course { @@ -140,6 +149,7 @@ impl Course { description, kind, term, + capacity, }; let created: Option = db.create(course.id.record()).content(course).await?; created.ok_or_else(|| AppError::Internal("failed to create course".into())) @@ -203,12 +213,14 @@ impl Course { description: CourseDescription, kind: CourseKind, term: Option, + capacity: Option, db: &Database, ) -> Result { self.title = title; self.description = description; self.kind = kind; self.term = term; + self.capacity = capacity; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } @@ -259,10 +271,35 @@ mod tests { } #[tokio::test] - async fn kind_is_course_or_study() { + async fn kind_is_course_study_or_club() { assert!(CourseKind::try_new("course").is_ok()); assert!(CourseKind::try_new("study").is_ok()); + assert!(CourseKind::try_new("club").is_ok()); assert!(CourseKind::try_new("etut").is_err()); assert_eq!(CourseKind::course().as_str(), "course"); } + + /// The database strips `NONE`-valued optional columns, and every course + /// row written before the capacity field existed has no `capacity` key at + /// all — both must decode as an uncapped course. + #[tokio::test] + async fn course_decodes_without_capacity_key() { + use surrealdb::types::Value; + + let course = Course { + id: CourseId::generate(), + creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), + title: CourseTitle::try_new("chess").unwrap(), + description: CourseDescription::try_new("").unwrap(), + kind: CourseKind::try_new("club").unwrap(), + term: None, + capacity: Some(12), + }; + let Value::Object(mut object) = course.into_value() else { + panic!("course must encode as an object"); + }; + object.remove("capacity"); + let decoded = Course::from_value(Value::Object(object)).unwrap(); + assert_eq!(decoded.get_capacity(), None); + } } diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 07eae29..e749534 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,10 +1,16 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use crate::database::{Database, ENROLLMENT_TABLE}; -use crate::domain::course::CourseId; +use crate::domain::course::{Course, CourseId}; use crate::domain::user::UserId; use crate::error::AppError; +/// Serializes enrolls so the capacity check (count, then write) can't +/// over-admit under concurrency — the database's optimistic transactions +/// don't serialize cross-record counts against concurrent inserts. +static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EnrollmentId(RecordId); @@ -62,13 +68,31 @@ impl Enrollment { /// Enroll (idempotently) `user` into `course`. One row per (course, user), /// keyed by a deterministic composite id so this is a single atomic UPSERT — /// concurrent enrolls for the same pair converge on one row instead of - /// racing the unique index into a 500. + /// racing the unique index into a 500. When the course carries a capacity, + /// a full roster refuses new members (409) — the whole check-then-write + /// runs under [`ENROLL_LOCK`], and the cap is re-derived from a fresh + /// course read inside it, since neither the transaction model nor a + /// caller-supplied course survives a concurrent capacity PATCH. An already + /// enrolled user is returned as-is even when the roster is full. pub async fn enroll( course: &CourseId, user: &UserId, enrolled_by: &UserId, db: &Database, ) -> Result { + let _guard = ENROLL_LOCK.lock().await; + if let Some(existing) = Self::read_for_user(course, user, db).await? { + return Ok(existing); + } + let capacity = Course::read(course, db) + .await? + .ok_or(AppError::NotFound)? + .get_capacity(); + if let Some(capacity) = capacity + && Self::list_for_course(course, db).await?.len() as i64 >= capacity + { + return Err(AppError::Conflict("the course is full")); + } let enrollment = Enrollment { id: EnrollmentId::composite(course, user), course: course.clone(), diff --git a/src/lib.rs b/src/lib.rs index 0f830e4..173dd74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", ), modifiers(&SecurityAddon), tags( @@ -41,7 +41,7 @@ use crate::state::AppState; (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only)"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (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"), - (name = "courses", description = "Courses — kind `course` (regular class) or `study` (etüt, a supervised study session; same behavior, different label) — enrollment (students only), course exams, and course sessions"), + (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"), (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+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), diff --git a/src/validate.rs b/src/validate.rs index 36dd0fb..70a7f6e 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -203,7 +203,7 @@ pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { } else { Err(ValidationError::Invalid { field: "kind", - reason: "must be one of: course, study", + reason: "must be one of: course, study, club", }) } } @@ -387,10 +387,11 @@ mod tests { #[tokio::test] async fn course_kind_rules() { - for kind in ["course", "study"] { + for kind in ["course", "study", "club"] { assert!(validate_course_kind(kind).is_ok()); } assert!(validate_course_kind("etut").is_err()); + assert!(validate_course_kind("kulup").is_err()); assert!(validate_course_kind("").is_err()); } diff --git a/src/web/courses.rs b/src/web/courses.rs index f10d635..2d1885f 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -50,25 +50,36 @@ struct CreateCourse { #[schema(example = "Algebra")] title: String, description: Option, - /// `course` (a regular class — the default) or `study` (a supervised - /// study session — etüt). Behaviorally identical; a label for the UI. + /// `course` (a regular class — the default), `study` (a supervised study + /// session — etüt), or `club` (a student club — kulüp). Behaviorally + /// identical; a label for the UI. #[schema(example = "course")] kind: Option, /// The academic term this course belongs to (`GET /terms`). Optional. term_id: Option, + /// Seat cap enforced when enrolling, at least 1. Omit for unlimited. + #[schema(example = 12)] + capacity: Option, } #[derive(Deserialize, ToSchema)] struct UpdateCourse { title: Option, description: Option, - /// `course` or `study` (etüt). Omit to keep the current kind. + /// `course`, `study` (etüt), or `club` (kulüp). Omit to keep the current + /// kind. kind: 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>, + /// Omit to keep the current cap, send `null` to lift it, or send a value + /// (at least 1) to (re)cap. Lowering below the current roster keeps the + /// roster — only new enrolls are refused. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, example = 12)] + capacity: Option>, } #[derive(Deserialize, ToSchema)] @@ -186,9 +197,22 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result) -> Result<(), AppError> { + if capacity.is_some_and(|capacity| capacity < 1) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "capacity", + reason: "capacity must be at least 1", + })); + } + Ok(()) +} + /// Create a course owned by the current user. Requires the `teacher` role or -/// higher. `kind` picks the flavor — `course` (a regular class, the default) -/// or `study` (a supervised study session — etüt); both behave identically. +/// higher. `kind` picks the flavor — `course` (a regular class, the default), +/// `study` (a supervised study session — etüt), or `club` (a student club — +/// kulüp); all behave identically. `capacity` caps the roster at enroll time +/// (omit for unlimited). #[utoipa::path( post, path = "/", @@ -197,7 +221,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result CourseKind::course(), }; let term = resolve_term(req.term_id.as_deref(), &st.db).await?; - let course = Course::create(user.get_id(), title, description, kind, term, &st.db).await?; + check_capacity(req.capacity)?; + let course = Course::create( + user.get_id(), + title, + description, + kind, + term, + req.capacity, + &st.db, + ) + .await?; Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) } @@ -321,7 +355,7 @@ async fn get_course( request_body = UpdateCourse, responses( (status = 200, description = "Updated course", body = CourseResponse), - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), + (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -359,9 +393,17 @@ async fn update_course( Some(update) => resolve_term(update.as_deref(), &st.db).await?, None => course.get_term().cloned(), }; + let capacity = match req.capacity { + // Explicit `null` lifts the cap; a value must be positive. + Some(update) => { + check_capacity(update)?; + update + } + None => course.get_capacity(), + }; let updated = course - .update(title, description, kind, term, &st.db) + .update(title, description, kind, term, capacity, &st.db) .await?; Ok(Json(CourseResponse::new(&updated))) } @@ -411,7 +453,8 @@ async fn delete_course( /// Enroll a user into a course (idempotent upsert). Requires teacher+ and /// course management rights. Only students can be enrolled — enrollment is /// student membership, and it gates sitting exams, being graded, and the class -/// roster, all student-only. +/// roster, all student-only. A course with a `capacity` refuses new members +/// once the roster is full (someone already enrolled is returned as-is). #[utoipa::path( post, path = "/{id}/enrollments", @@ -425,6 +468,7 @@ async fn delete_course( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "The course is full", body = ErrorResponse), ), )] async fn enroll( diff --git a/src/web/dto.rs b/src/web/dto.rs index 6a701b3..a37990a 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -161,13 +161,17 @@ pub struct CourseResponse { #[schema(example = "Algebra")] pub title: String, pub description: String, - /// `course` (a regular class) or `study` (a supervised study session — - /// etüt). Behaviorally identical; a label for the UI. + /// `course` (a regular class), `study` (a supervised study session — + /// etüt), or `club` (a student club — kulüp). Behaviorally identical; a + /// label for the UI. #[schema(example = "course")] pub kind: String, /// The academic term this course belongs to (`GET /terms`); `null` when /// unassigned. pub term: Option, + /// Seat cap enforced when enrolling; `null` = unlimited. + #[schema(example = 12)] + pub capacity: Option, } impl CourseResponse { @@ -179,6 +183,7 @@ impl CourseResponse { description: course.get_description().as_str().to_string(), kind: course.get_kind().as_str().to_string(), term: course.get_term().map(|term| term.key().to_string()), + capacity: course.get_capacity(), } } } diff --git a/tests/integration.rs b/tests/integration.rs index c0cbdb1..322c97d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -2359,6 +2359,87 @@ async fn enrollment_upsert_roster_and_my_courses() { ); } +#[tokio::test] +async fn capacity_caps_the_roster() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let bob = login(&app, "bob").await; // student + let alice_id = me_id(&app, &alice).await; + let bob_id = me_id(&app, &bob).await; + + // A zero-seat club is nonsense. + assert_eq!( + send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "chess", "kind": "club", "capacity": 0 })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // A one-seat club. + let created = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "chess", "kind": "club", "capacity": 1 })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED); + assert_eq!(created.body["kind"], "club"); + assert_eq!(created.body["capacity"], 1); + let course_id = id_of(&created.body); + + // The seat goes to alice; bob bounces off the full roster; re-enrolling + // the member stays an idempotent OK even at the cap. + let enroll = |cookie: String, user_id: String| { + let app = app.clone(); + let path = format!("/courses/{course_id}/enrollments"); + async move { + send( + &app, + "POST", + &path, + Some(&cookie), + Some(json!({ "user_id": user_id })), + ) + .await + .status + } + }; + assert_eq!( + enroll(teacher.clone(), alice_id.clone()).await, + StatusCode::OK + ); + assert_eq!( + enroll(teacher.clone(), bob_id.clone()).await, + StatusCode::CONFLICT + ); + assert_eq!( + enroll(teacher.clone(), alice_id.clone()).await, + StatusCode::OK + ); + + // `null` lifts the cap and the door reopens. + let lifted = send( + &app, + "PATCH", + &format!("/courses/{course_id}"), + Some(&teacher), + Some(json!({ "capacity": null })), + ) + .await; + assert_eq!(lifted.status, StatusCode::OK); + assert!(lifted.body["capacity"].is_null()); + assert_eq!(enroll(teacher.clone(), bob_id).await, StatusCode::OK); +} + #[tokio::test] async fn enrollment_requires_course_management() { let (app, db) = app_and_db().await;