diff --git a/.sqlx/query-b6c48120a6799eec2c06f2c35332af7f0abaaba4dd55a284c89ab1351113220e.json b/.sqlx/query-b6c48120a6799eec2c06f2c35332af7f0abaaba4dd55a284c89ab1351113220e.json new file mode 100644 index 0000000..f6901ee --- /dev/null +++ b/.sqlx/query-b6c48120a6799eec2c06f2c35332af7f0abaaba4dd55a284c89ab1351113220e.json @@ -0,0 +1,191 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.offering AS \"offering: CourseOfferingId\",\n cc.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n cc.title AS \"title?: CourseTitle\",\n cc.description AS \"description?: CourseDescription\",\n cc.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n cc.counts_toward_karne,\n cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,\n cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n JOIN class_course_teacher t ON t.class_course = cc.id\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE t.teacher = $1\n ORDER BY cc.attached_at DESC, cc.id DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "offering: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "offering" + } + } + }, + { + "ordinal": 4, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 5, + "name": "source?: ClassBlueprintId", + "type_info": "Int2", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade_level" + } + } + }, + { + "ordinal": 6, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course", + "name": "title" + } + } + }, + { + "ordinal": 7, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course", + "name": "description" + } + } + }, + { + "ordinal": 8, + "name": "ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 9, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 10, + "name": "subjects_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "subjects_inherited" + } + } + }, + { + "ordinal": 11, + "name": "exam_weights_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "exam_weights_inherited" + } + } + }, + { + "ordinal": 12, + "name": "weekly_plan_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "weekly_plan_inherited" + } + } + }, + { + "ordinal": 13, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 14, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true, + null, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "b6c48120a6799eec2c06f2c35332af7f0abaaba4dd55a284c89ab1351113220e" +} diff --git a/src/db/class_course.rs b/src/db/class_course.rs index a0ba7b6..8f1a2f6 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -181,6 +181,41 @@ pub async fn list_for_course_ids( Ok(rows) } +/// Every instance `teacher` is assigned to (one query, unpaged) — the batched +/// replacement for [`list_for_teacher`]-then-[`list_for_course`]-per-course: +/// a reach read walks the assignment junction directly, so a teacher's +/// catalogue page costs one query, not one per taught course. A teacher +/// assigned to two sections of one course gets both rows; an id that names no +/// assignment is simply absent. +pub async fn list_for_teacher_ids( + db: &Database, + teacher: &UserId, +) -> Result, AppError> { + let rows = sqlx::query_as!( + ClassCourse, + r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", + cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId", + cc.attached_by AS "attached_by: UserId", + b.grade_level AS "source?: ClassBlueprintId", + cc.title AS "title?: CourseTitle", + cc.description AS "description?: CourseDescription", + cc.ders_saati::bigint AS "ders_saati?: DersSaati", + cc.counts_toward_karne, + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, + cc.enrollment_count, + cc.attached_at AS "attached_at: Timestamp" + FROM class_course cc + JOIN class_course_teacher t ON t.class_course = cc.id + LEFT JOIN class_blueprint b ON b.id = cc.source + WHERE t.teacher = $1 + ORDER BY cc.attached_at DESC, cc.id DESC"#, + teacher.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows) +} + /// Load every instance behind `ids` (one query) — the join half of the reads /// that already hold instance ids (a marks report's per-instance blocks). pub async fn list_by_ids( diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 62eb827..044f8f9 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -203,7 +203,7 @@ pub async fn update( starts_at: Option, ends_at: Option>, ) -> Result { - FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid()) + let updated = FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid()) .set( "teacher", teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())), @@ -216,7 +216,19 @@ pub async fn update( ) .ordered("starts_at", "ends_at", range_error()) .run::(db) - .await + .await; + match updated { + Ok(updated) => Ok(updated), + // `23505` — the section's own `UNIQUE (class_course, starts_at)`: the + // PATCH moved this lesson onto an instant the section already holds + // (a hand-created one, or one a concurrent materialize just minted). + // The same coded refusal `create` answers with, never a raw 500. + Err(AppError::Db(err)) if unique_violation(&err).is_some() => Err(AppError::ConflictCoded { + code: "session_time_taken", + message: "this section already has a lesson starting then".into(), + }), + Err(err) => Err(err), + } } /// Delete the session and cascade-remove its roll-call rows, in one diff --git a/src/domain/calendar.rs b/src/domain/calendar.rs index c085233..f77b8e1 100644 --- a/src/domain/calendar.rs +++ b/src/domain/calendar.rs @@ -24,6 +24,12 @@ pub fn zone_offset_minutes(timezone: &str) -> i32 { } } +/// The largest shift [`zoned_day`] can ever apply: the biggest offset any +/// entry of [`crate::constant::TIMEZONES`] produces. A caller that must not +/// panic (the materialize route's raw `i64` instants) uses it for a checked +/// pre-flight that mirrors the unchecked arithmetic below. +pub const MAX_ZONE_OFFSET_MINUTES: i32 = 3 * 60; + /// The calendar day an instant falls on, in the school's zone. pub fn zoned_day(millis: i64, offset_minutes: i32) -> chrono::NaiveDate { let shifted = millis + i64::from(offset_minutes) * 60_000; diff --git a/src/service/instance.rs b/src/service/instance.rs index 53f866f..3f5fde3 100644 --- a/src/service/instance.rs +++ b/src/service/instance.rs @@ -91,24 +91,23 @@ pub async fn visible_instances( let manages = homeroom_keys.contains(&instance.get_class().key()); rows.push((instance, manages)); } - // The instances the caller teaches: read through the catalog courses they - // are assigned in (the junction has no teacher-keyed read of its own) and - // kept only where the assignment actually names them. + // The instances the caller teaches: one statement over the assignment + // junction (`class_course` join `class_course_teacher` filtered by the + // teacher), not a catalog read plus one query per taught course plus one + // gate call per instance. `manages` keeps today's meaning — an assigned + // teacher may run the section (D10's teacher arm; the manager+ arm is + // unreachable here, a manager's `visible` is served by the class arm + // above or read manager-side) — and a row the class arm already carried + // (homeroom ∩ assigned) is dropped, the union is a set. if user.get_role().at_least(Role::Teacher) { - for course in super::course::list_for_teacher(db, user.get_id()).await? { - let (taught, _) = - crate::db::class_course::list_for_course(db, course.get_id(), None, 0).await?; - for instance in taught { - if rows - .iter() - .any(|(row, _)| row.get_id() == instance.get_id()) - { - continue; - } - if can_manage_instance(db, instance.get_id(), user).await? { - rows.push((instance, true)); - } + for instance in crate::db::class_course::list_for_teacher_ids(db, user.get_id()).await? { + if rows + .iter() + .any(|(row, _)| row.get_id() == instance.get_id()) + { + continue; } + rows.push((instance, true)); } } Ok(rows) diff --git a/src/web/users.rs b/src/web/users.rs index feaa197..06b3590 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1020,6 +1020,16 @@ struct ProfileClassRef { /// carry their own resolved titles and hours, and the profile lists both. `id` /// is the instance id (`GET /instances/{id}`); `kind` is the catalog row's, /// which is the same for every section of one course. +/// +/// The class identity rides the profile's **class gate**, not the course one: +/// `class`, `class_name` and `grade_level` name the section's şube, and a +/// class name and grade are exactly what `GET /classes/user/{id}` withholds +/// from a viewer below the [`crate::service::parent_link::ensure_can_observe`] +/// bar — so this block withholds them from exactly the same viewers (they +/// read `null`), the same all-or-nothing rule the `classes` block answers to. +/// A viewer who passes — self, teacher+, a linked parent — reads all three. +/// `id`, `course`, `title` and `kind` stay populated for everyone the course +/// gate lets through: the block's purpose is the section, not the class. #[derive(Serialize, ToSchema)] struct ProfileCourseRef { /// The instance id (`GET /instances/{id}`). @@ -1028,19 +1038,22 @@ struct ProfileCourseRef { /// The catalog course this section teaches (`GET /courses/{id}`). #[schema(example = "019732e3-7b00-7000-8000-00000000beef")] course: String, - /// The class this section belongs to (`GET /classes/{id}`). + /// The class this section belongs to (`GET /classes/{id}`) — `null` for a + /// viewer below the class-observation bar. #[schema(example = "019732e3-7b00-7000-8000-00000000cafe")] - class: String, - /// The class's own name, e.g. `9-A`. + class: Option, + /// The class's own name, e.g. `9-A` — `null` for a viewer below the + /// class-observation bar. #[schema(example = "9-A")] - class_name: String, + class_name: Option, /// The **resolved** display title of this section: its own override, else /// its offering's, else the catalog course's. #[schema(example = "Matematik")] title: String, - /// The class's rung on the grade ladder (`0` = anaokulu). + /// The class's rung on the grade ladder (`0` = anaokulu) — `null` for a + /// viewer below the class-observation bar. #[schema(example = 9)] - grade_level: i16, + grade_level: Option, /// `course`, `study` (supervised study), or `club`. #[schema(example = "course")] kind: String, @@ -1215,6 +1228,12 @@ async fn profile_of( if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() { members.clear(); } + // The section rows name their class (`class`/`class_name`/`grade_level`), + // so the same all-or-nothing gate rules what that triple may say here: + // one predicate, computed once, feeding both blocks — never a second + // rule the two blocks could disagree about. + let may_see_class = viewer.get_id() == id + || ensure_can_observe(viewer, id, &st.db).await.is_ok(); let class_ids: Vec = members.iter().map(|row| row.get_class().clone()).collect(); let classes = crate::service::class_group::list_by_ids(&st.db, &class_ids).await?; // Both totals are the full counts, not the windowed ones — the blocks are a @@ -1249,10 +1268,10 @@ async fn profile_of( .map(|section| ProfileCourseRef { id: section.id.clone(), course: section.course.clone(), - class: section.class.clone(), - class_name: section.class_name.clone(), + class: may_see_class.then(|| section.class.clone()), + class_name: may_see_class.then(|| section.class_name.clone()), title: section.title.clone(), - grade_level: section.grade_level, + grade_level: may_see_class.then_some(section.grade_level), kind: kinds.get(§ion.course).cloned().unwrap_or_default(), }) .collect(), diff --git a/src/web/weekly_plan.rs b/src/web/weekly_plan.rs index a7467a8..a2d96a0 100644 --- a/src/web/weekly_plan.rs +++ b/src/web/weekly_plan.rs @@ -509,6 +509,25 @@ async fn materialize_weekly_plan( ) -> Result, AppError> { let instance = instance_or_404(&id, &st.db).await?; service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + // The day math shifts each instant by the zone offset before it reads the + // date off it, and `zoned_day` panics when that shifted value leaves + // chrono's representable range — so an absurd magnitude must be refused + // *here*, with checked arithmetic, naming the field. Checked before the + // offset is even loaded: the refusal cannot depend on the school's zone. + for (field, millis) in [("from", req.from), ("to", req.to)] { + if millis + .checked_add(i64::from( + crate::domain::calendar::MAX_ZONE_OFFSET_MINUTES, + ) * 60_000) + .and_then(chrono::DateTime::from_timestamp_millis) + .is_none() + { + return Err(AppError::Validation(crate::error::ValidationError::Invalid { + field, + reason: "is outside the representable calendar range", + })); + } + } let from = Timestamp::from_millis(req.from); let to = Timestamp::from_millis(req.to); check_time_range(Some(from), Some(to))?; @@ -517,9 +536,6 @@ async fn materialize_weekly_plan( // range may legitimately end in the past when `from` does not, which is // how a school backfills a plan it only now entered.) check_not_past("from", Some(from))?; - // The day-bucketing read `attendance` makes: a range's instants name - // *school* days, and each lesson lands at its slot's minute of that local - // day. let school = service::settings::load(&st.db).await?; let offset = zone_offset_minutes(school.get_timezone()); diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 8f150f1..adc1d13 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -565,6 +565,12 @@ const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[ the result door returns the stored text; a browser never sizes a \ transcript against this", ), + ( + "MAX_ZONE_OFFSET_MINUTES", + "the largest shift `calendar::zoned_day` applies — internal arithmetic \ + for a checked pre-flight in the materialize route, not a value a client \ + sizes a request against", + ), ]; #[test] diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index b079f45..2e46476 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -13,8 +13,9 @@ mod common; use axum::Router; use axum::http::StatusCode; use common::{ - app_and_db, create_exam_with, create_homework, create_subject, enroll, id_of, items, login, - login_as, me_id, send, set_role, taught_under, ABSENT_ID, + app_and_db, attach_instance, create_course, create_exam_with, create_homework, create_subject, + create_year, enroll, id_of, items, login, login_as, me_id, send, set_role, taught_under, + ABSENT_ID, }; use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; use hezarfen_backend::database::Database; @@ -919,6 +920,10 @@ struct Section { peer: String, student: String, student_id: String, + /// The şube the student sits in (`9-A`). + class: String, + /// The academic year that şube sits in. + year: String, } async fn section() -> Section { @@ -932,7 +937,8 @@ async fn section() -> Section { let student = login(&app, "kid").await; let student_id = me_id(&app, &student).await; - let class = create_class(&app, &manager, "9-A", 9).await; + let year = create_year(&app, &manager, "2026-2027").await; + let class = create_class(&app, &manager, "9-A", 9, &year).await; add_member(&app, &manager, &class, &student_id).await; link_student(&app, &admin, &parent_id, &student_id).await; @@ -944,16 +950,18 @@ async fn section() -> Section { peer, student, student_id, + class, + year, } } -async fn create_class(app: &Router, manager: &str, name: &str, grade_level: i16) -> String { +async fn create_class(app: &Router, manager: &str, name: &str, grade_level: i16, year: &str) -> String { let res = send( app, "POST", "/classes", Some(manager), - Some(json!({ "name": name, "grade_level": grade_level })), + Some(json!({ "name": name, "grade_level": grade_level, "year": year })), ) .await; assert_eq!( @@ -1075,6 +1083,59 @@ async fn teacher_parent_manager_and_the_owner_still_read_the_class_block() { assert_eq!(mine.body["classes"][0]["grade_level"], 9); } +/// The section rows' class triple answers the same bar the `classes` block +/// does. The leak this closes: the section split gave `ProfileCourseRef` a +/// `class`/`class_name`/`grade_level` of its own, filtered only by catalog +/// readability — so a fellow student reading a classmate's profile was served +/// the classmate's şube, name and grade and all, while the `classes` block in +/// the very same response stayed empty for exactly that viewer. Both sides in +/// one test, so the two blocks cannot drift apart unnoticed. +#[tokio::test] +async fn a_section_rows_class_fields_obey_the_class_block_gate() { + let s = section().await; + // Attach a course to the student's own class so the profile's course + // block carries the section row the gate is about. The fixture's şube + // already sits in `s.year`, so the attach lands. + let course = create_course(&s.app, &s.manager, "Tarih").await; + let _instance = attach_instance(&s.app, &s.manager, &s.class, &course).await; + // The peer shares the *catalog course* — their own şube teaches it too — + // which is the only way a fellow student passes the course gate and + // reaches the section row at all. The class gate then withholds the şube + // identity the row names: same course, different class. + let class_b = create_class(&s.app, &s.manager, "9-B", 9, &s.year).await; + let peer_id = me_id(&s.app, &s.peer).await; + add_member(&s.app, &s.manager, &class_b, &peer_id).await; + attach_instance(&s.app, &s.manager, &class_b, &course).await; + + let peer_seen = profile(&s.app, &s.peer, &s.student_id).await; + assert_eq!(peer_seen.status, StatusCode::OK, "{}", peer_seen.body); + let rows = peer_seen.body["courses"].as_array().expect("courses"); + assert_eq!(rows.len(), 1, "the section row itself is served: {}", peer_seen.body); + let row = &rows[0]; + // The block's purpose stays: the section, resolved title, kind. + assert_eq!(row["course"], json!(course), "{}", row); + assert_eq!(row["title"], json!("Tarih"), "{}", row); + assert_eq!(row["kind"], json!("course"), "{}", row); + // The class identity is withheld — null, not dropped. + assert_eq!(row["class"], json!(null), "{}", row); + assert_eq!(row["class_name"], json!(null), "{}", row); + assert_eq!(row["grade_level"], json!(null), "{}", row); + + // A manager passes the bar and reads the triple. + let boss_seen = profile(&s.app, &s.manager, &s.student_id).await; + assert_eq!(boss_seen.status, StatusCode::OK, "{}", boss_seen.body); + let boss_row = &boss_seen.body["courses"][0]; + assert_eq!(boss_row["class_name"], json!("9-A"), "{}", boss_row); + assert_eq!(boss_row["grade_level"], json!(9), "{}", boss_row); + assert!(boss_row["class"].as_str().is_some(), "{}", boss_row); + + // The owner passes it too, reading their own profile. + let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await; + assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); + assert_eq!(mine.body["courses"][0]["class_name"], json!("9-A"), "{}", mine.body); + assert_eq!(mine.body["courses"][0]["grade_level"], json!(9), "{}", mine.body); +} + /// `stats.classes` is the owner's true total, deliberately *not* the length of /// the gated block — the same call already made for `stats.courses`: it is the /// motivational counter, and a magnitude names no class. diff --git a/tests/regress_schedule.rs b/tests/regress_schedule.rs index 4227013..b2eb0a8 100644 --- a/tests/regress_schedule.rs +++ b/tests/regress_schedule.rs @@ -15,8 +15,8 @@ mod common; use axum::http::StatusCode; use chrono::{DateTime, Datelike, NaiveDate, Weekday}; use common::{ - app_and_db, attach_instance, create_class, create_course, ensure_year, enroll, id_of, items, - login, login_as, me_id, send, taught, + app_and_db, attach_instance, create_class, create_course, create_session, ensure_year, enroll, + id_of, items, login, login_as, me_id, send, taught, }; use serde_json::{json, Value}; @@ -674,6 +674,30 @@ async fn materialize_rejects_a_bad_range_before_anything_runs() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + // An instant the day math cannot represent: shifting by the zone offset + // overflows chrono's range and `zoned_day` panics there. The route must + // refuse with a 400 that names the field — for `i64::MAX` and `i64::MIN` + // alike — before anything runs. + for (field, at) in [("from", i64::MAX), ("to", i64::MAX), ("from", i64::MIN), ("to", i64::MIN)] { + let (from, to) = match field { + "from" => (at, day_start(later_monday())), + _ => (day_start(lesson_monday()), at), + }; + let res = materialize(&app, &manager, &t.instance, from, to, None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{field}={at}: {}", res.body); + let body = res.body.to_string(); + assert!( + body.contains(field), + "the 400 must name `{field}`: {body}" + ); + } + + // A sane range through the same gate still works — the guard refuses + // magnitudes, not the ordinary calendar. + let (from, to) = day_range(lesson_monday()); + let res = materialize(&app, &manager, &t.instance, from, to, None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let page = sessions_page(&app, &manager, &t.instance).await; assert_eq!(page["total"], json!(0), "nothing was written: {}", page); } @@ -744,6 +768,55 @@ async fn a_hand_created_session_on_a_generated_slot_is_a_coded_conflict() { assert_eq!(page["total"], json!(2), "{}", page); } +/// The PATCH door answers the same coded 409, not a 500: moving one lesson's +/// `starts_at` onto an instant the section already holds trips the same +/// `UNIQUE (class_course, starts_at)` the create door maps. A PATCH to a free +/// instant still succeeds. +#[tokio::test] +async fn a_session_moved_onto_an_occupied_instant_is_a_coded_conflict() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mgr", "manager").await; + let (t, _) = planned_monday(&app, &db, &manager, true).await; + + // Two lessons one minute apart. + create_session(&app, &manager, &t.instance, day_start(lesson_monday()) + 540 * 60_000).await; + let second = create_session(&app, &manager, &t.instance, day_start(lesson_monday()) + 601 * 60_000).await; + + // PATCH the second onto the first's instant: the unique wall, through the + // update path, must be the coded 409 — never a raw 500. + let moved = send( + &app, + "PATCH", + &format!("/sessions/{second}"), + Some(&manager), + Some(json!({ "starts_at": day_start(lesson_monday()) + 540 * 60_000 })), + ) + .await; + assert_eq!(moved.status, StatusCode::CONFLICT, "{}", moved.body); + assert_eq!(moved.body["code"], "session_time_taken", "{}", moved.body); + + // The refused PATCH wrote nothing: both lessons still sit where they did. + let page = sessions_page(&app, &manager, &t.instance).await; + assert_eq!(page["total"], json!(2), "{}", page); + + // A PATCH onto a free instant is not caught by the same wall. + let ok = send( + &app, + "PATCH", + &format!("/sessions/{second}"), + Some(&manager), + Some(json!({ "starts_at": day_start(lesson_monday()) + 661 * 60_000 })), + ) + .await; + assert_eq!(ok.status, StatusCode::OK, "{}", ok.body); + assert_eq!( + ok.body["starts_at"], + json!(day_start(lesson_monday()) + 661 * 60_000), + "{}", + ok.body + ); +} + // ---- the materializer: shape of the generated set -------------------------------- #[tokio::test]