From f29537cadbee032c4576fc2af74032c8abb4e89b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 16 Jul 2026 20:28:18 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(courses):=20add=20kind=20cours?= =?UTF-8?q?e|study=20(supervised=20study)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Supervised study sessions are courses under a different label: `kind` is settable at creation, PATCH-editable, and returned on every course response. Behavior (enrollment, exams, sessions, marks) is identical for both kinds. Boot backfills pre-kind rows to `kind = 'course'`; new writes default the same way. --- README.md | 11 ++++++-- src/constant.rs | 6 ++++ src/database.rs | 3 ++ src/domain/course.rs | 44 ++++++++++++++++++++++++++++-- src/lib.rs | 4 +-- src/validate.rs | 28 ++++++++++++++++--- src/web/courses.rs | 30 ++++++++++++++++---- src/web/dto.rs | 5 ++++ tests/integration.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 180 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index d2d583c..108f43e 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,9 @@ by seat: teachers register students (never the other way round), staff register only themselves, an optional `capacity` caps the seats, and the list closes the moment the event starts. 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, enrolls students, adds +(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) — enrolls students, adds exams inside it, and grades — enrolling, sitting exams, roll call, and marks are all student-only, staff never take part; students read a per-course weighted average and an overall average from their mark report — each exam weighted by its **kind** @@ -237,6 +239,11 @@ 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. + Course data is walled per course. A course, its exams, and its sessions are **visible** only to its enrolled users, its creator, and manager+ — a student sees just the classes they were added to, and the `/courses` / `/exams` @@ -298,7 +305,7 @@ 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?}` (creator manages it) | +| POST | `/courses` | teacher | `{title, description?, kind?, term_id?}` — `kind` is `course` (default) or `study` (etüt) (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+) | diff --git a/src/constant.rs b/src/constant.rs index 39c43ef..c49ccc0 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -99,6 +99,12 @@ pub const SETTINGS_UPDATE_RETRIES: usize = 3; pub const MAX_TERM_NAME_LEN: usize = 100; +/// The only accepted course kinds. `course`: a regular class (ders). `study`: +/// 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"]; + /// The only accepted exam modes. `sync`: everyone sits the exam inside one /// fixed window. `async`: each student starts inside the window and gets their /// own `duration_ms` slice of it. `open`: no window — students sit anytime, diff --git a/src/database.rs b/src/database.rs index deb5a3c..7235a91 100644 --- a/src/database.rs +++ b/src/database.rs @@ -107,6 +107,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; DEFINE FIELD IF NOT EXISTS title ON course TYPE string; 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 TABLE IF NOT EXISTS enrollment SCHEMAFULL; @@ -210,6 +211,8 @@ const MIGRATION: &str = " const BACKFILL: &str = " UPDATE user SET role = 'student' WHERE role = NONE; + UPDATE course SET kind = 'course' WHERE kind = NONE; + UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; -- The hand-picked `users` audience retired into `registration` (2026-07-16): diff --git a/src/domain/course.rs b/src/domain/course.rs index e83b6f8..077ca67 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -6,7 +6,7 @@ use crate::database::{COURSE_TABLE, Database}; use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -use crate::validate::{validate_optional, validate_required}; +use crate::validate::{validate_course_kind, validate_optional, validate_required}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseId(RecordId); @@ -60,15 +60,39 @@ 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. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct CourseKind(String); + +impl CourseKind { + pub fn try_new(value: &str) -> Result { + validate_course_kind(value)?; + Ok(Self(value.to_string())) + } + + /// The classic kind — what every course is unless said otherwise. + pub fn course() -> Self { + Self("course".to_string()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + /// 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. +/// academic term. Comes in two behaviorally identical kinds: `course` and +/// `study` (etüt). #[derive(Debug, Clone, SurrealValue)] pub struct Course { id: CourseId, creator: UserId, title: CourseTitle, description: CourseDescription, + kind: CourseKind, term: Option, } @@ -89,6 +113,10 @@ impl Course { &self.description } + pub fn get_kind(&self) -> &CourseKind { + &self.kind + } + pub fn get_term(&self) -> Option<&TermId> { self.term.as_ref() } @@ -101,6 +129,7 @@ impl Course { creator: &UserId, title: CourseTitle, description: CourseDescription, + kind: CourseKind, term: Option, db: &Database, ) -> Result { @@ -109,6 +138,7 @@ impl Course { creator: creator.clone(), title, description, + kind, term, }; let created: Option = db.create(course.id.record()).content(course).await?; @@ -171,11 +201,13 @@ impl Course { mut self, title: CourseTitle, description: CourseDescription, + kind: CourseKind, term: Option, db: &Database, ) -> Result { self.title = title; self.description = description; + self.kind = kind; self.term = term; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) @@ -221,4 +253,12 @@ mod tests { async fn description_is_optional() { assert!(CourseDescription::try_new("").is_ok()); } + + #[tokio::test] + async fn kind_is_course_or_study() { + assert!(CourseKind::try_new("course").is_ok()); + assert!(CourseKind::try_new("study").is_ok()); + assert!(CourseKind::try_new("etut").is_err()); + assert_eq!(CourseKind::course().as_str(), "course"); + } } diff --git a/src/lib.rs b/src/lib.rs index 1a80c38..365a220 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. 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 carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; 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. 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; staff clock in/out on a server-stamped work log; 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, enrollment (students only), course exams, and course sessions"), + (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 = "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 = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), diff --git a/src/validate.rs b/src/validate.rs index 956fd3f..36dd0fb 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,10 +2,10 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, - MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, - MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, - UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, + COURSE_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, + MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, + MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, + MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -197,6 +197,17 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> { Ok(()) } +pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { + if COURSE_KINDS.contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "kind", + reason: "must be one of: course, study", + }) + } +} + pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { if EXAM_MODES.contains(&value) { Ok(()) @@ -374,6 +385,15 @@ mod tests { assert!(validate_phone("55+5123456").is_err()); // + only allowed in front } + #[tokio::test] + async fn course_kind_rules() { + for kind in ["course", "study"] { + assert!(validate_course_kind(kind).is_ok()); + } + assert!(validate_course_kind("etut").is_err()); + assert!(validate_course_kind("").is_err()); + } + #[tokio::test] async fn exam_mode_rules() { for mode in ["sync", "async", "open"] { diff --git a/src/web/courses.rs b/src/web/courses.rs index 4a26e1b..87e5e91 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; +use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ @@ -46,6 +46,10 @@ 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. + #[schema(example = "course")] + kind: Option, /// The academic term this course belongs to (`GET /terms`). Optional. term_id: Option, } @@ -54,6 +58,8 @@ struct CreateCourse { struct UpdateCourse { title: Option, description: Option, + /// `course` or `study` (etüt). 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")] @@ -172,7 +178,9 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result Result Result<(StatusCode, Json), AppError> { let title = CourseTitle::try_new(&req.title)?; let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; + let kind = match req.kind { + Some(ref kind) => CourseKind::try_new(kind)?, + None => CourseKind::course(), + }; let term = resolve_term(req.term_id.as_deref(), &st.db).await?; - let course = Course::create(user.get_id(), title, description, term, &st.db).await?; + let course = Course::create(user.get_id(), title, description, kind, term, &st.db).await?; Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) } @@ -301,7 +313,7 @@ async fn get_course( request_body = UpdateCourse, responses( (status = 200, description = "Updated course", body = CourseResponse), - (status = 400, description = "Invalid fields", body = ErrorResponse), + (status = 400, description = "Invalid fields or kind", 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), @@ -330,13 +342,19 @@ async fn update_course( Some(ref description) => CourseDescription::try_new(description)?, None => course.get_description().clone(), }; + let kind = match req.kind { + Some(ref kind) => CourseKind::try_new(kind)?, + None => course.get_kind().clone(), + }; let term = match req.term_id { // Explicit `null` clears the link; a value must name a real term. Some(update) => resolve_term(update.as_deref(), &st.db).await?, None => course.get_term().cloned(), }; - let updated = course.update(title, description, term, &st.db).await?; + let updated = course + .update(title, description, kind, term, &st.db) + .await?; Ok(Json(CourseResponse::new(&updated))) } diff --git a/src/web/dto.rs b/src/web/dto.rs index ca57632..babf1d2 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -160,6 +160,10 @@ 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. + #[schema(example = "course")] + pub kind: String, /// The academic term this course belongs to (`GET /terms`); `null` when /// unassigned. pub term: Option, @@ -172,6 +176,7 @@ impl CourseResponse { creator: course.get_creator().key().to_string(), title: course.get_title().as_str().to_string(), 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()), } } diff --git a/tests/integration.rs b/tests/integration.rs index e658b6f..27fb5ff 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -2132,6 +2132,71 @@ async fn course_input_validation() { ); } +/// A course is `course` by default, may be born a `study` (etüt), the kind is +/// PATCH-editable, and anything else is a 400. +#[tokio::test] +async fn course_kind_defaults_validates_and_edits() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + + let plain = send( + &app, + "POST", + "/courses", + Some(&ali), + Some(json!({"title":"algebra"})), + ) + .await; + assert_eq!(plain.status, StatusCode::CREATED); + assert_eq!(plain.body["kind"], "course"); + + let etut = send( + &app, + "POST", + "/courses", + Some(&ali), + Some(json!({"title":"evening etut", "kind":"study"})), + ) + .await; + assert_eq!(etut.status, StatusCode::CREATED); + assert_eq!(etut.body["kind"], "study"); + + assert_eq!( + send( + &app, + "POST", + "/courses", + Some(&ali), + Some(json!({"title":"nope", "kind":"etut"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // PATCH flips the kind; omitting it keeps the current one. + let id = id_of(&plain.body); + let flipped = send( + &app, + "PATCH", + &format!("/courses/{id}"), + Some(&ali), + Some(json!({"kind":"study"})), + ) + .await; + assert_eq!(flipped.status, StatusCode::OK); + assert_eq!(flipped.body["kind"], "study"); + let renamed = send( + &app, + "PATCH", + &format!("/courses/{id}"), + Some(&ali), + Some(json!({"title":"geometry"})), + ) + .await; + assert_eq!(renamed.body["kind"], "study", "omitted kind is kept"); +} + #[tokio::test] async fn enrollment_upsert_roster_and_my_courses() { let (app, db) = app_and_db().await;