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
15 register only themselves, an optional `capacity` caps the seats, and the list15 register only themselves, an optional `capacity` caps the seats, and the list
16 closes the moment the event starts. Every event stays visible to everyone —16 closes the moment the event starts. Every event stays visible to everyone —
17 the audience is a roster, not a wall. Marks are course-shaped17 the audience is a roster, not a wall. Marks are course-shaped
18-(Google Classroom style): a teacher creates a course, enrolls students, adds18+(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
19 exams inside it, and grades — enrolling, sitting exams, roll call, and marks are21 exams inside it, and grades — enrolling, sitting exams, roll call, and marks are
20 all student-only, staff never take part; students read a per-course weighted average and22 all student-only, staff never take part; students read a per-course weighted average and
21 an overall average from their mark report — each exam weighted by its **kind**23 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`).
237 `Auth` is the minimum role; `no` means no session required, `student` means any239 `Auth` is the minimum role; `no` means no session required, `student` means any
238 logged-in user.240 logged-in user.
239 241
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+
240 Course data is walled per course. A course, its exams, and its sessions are247 Course data is walled per course. A course, its exams, and its sessions are
241 **visible** only to its enrolled users, its creator, and manager+ — a student248 **visible** only to its enrolled users, its creator, and manager+ — a student
242 sees just the classes they were added to, and the `/courses` / `/exams`249 sees just the classes they were added to, and the `/courses` / `/exams`
@@ -298,7 +305,7 @@ their existing shapes: the student exam-room reads
298 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |305 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
299 | 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 |306 | 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 |
300 | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |307 | 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) |
302 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |309 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
303 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |310 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
304 | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) |311 | 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;
99 99
100 pub const MAX_TERM_NAME_LEN: usize = 100;100 pub const MAX_TERM_NAME_LEN: usize = 100;
101 101
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+
102 /// The only accepted exam modes. `sync`: everyone sits the exam inside one108 /// The only accepted exam modes. `sync`: everyone sits the exam inside one
103 /// fixed window. `async`: each student starts inside the window and gets their109 /// fixed window. `async`: each student starts inside the window and gets their
104 /// own `duration_ms` slice of it. `open`: no window — students sit anytime,110 /// own `duration_ms` slice of it. `open`: no window — students sit anytime,
src/database.rsmodified+3 -0
@@ -107,6 +107,7 @@ const MIGRATION: &str = "
107 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;107 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
108 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;108 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
109 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;109 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
110+ DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
110 DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;111 DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
111 112
112 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;113 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
@@ -210,6 +211,8 @@ const MIGRATION: &str = "
210 const BACKFILL: &str = "211 const BACKFILL: &str = "
211 UPDATE user SET role = 'student' WHERE role = NONE;212 UPDATE user SET role = 'student' WHERE role = NONE;
212 213
214+ UPDATE course SET kind = 'course' WHERE kind = NONE;
215+
213 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};216 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
214 217
215 -- The hand-picked `users` audience retired into `registration` (2026-07-16):218 -- 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};
6 use crate::domain::term::TermId;6 use crate::domain::term::TermId;
7 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
8 use crate::error::{AppError, ValidationError};8 use crate::error::{AppError, ValidationError};
9-use crate::validate::{validate_optional, validate_required};9+use crate::validate::{validate_course_kind, validate_optional, validate_required};
10 10
11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
12 pub struct CourseId(RecordId);12 pub struct CourseId(RecordId);
@@ -60,15 +60,39 @@ impl CourseDescription {
60 }60 }
61 }61 }
62 62
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+
63 /// A course: the unit exams and enrollments hang off. Marks are computed per85 /// A course: the unit exams and enrollments hang off. Marks are computed per
64 /// course, each exam weighted by its kind's settings weight. May belong to an86 /// 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).
66 #[derive(Debug, Clone, SurrealValue)]89 #[derive(Debug, Clone, SurrealValue)]
67 pub struct Course {90 pub struct Course {
68 id: CourseId,91 id: CourseId,
69 creator: UserId,92 creator: UserId,
70 title: CourseTitle,93 title: CourseTitle,
71 description: CourseDescription,94 description: CourseDescription,
95+ kind: CourseKind,
72 term: Option<TermId>,96 term: Option<TermId>,
73 }97 }
74 98
@@ -89,6 +113,10 @@ impl Course {
89 &self.description113 &self.description
90 }114 }
91 115
116+ pub fn get_kind(&self) -> &CourseKind {
117+ &self.kind
118+ }
119+
92 pub fn get_term(&self) -> Option<&TermId> {120 pub fn get_term(&self) -> Option<&TermId> {
93 self.term.as_ref()121 self.term.as_ref()
94 }122 }
@@ -101,6 +129,7 @@ impl Course {
101 creator: &UserId,129 creator: &UserId,
102 title: CourseTitle,130 title: CourseTitle,
103 description: CourseDescription,131 description: CourseDescription,
132+ kind: CourseKind,
104 term: Option<TermId>,133 term: Option<TermId>,
105 db: &Database,134 db: &Database,
106 ) -> Result<Course, AppError> {135 ) -> Result<Course, AppError> {
@@ -109,6 +138,7 @@ impl Course {
109 creator: creator.clone(),138 creator: creator.clone(),
110 title,139 title,
111 description,140 description,
141+ kind,
112 term,142 term,
113 };143 };
114 let created: Option<Course> = db.create(course.id.record()).content(course).await?;144 let created: Option<Course> = db.create(course.id.record()).content(course).await?;
@@ -171,11 +201,13 @@ impl Course {
171 mut self,201 mut self,
172 title: CourseTitle,202 title: CourseTitle,
173 description: CourseDescription,203 description: CourseDescription,
204+ kind: CourseKind,
174 term: Option<TermId>,205 term: Option<TermId>,
175 db: &Database,206 db: &Database,
176 ) -> Result<Course, AppError> {207 ) -> Result<Course, AppError> {
177 self.title = title;208 self.title = title;
178 self.description = description;209 self.description = description;
210+ self.kind = kind;
179 self.term = term;211 self.term = term;
180 let updated: Option<Course> = db.update(self.id.record()).content(self).await?;212 let updated: Option<Course> = db.update(self.id.record()).content(self).await?;
181 updated.ok_or(AppError::NotFound)213 updated.ok_or(AppError::NotFound)
@@ -221,4 +253,12 @@ mod tests {
221 async fn description_is_optional() {253 async fn description_is_optional() {
222 assert!(CourseDescription::try_new("").is_ok());254 assert!(CourseDescription::try_new("").is_ok());
223 }255 }
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+ }
224 }264 }
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. 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.",
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, 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"),
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 = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),47 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
src/validate.rsmodified+24 -4
@@ -2,10 +2,10 @@
2 //! the value, so an existing newtype is always valid (parse, don't validate).2 //! the value, so an existing newtype is always valid (parse, don't validate).
3 3
4 use crate::constant::{4 use crate::constant::{
5- EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN,5+ COURSE_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK,
6- MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK,6+ MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN,
7- MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS,7+ MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS,
8- UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,8+ MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,
9 };9 };
10 use crate::error::ValidationError;10 use crate::error::ValidationError;
11 11
@@ -197,6 +197,17 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> {
197 Ok(())197 Ok(())
198 }198 }
199 199
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+
200 pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {211 pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {
201 if EXAM_MODES.contains(&value) {212 if EXAM_MODES.contains(&value) {
202 Ok(())213 Ok(())
@@ -374,6 +385,15 @@ mod tests {
374 assert!(validate_phone("55+5123456").is_err()); // + only allowed in front385 assert!(validate_phone("55+5123456").is_err()); // + only allowed in front
375 }386 }
376 387
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+
377 #[tokio::test]397 #[tokio::test]
378 async fn exam_mode_rules() {398 async fn exam_mode_rules() {
379 for mode in ["sync", "async", "open"] {399 for mode in ["sync", "async", "open"] {
src/web/courses.rsmodified+24 -6
@@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter;
9 use utoipa_axum::routes;9 use utoipa_axum::routes;
10 10
11 use crate::database::Database;11 use crate::database::Database;
12-use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle};12+use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
13 use crate::domain::course_session::{CourseSession, SessionTopic};13 use crate::domain::course_session::{CourseSession, SessionTopic};
14 use crate::domain::enrollment::Enrollment;14 use crate::domain::enrollment::Enrollment;
15 use crate::domain::exam::{15 use crate::domain::exam::{
@@ -46,6 +46,10 @@ struct CreateCourse {
46 #[schema(example = "Algebra")]46 #[schema(example = "Algebra")]
47 title: String,47 title: String,
48 description: Option<String>,48 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>,
49 /// The academic term this course belongs to (`GET /terms`). Optional.53 /// The academic term this course belongs to (`GET /terms`). Optional.
50 term_id: Option<String>,54 term_id: Option<String>,
51 }55 }
@@ -54,6 +58,8 @@ struct CreateCourse {
54 struct UpdateCourse {58 struct UpdateCourse {
55 title: Option<String>,59 title: Option<String>,
56 description: Option<String>,60 description: Option<String>,
61+ /// `course` or `study` (etüt). Omit to keep the current kind.
62+ kind: Option<String>,
57 /// Omit to keep the current term, send `null` to unlink, or send a term63 /// Omit to keep the current term, send `null` to unlink, or send a term
58 /// id to (re)assign.64 /// id to (re)assign.
59 #[serde(default, deserialize_with = "set_or_clear")]65 #[serde(default, deserialize_with = "set_or_clear")]
@@ -172,7 +178,9 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
172 178
173 // ---- courses ------------------------------------------------------------179 // ---- courses ------------------------------------------------------------
174 180
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.
176 #[utoipa::path(184 #[utoipa::path(
177 post,185 post,
178 path = "/",186 path = "/",
@@ -181,7 +189,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
181 request_body = CreateCourse,189 request_body = CreateCourse,
182 responses(190 responses(
183 (status = 201, description = "Course created", body = CourseResponse),191 (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),
185 (status = 401, description = "Not authenticated", body = ErrorResponse),193 (status = 401, description = "Not authenticated", body = ErrorResponse),
186 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),194 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
187 ),195 ),
@@ -193,8 +201,12 @@ async fn create_course(
193 ) -> Result<(StatusCode, Json<CourseResponse>), AppError> {201 ) -> Result<(StatusCode, Json<CourseResponse>), AppError> {
194 let title = CourseTitle::try_new(&req.title)?;202 let title = CourseTitle::try_new(&req.title)?;
195 let description = CourseDescription::try_new(&req.description.unwrap_or_default())?;203 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+ };
196 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;208 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?;
198 Ok((StatusCode::CREATED, Json(CourseResponse::new(&course))))210 Ok((StatusCode::CREATED, Json(CourseResponse::new(&course))))
199 }211 }
200 212
@@ -301,7 +313,7 @@ async fn get_course(
301 request_body = UpdateCourse,313 request_body = UpdateCourse,
302 responses(314 responses(
303 (status = 200, description = "Updated course", body = CourseResponse),315 (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),
305 (status = 401, description = "Not authenticated", body = ErrorResponse),317 (status = 401, description = "Not authenticated", body = ErrorResponse),
306 (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),318 (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
307 (status = 404, description = "Not found", body = ErrorResponse),319 (status = 404, description = "Not found", body = ErrorResponse),
@@ -330,13 +342,19 @@ async fn update_course(
330 Some(ref description) => CourseDescription::try_new(description)?,342 Some(ref description) => CourseDescription::try_new(description)?,
331 None => course.get_description().clone(),343 None => course.get_description().clone(),
332 };344 };
345+ let kind = match req.kind {
346+ Some(ref kind) => CourseKind::try_new(kind)?,
347+ None => course.get_kind().clone(),
348+ };
333 let term = match req.term_id {349 let term = match req.term_id {
334 // Explicit `null` clears the link; a value must name a real term.350 // Explicit `null` clears the link; a value must name a real term.
335 Some(update) => resolve_term(update.as_deref(), &st.db).await?,351 Some(update) => resolve_term(update.as_deref(), &st.db).await?,
336 None => course.get_term().cloned(),352 None => course.get_term().cloned(),
337 };353 };
338 354
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?;
340 Ok(Json(CourseResponse::new(&updated)))358 Ok(Json(CourseResponse::new(&updated)))
341 }359 }
342 360
src/web/dto.rsmodified+5 -0
@@ -160,6 +160,10 @@ pub struct CourseResponse {
160 #[schema(example = "Algebra")]160 #[schema(example = "Algebra")]
161 pub title: String,161 pub title: String,
162 pub description: String,162 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,
163 /// The academic term this course belongs to (`GET /terms`); `null` when167 /// The academic term this course belongs to (`GET /terms`); `null` when
164 /// unassigned.168 /// unassigned.
165 pub term: Option<String>,169 pub term: Option<String>,
@@ -172,6 +176,7 @@ impl CourseResponse {
172 creator: course.get_creator().key().to_string(),176 creator: course.get_creator().key().to_string(),
173 title: course.get_title().as_str().to_string(),177 title: course.get_title().as_str().to_string(),
174 description: course.get_description().as_str().to_string(),178 description: course.get_description().as_str().to_string(),
179+ kind: course.get_kind().as_str().to_string(),
175 term: course.get_term().map(|term| term.key().to_string()),180 term: course.get_term().map(|term| term.key().to_string()),
176 }181 }
177 }182 }
tests/integration.rsmodified+65 -0
@@ -2132,6 +2132,71 @@ async fn course_input_validation() {
2132 );2132 );
2133 }2133 }
2134 2134
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+
2135 #[tokio::test]2200 #[tokio::test]
2136 async fn enrollment_upsert_roster_and_my_courses() {2201 async fn enrollment_upsert_roster_and_my_courses() {
2137 let (app, db) = app_and_db().await;2202 let (app, db) = app_and_db().await;