forge
Explore
Log in

Don't you dare go Hollow

Add kind course|study (supervised study)

Browse files at this commit

f29537cadbee032c4576fc2af74032c8abb4e89bAhmet Kaan GümüşParent: 31e155a
  • feat
    • add kind course|study (supervised study)
Show full message
✨ feat(courses): add kind course|study (supervised study)

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.mdmodified+9 -2
@@ -15,7 +15,9 @@ by seat: teachers register students (never the other way round), staff
1515 register only themselves, an optional `capacity` caps the seats, and the list
1616 closes the moment the event starts. Every event stays visible to everyone —
1717 the audience is a roster, not a wall. Marks are course-shaped
18-(Google Classroom style): a teacher creates a course, enrolls students, adds
18+(Google Classroom style): a teacher creates a course — kind **`course`** (a
19+regular class) or **`study`** (a supervised study session — *etüt*; same
20+behavior, different label) — enrolls students, adds
1921 exams inside it, and grades — enrolling, sitting exams, roll call, and marks are
2022 all student-only, staff never take part; students read a per-course weighted average and
2123 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`).
237239 `Auth` is the minimum role; `no` means no session required, `student` means any
238240 logged-in user.
239241
242+A course is either a regular class (kind `course`, the default) or an *etüt*
243+(kind `study` — a supervised study session). The two kinds behave identically
244+everywhere — enrollment, exams, sessions, marks — the kind is a label the UI
245+renders differently, settable at creation and editable later.
246+
240247 Course data is walled per course. A course, its exams, and its sessions are
241248 **visible** only to its enrolled users, its creator, and manager+ — a student
242249 sees just the classes they were added to, and the `/courses` / `/exams`
@@ -298,7 +305,7 @@ their existing shapes: the student exam-room reads
298305 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
299306 | 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 |
300307 | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |
301-| POST | `/courses` | teacher | `{title, description?}` (creator manages it) |
308+| POST | `/courses` | teacher | `{title, description?, kind?, term_id?}` — `kind` is `course` (default) or `study` (etüt) (creator manages it) |
302309 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
303310 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
304311 | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) |
src/constant.rsmodified+6 -0
@@ -99,6 +99,12 @@ pub const SETTINGS_UPDATE_RETRIES: usize = 3;
9999
100100 pub const MAX_TERM_NAME_LEN: usize = 100;
101101
102+/// The only accepted course kinds. `course`: a regular class (ders). `study`:
103+/// a supervised study session (etüt). Behaviorally identical — the kind is a
104+/// label for the UI, everything else (enrollment, exams, sessions, marks)
105+/// works the same.
106+pub const COURSE_KINDS: [&str; 2] = ["course", "study"];
107+
102108 /// The only accepted exam modes. `sync`: everyone sits the exam inside one
103109 /// fixed window. `async`: each student starts inside the window and gets their
104110 /// own `duration_ms` slice of it. `open`: no window — students sit anytime,
src/database.rsmodified+3 -0
@@ -107,6 +107,7 @@ const MIGRATION: &str = "
107107 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
108108 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
109109 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
110+ DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
110111 DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
111112
112113 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
@@ -210,6 +211,8 @@ const MIGRATION: &str = "
210211 const BACKFILL: &str = "
211212 UPDATE user SET role = 'student' WHERE role = NONE;
212213
214+ UPDATE course SET kind = 'course' WHERE kind = NONE;
215+
213216 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
214217
215218 -- The hand-picked `users` audience retired into `registration` (2026-07-16):
src/domain/course.rsmodified+42 -2
@@ -6,7 +6,7 @@ use crate::database::{COURSE_TABLE, Database};
66 use crate::domain::term::TermId;
77 use crate::domain::user::UserId;
88 use crate::error::{AppError, ValidationError};
9-use crate::validate::{validate_optional, validate_required};
9+use crate::validate::{validate_course_kind, validate_optional, validate_required};
1010
1111 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
1212 pub struct CourseId(RecordId);
@@ -60,15 +60,39 @@ impl CourseDescription {
6060 }
6161 }
6262
63+/// A validated course kind: `course` (a regular class — ders) or `study` (a
64+/// supervised study session — etüt). Purely a label; both kinds behave
65+/// identically.
66+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
67+pub struct CourseKind(String);
68+
69+impl CourseKind {
70+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
71+ validate_course_kind(value)?;
72+ Ok(Self(value.to_string()))
73+ }
74+
75+ /// The classic kind — what every course is unless said otherwise.
76+ pub fn course() -> Self {
77+ Self("course".to_string())
78+ }
79+
80+ pub fn as_str(&self) -> &str {
81+ &self.0
82+ }
83+}
84+
6385 /// A course: the unit exams and enrollments hang off. Marks are computed per
6486 /// course, each exam weighted by its kind's settings weight. May belong to an
65-/// academic term.
87+/// academic term. Comes in two behaviorally identical kinds: `course` and
88+/// `study` (etüt).
6689 #[derive(Debug, Clone, SurrealValue)]
6790 pub struct Course {
6891 id: CourseId,
6992 creator: UserId,
7093 title: CourseTitle,
7194 description: CourseDescription,
95+ kind: CourseKind,
7296 term: Option<TermId>,
7397 }
7498
@@ -89,6 +113,10 @@ impl Course {
89113 &self.description
90114 }
91115
116+ pub fn get_kind(&self) -> &CourseKind {
117+ &self.kind
118+ }
119+
92120 pub fn get_term(&self) -> Option<&TermId> {
93121 self.term.as_ref()
94122 }
@@ -101,6 +129,7 @@ impl Course {
101129 creator: &UserId,
102130 title: CourseTitle,
103131 description: CourseDescription,
132+ kind: CourseKind,
104133 term: Option<TermId>,
105134 db: &Database,
106135 ) -> Result<Course, AppError> {
@@ -109,6 +138,7 @@ impl Course {
109138 creator: creator.clone(),
110139 title,
111140 description,
141+ kind,
112142 term,
113143 };
114144 let created: Option<Course> = db.create(course.id.record()).content(course).await?;
@@ -171,11 +201,13 @@ impl Course {
171201 mut self,
172202 title: CourseTitle,
173203 description: CourseDescription,
204+ kind: CourseKind,
174205 term: Option<TermId>,
175206 db: &Database,
176207 ) -> Result<Course, AppError> {
177208 self.title = title;
178209 self.description = description;
210+ self.kind = kind;
179211 self.term = term;
180212 let updated: Option<Course> = db.update(self.id.record()).content(self).await?;
181213 updated.ok_or(AppError::NotFound)
@@ -221,4 +253,12 @@ mod tests {
221253 async fn description_is_optional() {
222254 assert!(CourseDescription::try_new("").is_ok());
223255 }
256+
257+ #[tokio::test]
258+ async fn kind_is_course_or_study() {
259+ assert!(CourseKind::try_new("course").is_ok());
260+ assert!(CourseKind::try_new("study").is_ok());
261+ assert!(CourseKind::try_new("etut").is_err());
262+ assert_eq!(CourseKind::course().as_str(), "course");
263+ }
224264 }
src/lib.rsmodified+2 -2
@@ -32,7 +32,7 @@ use crate::state::AppState;
3232 info(
3333 title = "Hezarfen Backend API",
3434 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. 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.",
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. 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.",
3636 ),
3737 modifiers(&SecurityAddon),
3838 tags(
@@ -41,7 +41,7 @@ use crate::state::AppState;
4141 (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)"),
4242 (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`)"),
4343 (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, enrollment (students only), course exams, and course sessions"),
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"),
4545 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
4646 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
4747 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
src/validate.rsmodified+24 -4
@@ -2,10 +2,10 @@
22 //! the value, so an existing newtype is always valid (parse, don't validate).
33
44 use crate::constant::{
5- EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN,
6- MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK,
7- MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS,
8- UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,
5+ COURSE_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK,
6+ MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN,
7+ MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS,
8+ MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,
99 };
1010 use crate::error::ValidationError;
1111
@@ -197,6 +197,17 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> {
197197 Ok(())
198198 }
199199
200+pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> {
201+ if COURSE_KINDS.contains(&value) {
202+ Ok(())
203+ } else {
204+ Err(ValidationError::Invalid {
205+ field: "kind",
206+ reason: "must be one of: course, study",
207+ })
208+ }
209+}
210+
200211 pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {
201212 if EXAM_MODES.contains(&value) {
202213 Ok(())
@@ -374,6 +385,15 @@ mod tests {
374385 assert!(validate_phone("55+5123456").is_err()); // + only allowed in front
375386 }
376387
388+ #[tokio::test]
389+ async fn course_kind_rules() {
390+ for kind in ["course", "study"] {
391+ assert!(validate_course_kind(kind).is_ok());
392+ }
393+ assert!(validate_course_kind("etut").is_err());
394+ assert!(validate_course_kind("").is_err());
395+ }
396+
377397 #[tokio::test]
378398 async fn exam_mode_rules() {
379399 for mode in ["sync", "async", "open"] {
src/web/courses.rsmodified+24 -6
@@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter;
99 use utoipa_axum::routes;
1010
1111 use crate::database::Database;
12-use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle};
12+use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
1313 use crate::domain::course_session::{CourseSession, SessionTopic};
1414 use crate::domain::enrollment::Enrollment;
1515 use crate::domain::exam::{
@@ -46,6 +46,10 @@ struct CreateCourse {
4646 #[schema(example = "Algebra")]
4747 title: String,
4848 description: Option<String>,
49+ /// `course` (a regular class — the default) or `study` (a supervised
50+ /// study session — etüt). Behaviorally identical; a label for the UI.
51+ #[schema(example = "course")]
52+ kind: Option<String>,
4953 /// The academic term this course belongs to (`GET /terms`). Optional.
5054 term_id: Option<String>,
5155 }
@@ -54,6 +58,8 @@ struct CreateCourse {
5458 struct UpdateCourse {
5559 title: Option<String>,
5660 description: Option<String>,
61+ /// `course` or `study` (etüt). Omit to keep the current kind.
62+ kind: Option<String>,
5763 /// Omit to keep the current term, send `null` to unlink, or send a term
5864 /// id to (re)assign.
5965 #[serde(default, deserialize_with = "set_or_clear")]
@@ -172,7 +178,9 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
172178
173179 // ---- courses ------------------------------------------------------------
174180
175-/// Create a course owned by the current user. Requires the `teacher` role or higher.
181+/// Create a course owned by the current user. Requires the `teacher` role or
182+/// higher. `kind` picks the flavor — `course` (a regular class, the default)
183+/// or `study` (a supervised study session — etüt); both behave identically.
176184 #[utoipa::path(
177185 post,
178186 path = "/",
@@ -181,7 +189,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
181189 request_body = CreateCourse,
182190 responses(
183191 (status = 201, description = "Course created", body = CourseResponse),
184- (status = 400, description = "Invalid fields", body = ErrorResponse),
192+ (status = 400, description = "Invalid fields or kind", body = ErrorResponse),
185193 (status = 401, description = "Not authenticated", body = ErrorResponse),
186194 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
187195 ),
@@ -193,8 +201,12 @@ async fn create_course(
193201 ) -> Result<(StatusCode, Json<CourseResponse>), AppError> {
194202 let title = CourseTitle::try_new(&req.title)?;
195203 let description = CourseDescription::try_new(&req.description.unwrap_or_default())?;
204+ let kind = match req.kind {
205+ Some(ref kind) => CourseKind::try_new(kind)?,
206+ None => CourseKind::course(),
207+ };
196208 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
197- let course = Course::create(user.get_id(), title, description, term, &st.db).await?;
209+ let course = Course::create(user.get_id(), title, description, kind, term, &st.db).await?;
198210 Ok((StatusCode::CREATED, Json(CourseResponse::new(&course))))
199211 }
200212
@@ -301,7 +313,7 @@ async fn get_course(
301313 request_body = UpdateCourse,
302314 responses(
303315 (status = 200, description = "Updated course", body = CourseResponse),
304- (status = 400, description = "Invalid fields", body = ErrorResponse),
316+ (status = 400, description = "Invalid fields or kind", body = ErrorResponse),
305317 (status = 401, description = "Not authenticated", body = ErrorResponse),
306318 (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
307319 (status = 404, description = "Not found", body = ErrorResponse),
@@ -330,13 +342,19 @@ async fn update_course(
330342 Some(ref description) => CourseDescription::try_new(description)?,
331343 None => course.get_description().clone(),
332344 };
345+ let kind = match req.kind {
346+ Some(ref kind) => CourseKind::try_new(kind)?,
347+ None => course.get_kind().clone(),
348+ };
333349 let term = match req.term_id {
334350 // Explicit `null` clears the link; a value must name a real term.
335351 Some(update) => resolve_term(update.as_deref(), &st.db).await?,
336352 None => course.get_term().cloned(),
337353 };
338354
339- let updated = course.update(title, description, term, &st.db).await?;
355+ let updated = course
356+ .update(title, description, kind, term, &st.db)
357+ .await?;
340358 Ok(Json(CourseResponse::new(&updated)))
341359 }
342360
src/web/dto.rsmodified+5 -0
@@ -160,6 +160,10 @@ pub struct CourseResponse {
160160 #[schema(example = "Algebra")]
161161 pub title: String,
162162 pub description: String,
163+ /// `course` (a regular class) or `study` (a supervised study session —
164+ /// etüt). Behaviorally identical; a label for the UI.
165+ #[schema(example = "course")]
166+ pub kind: String,
163167 /// The academic term this course belongs to (`GET /terms`); `null` when
164168 /// unassigned.
165169 pub term: Option<String>,
@@ -172,6 +176,7 @@ impl CourseResponse {
172176 creator: course.get_creator().key().to_string(),
173177 title: course.get_title().as_str().to_string(),
174178 description: course.get_description().as_str().to_string(),
179+ kind: course.get_kind().as_str().to_string(),
175180 term: course.get_term().map(|term| term.key().to_string()),
176181 }
177182 }
tests/integration.rsmodified+65 -0
@@ -2132,6 +2132,71 @@ async fn course_input_validation() {
21322132 );
21332133 }
21342134
2135+/// A course is `course` by default, may be born a `study` (etüt), the kind is
2136+/// PATCH-editable, and anything else is a 400.
2137+#[tokio::test]
2138+async fn course_kind_defaults_validates_and_edits() {
2139+ let (app, db) = app_and_db().await;
2140+ let ali = login_as(&app, &db, "ali", "teacher").await;
2141+
2142+ let plain = send(
2143+ &app,
2144+ "POST",
2145+ "/courses",
2146+ Some(&ali),
2147+ Some(json!({"title":"algebra"})),
2148+ )
2149+ .await;
2150+ assert_eq!(plain.status, StatusCode::CREATED);
2151+ assert_eq!(plain.body["kind"], "course");
2152+
2153+ let etut = send(
2154+ &app,
2155+ "POST",
2156+ "/courses",
2157+ Some(&ali),
2158+ Some(json!({"title":"evening etut", "kind":"study"})),
2159+ )
2160+ .await;
2161+ assert_eq!(etut.status, StatusCode::CREATED);
2162+ assert_eq!(etut.body["kind"], "study");
2163+
2164+ assert_eq!(
2165+ send(
2166+ &app,
2167+ "POST",
2168+ "/courses",
2169+ Some(&ali),
2170+ Some(json!({"title":"nope", "kind":"etut"}))
2171+ )
2172+ .await
2173+ .status,
2174+ StatusCode::BAD_REQUEST
2175+ );
2176+
2177+ // PATCH flips the kind; omitting it keeps the current one.
2178+ let id = id_of(&plain.body);
2179+ let flipped = send(
2180+ &app,
2181+ "PATCH",
2182+ &format!("/courses/{id}"),
2183+ Some(&ali),
2184+ Some(json!({"kind":"study"})),
2185+ )
2186+ .await;
2187+ assert_eq!(flipped.status, StatusCode::OK);
2188+ assert_eq!(flipped.body["kind"], "study");
2189+ let renamed = send(
2190+ &app,
2191+ "PATCH",
2192+ &format!("/courses/{id}"),
2193+ Some(&ali),
2194+ Some(json!({"title":"geometry"})),
2195+ )
2196+ .await;
2197+ assert_eq!(renamed.body["kind"], "study", "omitted kind is kept");
2198+}
2199+
21352200 #[tokio::test]
21362201 async fn enrollment_upsert_roster_and_my_courses() {
21372202 let (app, db) = app_and_db().await;