Club kind and enroll-time roster capacity
Browse files at this commit7864d0a4ce178281ce1020b000a5bb0a7992290bParent: d8fdbf0- feat
- club kind and enroll-time roster capacity
10 changed files +233 -34
- README.md +15 -9
- src/constant.rs +1 -1
- src/database.rs +1 -0
- src/domain/course.rs +43 -6
- src/domain/enrollment.rs +26 -2
- src/lib.rs +2 -2
- src/validate.rs +3 -2
- src/web/courses.rs +54 -10
- src/web/dto.rs +7 -2
- tests/integration.rs +81 -0
README.mdmodified+15 -9
| @@ -17,8 +17,10 @@ closes the moment the event starts (or, for an event with only an end time — | |||
| 17 | a pure signup deadline — the moment that end passes). Every event stays visible to everyone — | 17 | a pure signup deadline — the moment that end passes). Every event stays visible to everyone — |
| 18 | the audience is a roster, not a wall. Marks are course-shaped | 18 | the audience is a roster, not a wall. Marks are course-shaped |
| 19 | (Google Classroom style): a teacher creates a course — kind **`course`** (a | 19 | (Google Classroom style): a teacher creates a course — kind **`course`** (a |
| 20 | -regular class) or **`study`** (a supervised study session — *etüt*; same | 20 | +regular class), **`study`** (a supervised study session — *etüt*), or |
| 21 | -behavior, different label) — lays out its **subjects** (curriculum topics — | 21 | +**`club`** (a student club — *kulüp*; same behavior, different label), |
| 22 | +optionally capped by a `capacity` that refuses new enrolls once the roster is | ||
| 23 | +full — lays out its **subjects** (curriculum topics — | ||
| 22 | every exam question must be tagged with one of its course's subjects, so | 24 | every exam question must be tagged with one of its course's subjects, so |
| 23 | results can later be read per topic), enrolls students, adds | 25 | results can later be read per topic), enrolls students, adds |
| 24 | exams inside it, and grades — enrolling, sitting exams, roll call, and marks are | 26 | 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`). | |||
| 257 | `Auth` is the minimum role; `no` means no session required, `student` means any | 259 | `Auth` is the minimum role; `no` means no session required, `student` means any |
| 258 | logged-in user. | 260 | logged-in user. |
| 259 | 261 | ||
| 260 | -A course is either a regular class (kind `course`, the default) or an *etüt* | 262 | +A course is a regular class (kind `course`, the default), an *etüt* (kind |
| 261 | -(kind `study` — a supervised study session). The two kinds behave identically | 263 | +`study` — a supervised study session), or a *kulüp* (kind `club` — a student |
| 262 | -everywhere — enrollment, exams, sessions, marks — the kind is a label the UI | 264 | +club). The three kinds behave identically everywhere — enrollment, exams, |
| 263 | -renders differently, settable at creation and editable later. | 265 | +sessions, marks — the kind is a label the UI renders differently, settable at |
| 266 | +creation and editable later. A course may also carry a `capacity`: once the | ||
| 267 | +roster reaches it, new enrolls are refused with `409` (members already on the | ||
| 268 | +roster are unaffected, even if the cap is later lowered below them; `null` | ||
| 269 | +lifts the cap). | ||
| 264 | 270 | ||
| 265 | Course data is walled per course. A course, its exams, its sessions, and its | 271 | Course data is walled per course. A course, its exams, its sessions, and its |
| 266 | subjects are | 272 | subjects are |
| @@ -324,13 +330,13 @@ their existing shapes: the student exam-room reads | |||
| 324 | | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | | 330 | | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | |
| 325 | | 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 | | 331 | | 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 | |
| 326 | | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started | | 332 | | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started | |
| 327 | -| POST | `/courses` | teacher | `{title, description?, kind?, term_id?}` — `kind` is `course` (default) or `study` (etüt) (creator manages it) | | 333 | +| 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) | |
| 328 | | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | | 334 | | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | |
| 329 | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | | 335 | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | |
| 330 | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | | 336 | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | |
| 331 | -| PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | | 337 | +| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (creator, or manager+ for any) | |
| 332 | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) | | 338 | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) | |
| 333 | -| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | | 339 | +| 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) | |
| 334 | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | 340 | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | |
| 335 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | 341 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | |
| 336 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | 342 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | |
src/constant.rsmodified+1 -1
| @@ -112,7 +112,7 @@ pub const MAX_TERM_NAME_LEN: usize = 100; | |||
| 112 | /// a supervised study session (etüt). Behaviorally identical — the kind is a | 112 | /// a supervised study session (etüt). Behaviorally identical — the kind is a |
| 113 | /// label for the UI, everything else (enrollment, exams, sessions, marks) | 113 | /// label for the UI, everything else (enrollment, exams, sessions, marks) |
| 114 | /// works the same. | 114 | /// works the same. |
| 115 | -pub const COURSE_KINDS: [&str; 2] = ["course", "study"]; | 115 | +pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"]; |
| 116 | 116 | ||
| 117 | /// The only accepted exam modes. `sync`: everyone sits the exam inside one | 117 | /// The only accepted exam modes. `sync`: everyone sits the exam inside one |
| 118 | /// fixed window. `async`: each student starts inside the window and gets their | 118 | /// fixed window. `async`: each student starts inside the window and gets their |
src/database.rsmodified+1 -0
| @@ -112,6 +112,7 @@ const MIGRATION: &str = " | |||
| 112 | DEFINE FIELD IF NOT EXISTS description ON course TYPE string; | 112 | DEFINE FIELD IF NOT EXISTS description ON course TYPE string; |
| 113 | DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; | 113 | DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; |
| 114 | DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; | 114 | DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; |
| 115 | + DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>; | ||
| 115 | 116 | ||
| 116 | DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; | 117 | DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; |
| 117 | DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>; | 118 | DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>; |
src/domain/course.rsmodified+43 -6
| @@ -60,9 +60,9 @@ impl CourseDescription { | |||
| 60 | } | 60 | } |
| 61 | } | 61 | } |
| 62 | 62 | ||
| 63 | -/// A validated course kind: `course` (a regular class — ders) or `study` (a | 63 | +/// A validated course kind: `course` (a regular class — ders), `study` (a |
| 64 | -/// supervised study session — etüt). Purely a label; both kinds behave | 64 | +/// supervised study session — etüt), or `club` (a student club — kulüp). |
| 65 | -/// identically. | 65 | +/// Purely a label; all kinds behave identically. |
| 66 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 66 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 67 | pub struct CourseKind(String); | 67 | pub struct CourseKind(String); |
| 68 | 68 | ||
| @@ -84,8 +84,10 @@ impl CourseKind { | |||
| 84 | 84 | ||
| 85 | /// A course: the unit exams and enrollments hang off. Marks are computed per | 85 | /// A course: the unit exams and enrollments hang off. Marks are computed per |
| 86 | /// course, each exam weighted by its kind's settings weight. May belong to an | 86 | /// course, each exam weighted by its kind's settings weight. May belong to an |
| 87 | -/// academic term. Comes in two behaviorally identical kinds: `course` and | 87 | +/// academic term. Comes in three behaviorally identical kinds: `course`, |
| 88 | -/// `study` (etüt). | 88 | +/// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster |
| 89 | +/// at enroll time (`None` = unlimited); rows written before the field existed | ||
| 90 | +/// decode as uncapped. | ||
| 89 | #[derive(Debug, Clone, SurrealValue)] | 91 | #[derive(Debug, Clone, SurrealValue)] |
| 90 | pub struct Course { | 92 | pub struct Course { |
| 91 | id: CourseId, | 93 | id: CourseId, |
| @@ -94,6 +96,7 @@ pub struct Course { | |||
| 94 | description: CourseDescription, | 96 | description: CourseDescription, |
| 95 | kind: CourseKind, | 97 | kind: CourseKind, |
| 96 | term: Option<TermId>, | 98 | term: Option<TermId>, |
| 99 | + capacity: Option<i64>, | ||
| 97 | } | 100 | } |
| 98 | 101 | ||
| 99 | impl Course { | 102 | impl Course { |
| @@ -121,6 +124,11 @@ impl Course { | |||
| 121 | self.term.as_ref() | 124 | self.term.as_ref() |
| 122 | } | 125 | } |
| 123 | 126 | ||
| 127 | + /// The seat cap enforced at enroll time; `None` = unlimited. | ||
| 128 | + pub fn get_capacity(&self) -> Option<i64> { | ||
| 129 | + self.capacity | ||
| 130 | + } | ||
| 131 | + | ||
| 124 | pub fn is_creator(&self, user: &UserId) -> bool { | 132 | pub fn is_creator(&self, user: &UserId) -> bool { |
| 125 | &self.creator == user | 133 | &self.creator == user |
| 126 | } | 134 | } |
| @@ -131,6 +139,7 @@ impl Course { | |||
| 131 | description: CourseDescription, | 139 | description: CourseDescription, |
| 132 | kind: CourseKind, | 140 | kind: CourseKind, |
| 133 | term: Option<TermId>, | 141 | term: Option<TermId>, |
| 142 | + capacity: Option<i64>, | ||
| 134 | db: &Database, | 143 | db: &Database, |
| 135 | ) -> Result<Course, AppError> { | 144 | ) -> Result<Course, AppError> { |
| 136 | let course = Course { | 145 | let course = Course { |
| @@ -140,6 +149,7 @@ impl Course { | |||
| 140 | description, | 149 | description, |
| 141 | kind, | 150 | kind, |
| 142 | term, | 151 | term, |
| 152 | + capacity, | ||
| 143 | }; | 153 | }; |
| 144 | let created: Option<Course> = db.create(course.id.record()).content(course).await?; | 154 | let created: Option<Course> = db.create(course.id.record()).content(course).await?; |
| 145 | created.ok_or_else(|| AppError::Internal("failed to create course".into())) | 155 | created.ok_or_else(|| AppError::Internal("failed to create course".into())) |
| @@ -203,12 +213,14 @@ impl Course { | |||
| 203 | description: CourseDescription, | 213 | description: CourseDescription, |
| 204 | kind: CourseKind, | 214 | kind: CourseKind, |
| 205 | term: Option<TermId>, | 215 | term: Option<TermId>, |
| 216 | + capacity: Option<i64>, | ||
| 206 | db: &Database, | 217 | db: &Database, |
| 207 | ) -> Result<Course, AppError> { | 218 | ) -> Result<Course, AppError> { |
| 208 | self.title = title; | 219 | self.title = title; |
| 209 | self.description = description; | 220 | self.description = description; |
| 210 | self.kind = kind; | 221 | self.kind = kind; |
| 211 | self.term = term; | 222 | self.term = term; |
| 223 | + self.capacity = capacity; | ||
| 212 | let updated: Option<Course> = db.update(self.id.record()).content(self).await?; | 224 | let updated: Option<Course> = db.update(self.id.record()).content(self).await?; |
| 213 | updated.ok_or(AppError::NotFound) | 225 | updated.ok_or(AppError::NotFound) |
| 214 | } | 226 | } |
| @@ -259,10 +271,35 @@ mod tests { | |||
| 259 | } | 271 | } |
| 260 | 272 | ||
| 261 | #[tokio::test] | 273 | #[tokio::test] |
| 262 | - async fn kind_is_course_or_study() { | 274 | + async fn kind_is_course_study_or_club() { |
| 263 | assert!(CourseKind::try_new("course").is_ok()); | 275 | assert!(CourseKind::try_new("course").is_ok()); |
| 264 | assert!(CourseKind::try_new("study").is_ok()); | 276 | assert!(CourseKind::try_new("study").is_ok()); |
| 277 | + assert!(CourseKind::try_new("club").is_ok()); | ||
| 265 | assert!(CourseKind::try_new("etut").is_err()); | 278 | assert!(CourseKind::try_new("etut").is_err()); |
| 266 | assert_eq!(CourseKind::course().as_str(), "course"); | 279 | assert_eq!(CourseKind::course().as_str(), "course"); |
| 267 | } | 280 | } |
| 281 | + | ||
| 282 | + /// The database strips `NONE`-valued optional columns, and every course | ||
| 283 | + /// row written before the capacity field existed has no `capacity` key at | ||
| 284 | + /// all — both must decode as an uncapped course. | ||
| 285 | + #[tokio::test] | ||
| 286 | + async fn course_decodes_without_capacity_key() { | ||
| 287 | + use surrealdb::types::Value; | ||
| 288 | + | ||
| 289 | + let course = Course { | ||
| 290 | + id: CourseId::generate(), | ||
| 291 | + creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), | ||
| 292 | + title: CourseTitle::try_new("chess").unwrap(), | ||
| 293 | + description: CourseDescription::try_new("").unwrap(), | ||
| 294 | + kind: CourseKind::try_new("club").unwrap(), | ||
| 295 | + term: None, | ||
| 296 | + capacity: Some(12), | ||
| 297 | + }; | ||
| 298 | + let Value::Object(mut object) = course.into_value() else { | ||
| 299 | + panic!("course must encode as an object"); | ||
| 300 | + }; | ||
| 301 | + object.remove("capacity"); | ||
| 302 | + let decoded = Course::from_value(Value::Object(object)).unwrap(); | ||
| 303 | + assert_eq!(decoded.get_capacity(), None); | ||
| 304 | + } | ||
| 268 | } | 305 | } |
src/domain/enrollment.rsmodified+26 -2
| @@ -1,10 +1,16 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | +use tokio::sync::Mutex; | ||
| 2 | 3 | ||
| 3 | use crate::database::{Database, ENROLLMENT_TABLE}; | 4 | use crate::database::{Database, ENROLLMENT_TABLE}; |
| 4 | -use crate::domain::course::CourseId; | 5 | +use crate::domain::course::{Course, CourseId}; |
| 5 | use crate::domain::user::UserId; | 6 | use crate::domain::user::UserId; |
| 6 | use crate::error::AppError; | 7 | use crate::error::AppError; |
| 7 | 8 | ||
| 9 | +/// Serializes enrolls so the capacity check (count, then write) can't | ||
| 10 | +/// over-admit under concurrency — the database's optimistic transactions | ||
| 11 | +/// don't serialize cross-record counts against concurrent inserts. | ||
| 12 | +static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 13 | + | ||
| 8 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 14 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 9 | pub struct EnrollmentId(RecordId); | 15 | pub struct EnrollmentId(RecordId); |
| 10 | 16 | ||
| @@ -62,13 +68,31 @@ impl Enrollment { | |||
| 62 | /// Enroll (idempotently) `user` into `course`. One row per (course, user), | 68 | /// Enroll (idempotently) `user` into `course`. One row per (course, user), |
| 63 | /// keyed by a deterministic composite id so this is a single atomic UPSERT — | 69 | /// keyed by a deterministic composite id so this is a single atomic UPSERT — |
| 64 | /// concurrent enrolls for the same pair converge on one row instead of | 70 | /// concurrent enrolls for the same pair converge on one row instead of |
| 65 | - /// racing the unique index into a 500. | 71 | + /// racing the unique index into a 500. When the course carries a capacity, |
| 72 | + /// a full roster refuses new members (409) — the whole check-then-write | ||
| 73 | + /// runs under [`ENROLL_LOCK`], and the cap is re-derived from a fresh | ||
| 74 | + /// course read inside it, since neither the transaction model nor a | ||
| 75 | + /// caller-supplied course survives a concurrent capacity PATCH. An already | ||
| 76 | + /// enrolled user is returned as-is even when the roster is full. | ||
| 66 | pub async fn enroll( | 77 | pub async fn enroll( |
| 67 | course: &CourseId, | 78 | course: &CourseId, |
| 68 | user: &UserId, | 79 | user: &UserId, |
| 69 | enrolled_by: &UserId, | 80 | enrolled_by: &UserId, |
| 70 | db: &Database, | 81 | db: &Database, |
| 71 | ) -> Result<Enrollment, AppError> { | 82 | ) -> Result<Enrollment, AppError> { |
| 83 | + let _guard = ENROLL_LOCK.lock().await; | ||
| 84 | + if let Some(existing) = Self::read_for_user(course, user, db).await? { | ||
| 85 | + return Ok(existing); | ||
| 86 | + } | ||
| 87 | + let capacity = Course::read(course, db) | ||
| 88 | + .await? | ||
| 89 | + .ok_or(AppError::NotFound)? | ||
| 90 | + .get_capacity(); | ||
| 91 | + if let Some(capacity) = capacity | ||
| 92 | + && Self::list_for_course(course, db).await?.len() as i64 >= capacity | ||
| 93 | + { | ||
| 94 | + return Err(AppError::Conflict("the course is full")); | ||
| 95 | + } | ||
| 72 | let enrollment = Enrollment { | 96 | let enrollment = Enrollment { |
| 73 | id: EnrollmentId::composite(course, user), | 97 | id: EnrollmentId::composite(course, user), |
| 74 | course: course.clone(), | 98 | course: course.clone(), |
src/lib.rsmodified+2 -2
| @@ -32,7 +32,7 @@ use crate::state::AppState; | |||
| 32 | info( | 32 | info( |
| 33 | title = "Hezarfen Backend API", | 33 | title = "Hezarfen Backend API", |
| 34 | version = env!("CARGO_PKG_VERSION"), | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - 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.", | 35 | + 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.", |
| 36 | ), | 36 | ), |
| 37 | modifiers(&SecurityAddon), | 37 | modifiers(&SecurityAddon), |
| 38 | tags( | 38 | tags( |
| @@ -41,7 +41,7 @@ use crate::state::AppState; | |||
| 41 | (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)"), | 41 | (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)"), |
| 42 | (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`)"), | 42 | (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`)"), |
| 43 | (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"), | 43 | (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"), |
| 44 | - (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"), | 44 | + (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"), |
| 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), | 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| 46 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | 46 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 47 | (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"), | 47 | (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"), |
src/validate.rsmodified+3 -2
| @@ -203,7 +203,7 @@ pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { | |||
| 203 | } else { | 203 | } else { |
| 204 | Err(ValidationError::Invalid { | 204 | Err(ValidationError::Invalid { |
| 205 | field: "kind", | 205 | field: "kind", |
| 206 | - reason: "must be one of: course, study", | 206 | + reason: "must be one of: course, study, club", |
| 207 | }) | 207 | }) |
| 208 | } | 208 | } |
| 209 | } | 209 | } |
| @@ -387,10 +387,11 @@ mod tests { | |||
| 387 | 387 | ||
| 388 | #[tokio::test] | 388 | #[tokio::test] |
| 389 | async fn course_kind_rules() { | 389 | async fn course_kind_rules() { |
| 390 | - for kind in ["course", "study"] { | 390 | + for kind in ["course", "study", "club"] { |
| 391 | assert!(validate_course_kind(kind).is_ok()); | 391 | assert!(validate_course_kind(kind).is_ok()); |
| 392 | } | 392 | } |
| 393 | assert!(validate_course_kind("etut").is_err()); | 393 | assert!(validate_course_kind("etut").is_err()); |
| 394 | + assert!(validate_course_kind("kulup").is_err()); | ||
| 394 | assert!(validate_course_kind("").is_err()); | 395 | assert!(validate_course_kind("").is_err()); |
| 395 | } | 396 | } |
| 396 | 397 | ||
src/web/courses.rsmodified+54 -10
| @@ -50,25 +50,36 @@ struct CreateCourse { | |||
| 50 | #[schema(example = "Algebra")] | 50 | #[schema(example = "Algebra")] |
| 51 | title: String, | 51 | title: String, |
| 52 | description: Option<String>, | 52 | description: Option<String>, |
| 53 | - /// `course` (a regular class — the default) or `study` (a supervised | 53 | + /// `course` (a regular class — the default), `study` (a supervised study |
| 54 | - /// study session — etüt). Behaviorally identical; a label for the UI. | 54 | + /// session — etüt), or `club` (a student club — kulüp). Behaviorally |
| 55 | + /// identical; a label for the UI. | ||
| 55 | #[schema(example = "course")] | 56 | #[schema(example = "course")] |
| 56 | kind: Option<String>, | 57 | kind: Option<String>, |
| 57 | /// The academic term this course belongs to (`GET /terms`). Optional. | 58 | /// The academic term this course belongs to (`GET /terms`). Optional. |
| 58 | term_id: Option<String>, | 59 | term_id: Option<String>, |
| 60 | + /// Seat cap enforced when enrolling, at least 1. Omit for unlimited. | ||
| 61 | + #[schema(example = 12)] | ||
| 62 | + capacity: Option<i64>, | ||
| 59 | } | 63 | } |
| 60 | 64 | ||
| 61 | #[derive(Deserialize, ToSchema)] | 65 | #[derive(Deserialize, ToSchema)] |
| 62 | struct UpdateCourse { | 66 | struct UpdateCourse { |
| 63 | title: Option<String>, | 67 | title: Option<String>, |
| 64 | description: Option<String>, | 68 | description: Option<String>, |
| 65 | - /// `course` or `study` (etüt). Omit to keep the current kind. | 69 | + /// `course`, `study` (etüt), or `club` (kulüp). Omit to keep the current |
| 70 | + /// kind. | ||
| 66 | kind: Option<String>, | 71 | kind: Option<String>, |
| 67 | /// Omit to keep the current term, send `null` to unlink, or send a term | 72 | /// Omit to keep the current term, send `null` to unlink, or send a term |
| 68 | /// id to (re)assign. | 73 | /// id to (re)assign. |
| 69 | #[serde(default, deserialize_with = "set_or_clear")] | 74 | #[serde(default, deserialize_with = "set_or_clear")] |
| 70 | #[schema(value_type = Option<String>)] | 75 | #[schema(value_type = Option<String>)] |
| 71 | term_id: Option<Option<String>>, | 76 | term_id: Option<Option<String>>, |
| 77 | + /// Omit to keep the current cap, send `null` to lift it, or send a value | ||
| 78 | + /// (at least 1) to (re)cap. Lowering below the current roster keeps the | ||
| 79 | + /// roster — only new enrolls are refused. | ||
| 80 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 81 | + #[schema(value_type = Option<i64>, example = 12)] | ||
| 82 | + capacity: Option<Option<i64>>, | ||
| 72 | } | 83 | } |
| 73 | 84 | ||
| 74 | #[derive(Deserialize, ToSchema)] | 85 | #[derive(Deserialize, ToSchema)] |
| @@ -186,9 +197,22 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co | |||
| 186 | 197 | ||
| 187 | // ---- courses ------------------------------------------------------------ | 198 | // ---- courses ------------------------------------------------------------ |
| 188 | 199 | ||
| 200 | +/// A seat cap, when given, must be positive — `null`/omitted means unlimited. | ||
| 201 | +fn check_capacity(capacity: Option<i64>) -> Result<(), AppError> { | ||
| 202 | + if capacity.is_some_and(|capacity| capacity < 1) { | ||
| 203 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 204 | + field: "capacity", | ||
| 205 | + reason: "capacity must be at least 1", | ||
| 206 | + })); | ||
| 207 | + } | ||
| 208 | + Ok(()) | ||
| 209 | +} | ||
| 210 | + | ||
| 189 | /// Create a course owned by the current user. Requires the `teacher` role or | 211 | /// Create a course owned by the current user. Requires the `teacher` role or |
| 190 | -/// higher. `kind` picks the flavor — `course` (a regular class, the default) | 212 | +/// higher. `kind` picks the flavor — `course` (a regular class, the default), |
| 191 | -/// or `study` (a supervised study session — etüt); both behave identically. | 213 | +/// `study` (a supervised study session — etüt), or `club` (a student club — |
| 214 | +/// kulüp); all behave identically. `capacity` caps the roster at enroll time | ||
| 215 | +/// (omit for unlimited). | ||
| 192 | #[utoipa::path( | 216 | #[utoipa::path( |
| 193 | post, | 217 | post, |
| 194 | path = "/", | 218 | path = "/", |
| @@ -197,7 +221,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co | |||
| 197 | request_body = CreateCourse, | 221 | request_body = CreateCourse, |
| 198 | responses( | 222 | responses( |
| 199 | (status = 201, description = "Course created", body = CourseResponse), | 223 | (status = 201, description = "Course created", body = CourseResponse), |
| 200 | - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), | 224 | + (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), |
| 201 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 225 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 202 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 226 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 203 | ), | 227 | ), |
| @@ -214,7 +238,17 @@ async fn create_course( | |||
| 214 | None => CourseKind::course(), | 238 | None => CourseKind::course(), |
| 215 | }; | 239 | }; |
| 216 | let term = resolve_term(req.term_id.as_deref(), &st.db).await?; | 240 | let term = resolve_term(req.term_id.as_deref(), &st.db).await?; |
| 217 | - let course = Course::create(user.get_id(), title, description, kind, term, &st.db).await?; | 241 | + check_capacity(req.capacity)?; |
| 242 | + let course = Course::create( | ||
| 243 | + user.get_id(), | ||
| 244 | + title, | ||
| 245 | + description, | ||
| 246 | + kind, | ||
| 247 | + term, | ||
| 248 | + req.capacity, | ||
| 249 | + &st.db, | ||
| 250 | + ) | ||
| 251 | + .await?; | ||
| 218 | Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) | 252 | Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) |
| 219 | } | 253 | } |
| 220 | 254 | ||
| @@ -321,7 +355,7 @@ async fn get_course( | |||
| 321 | request_body = UpdateCourse, | 355 | request_body = UpdateCourse, |
| 322 | responses( | 356 | responses( |
| 323 | (status = 200, description = "Updated course", body = CourseResponse), | 357 | (status = 200, description = "Updated course", body = CourseResponse), |
| 324 | - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), | 358 | + (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), |
| 325 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 359 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 326 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | 360 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), |
| 327 | (status = 404, description = "Not found", body = ErrorResponse), | 361 | (status = 404, description = "Not found", body = ErrorResponse), |
| @@ -359,9 +393,17 @@ async fn update_course( | |||
| 359 | Some(update) => resolve_term(update.as_deref(), &st.db).await?, | 393 | Some(update) => resolve_term(update.as_deref(), &st.db).await?, |
| 360 | None => course.get_term().cloned(), | 394 | None => course.get_term().cloned(), |
| 361 | }; | 395 | }; |
| 396 | + let capacity = match req.capacity { | ||
| 397 | + // Explicit `null` lifts the cap; a value must be positive. | ||
| 398 | + Some(update) => { | ||
| 399 | + check_capacity(update)?; | ||
| 400 | + update | ||
| 401 | + } | ||
| 402 | + None => course.get_capacity(), | ||
| 403 | + }; | ||
| 362 | 404 | ||
| 363 | let updated = course | 405 | let updated = course |
| 364 | - .update(title, description, kind, term, &st.db) | 406 | + .update(title, description, kind, term, capacity, &st.db) |
| 365 | .await?; | 407 | .await?; |
| 366 | Ok(Json(CourseResponse::new(&updated))) | 408 | Ok(Json(CourseResponse::new(&updated))) |
| 367 | } | 409 | } |
| @@ -411,7 +453,8 @@ async fn delete_course( | |||
| 411 | /// Enroll a user into a course (idempotent upsert). Requires teacher+ and | 453 | /// Enroll a user into a course (idempotent upsert). Requires teacher+ and |
| 412 | /// course management rights. Only students can be enrolled — enrollment is | 454 | /// course management rights. Only students can be enrolled — enrollment is |
| 413 | /// student membership, and it gates sitting exams, being graded, and the class | 455 | /// student membership, and it gates sitting exams, being graded, and the class |
| 414 | -/// roster, all student-only. | 456 | +/// roster, all student-only. A course with a `capacity` refuses new members |
| 457 | +/// once the roster is full (someone already enrolled is returned as-is). | ||
| 415 | #[utoipa::path( | 458 | #[utoipa::path( |
| 416 | post, | 459 | post, |
| 417 | path = "/{id}/enrollments", | 460 | path = "/{id}/enrollments", |
| @@ -425,6 +468,7 @@ async fn delete_course( | |||
| 425 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 468 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 426 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | 469 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 427 | (status = 404, description = "Course not found", body = ErrorResponse), | 470 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 471 | + (status = 409, description = "The course is full", body = ErrorResponse), | ||
| 428 | ), | 472 | ), |
| 429 | )] | 473 | )] |
| 430 | async fn enroll( | 474 | async fn enroll( |
src/web/dto.rsmodified+7 -2
| @@ -161,13 +161,17 @@ pub struct CourseResponse { | |||
| 161 | #[schema(example = "Algebra")] | 161 | #[schema(example = "Algebra")] |
| 162 | pub title: String, | 162 | pub title: String, |
| 163 | pub description: String, | 163 | pub description: String, |
| 164 | - /// `course` (a regular class) or `study` (a supervised study session — | 164 | + /// `course` (a regular class), `study` (a supervised study session — |
| 165 | - /// etüt). Behaviorally identical; a label for the UI. | 165 | + /// etüt), or `club` (a student club — kulüp). Behaviorally identical; a |
| 166 | + /// label for the UI. | ||
| 166 | #[schema(example = "course")] | 167 | #[schema(example = "course")] |
| 167 | pub kind: String, | 168 | pub kind: String, |
| 168 | /// The academic term this course belongs to (`GET /terms`); `null` when | 169 | /// The academic term this course belongs to (`GET /terms`); `null` when |
| 169 | /// unassigned. | 170 | /// unassigned. |
| 170 | pub term: Option<String>, | 171 | pub term: Option<String>, |
| 172 | + /// Seat cap enforced when enrolling; `null` = unlimited. | ||
| 173 | + #[schema(example = 12)] | ||
| 174 | + pub capacity: Option<i64>, | ||
| 171 | } | 175 | } |
| 172 | 176 | ||
| 173 | impl CourseResponse { | 177 | impl CourseResponse { |
| @@ -179,6 +183,7 @@ impl CourseResponse { | |||
| 179 | description: course.get_description().as_str().to_string(), | 183 | description: course.get_description().as_str().to_string(), |
| 180 | kind: course.get_kind().as_str().to_string(), | 184 | kind: course.get_kind().as_str().to_string(), |
| 181 | term: course.get_term().map(|term| term.key().to_string()), | 185 | term: course.get_term().map(|term| term.key().to_string()), |
| 186 | + capacity: course.get_capacity(), | ||
| 182 | } | 187 | } |
| 183 | } | 188 | } |
| 184 | } | 189 | } |
tests/integration.rsmodified+81 -0
| @@ -2359,6 +2359,87 @@ async fn enrollment_upsert_roster_and_my_courses() { | |||
| 2359 | ); | 2359 | ); |
| 2360 | } | 2360 | } |
| 2361 | 2361 | ||
| 2362 | +#[tokio::test] | ||
| 2363 | +async fn capacity_caps_the_roster() { | ||
| 2364 | + let (app, db) = app_and_db().await; | ||
| 2365 | + let teacher = login_as(&app, &db, "teacher", "teacher").await; | ||
| 2366 | + let alice = login(&app, "alice").await; // student | ||
| 2367 | + let bob = login(&app, "bob").await; // student | ||
| 2368 | + let alice_id = me_id(&app, &alice).await; | ||
| 2369 | + let bob_id = me_id(&app, &bob).await; | ||
| 2370 | + | ||
| 2371 | + // A zero-seat club is nonsense. | ||
| 2372 | + assert_eq!( | ||
| 2373 | + send( | ||
| 2374 | + &app, | ||
| 2375 | + "POST", | ||
| 2376 | + "/courses", | ||
| 2377 | + Some(&teacher), | ||
| 2378 | + Some(json!({ "title": "chess", "kind": "club", "capacity": 0 })), | ||
| 2379 | + ) | ||
| 2380 | + .await | ||
| 2381 | + .status, | ||
| 2382 | + StatusCode::BAD_REQUEST | ||
| 2383 | + ); | ||
| 2384 | + | ||
| 2385 | + // A one-seat club. | ||
| 2386 | + let created = send( | ||
| 2387 | + &app, | ||
| 2388 | + "POST", | ||
| 2389 | + "/courses", | ||
| 2390 | + Some(&teacher), | ||
| 2391 | + Some(json!({ "title": "chess", "kind": "club", "capacity": 1 })), | ||
| 2392 | + ) | ||
| 2393 | + .await; | ||
| 2394 | + assert_eq!(created.status, StatusCode::CREATED); | ||
| 2395 | + assert_eq!(created.body["kind"], "club"); | ||
| 2396 | + assert_eq!(created.body["capacity"], 1); | ||
| 2397 | + let course_id = id_of(&created.body); | ||
| 2398 | + | ||
| 2399 | + // The seat goes to alice; bob bounces off the full roster; re-enrolling | ||
| 2400 | + // the member stays an idempotent OK even at the cap. | ||
| 2401 | + let enroll = |cookie: String, user_id: String| { | ||
| 2402 | + let app = app.clone(); | ||
| 2403 | + let path = format!("/courses/{course_id}/enrollments"); | ||
| 2404 | + async move { | ||
| 2405 | + send( | ||
| 2406 | + &app, | ||
| 2407 | + "POST", | ||
| 2408 | + &path, | ||
| 2409 | + Some(&cookie), | ||
| 2410 | + Some(json!({ "user_id": user_id })), | ||
| 2411 | + ) | ||
| 2412 | + .await | ||
| 2413 | + .status | ||
| 2414 | + } | ||
| 2415 | + }; | ||
| 2416 | + assert_eq!( | ||
| 2417 | + enroll(teacher.clone(), alice_id.clone()).await, | ||
| 2418 | + StatusCode::OK | ||
| 2419 | + ); | ||
| 2420 | + assert_eq!( | ||
| 2421 | + enroll(teacher.clone(), bob_id.clone()).await, | ||
| 2422 | + StatusCode::CONFLICT | ||
| 2423 | + ); | ||
| 2424 | + assert_eq!( | ||
| 2425 | + enroll(teacher.clone(), alice_id.clone()).await, | ||
| 2426 | + StatusCode::OK | ||
| 2427 | + ); | ||
| 2428 | + | ||
| 2429 | + // `null` lifts the cap and the door reopens. | ||
| 2430 | + let lifted = send( | ||
| 2431 | + &app, | ||
| 2432 | + "PATCH", | ||
| 2433 | + &format!("/courses/{course_id}"), | ||
| 2434 | + Some(&teacher), | ||
| 2435 | + Some(json!({ "capacity": null })), | ||
| 2436 | + ) | ||
| 2437 | + .await; | ||
| 2438 | + assert_eq!(lifted.status, StatusCode::OK); | ||
| 2439 | + assert!(lifted.body["capacity"].is_null()); | ||
| 2440 | + assert_eq!(enroll(teacher.clone(), bob_id).await, StatusCode::OK); | ||
| 2441 | +} | ||
| 2442 | + | ||
| 2362 | #[tokio::test] | 2443 | #[tokio::test] |
| 2363 | async fn enrollment_requires_course_management() { | 2444 | async fn enrollment_requires_course_management() { |
| 2364 | let (app, db) = app_and_db().await; | 2445 | let (app, db) = app_and_db().await; |