forge
Explore
Log in

Don't you dare go Hollow

The materializer, the holiday calendar and section lists end to end

Browse files at this commit

aa7132ae135f9f88cfcb13ab118da6ed9f3b19e3Ahmet Kaan GümüşParent: 721daa1
  • test
    • the materializer, the holiday calendar and section lists end to end
Show full message
🧪 test(schedule): the materializer, the holiday calendar and section lists end to end

`tests/regress_schedule.rs`: 20 tests over the new surface — holiday CRUD with
its role gates and the overlap window filter, dry-run vs apply vs idempotent
re-apply, the holiday skip, both coded refusals, the range and candidate caps,
`session_time_taken` on a hand-made lesson at a generated instant, and the
per-section course lists (catalogue row, `/courses/me`, the profile block,
reach filtering). The four generated-lesson tests assert the slot's own
weekday, the +180 school zone, the topic fallback chain and the instance's
first assigned teacher.

One stale pin moved in `tests/integration.rs`
(`session_crud_follows_course_management`): it created two lessons of one
section at the same instant, a premise the new UNIQUE (class_course,
starts_at) wall outlaws — the second lesson now gets its own instant and the
assertions about the manager's rights are unchanged. `tests/regress_profile.rs`
and `tests/persistence.rs` needed no change.

README's generated `## Endpoints` table picks up the five `/holidays` routes
and the materialize route.
README.mdmodified+6 -0
@@ -1323,6 +1323,11 @@ window filtering, before paging; negative values are a `400` naming the field.
13231323 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | A prior sitting's drawn-answer bytes. Requires teacher+ and management rights over the exam's instance — the seq-scoped mirror of the grader's latest-sitting drawing read. |
13241324 | GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full mark history at an exam — every sitting's mark, oldest first (the grade-of-record is the latest). Requires teacher+ and management rights over the exam's instance. |
13251325 | GET | `/health` | no | Health probe: the database verdict and the AI bridge, `503` when degraded. |
1326+| GET | `/holidays` | student | List the calendar, newest start first. Any authenticated user — students need the calendar to make sense of their courses. Paged via `?limit=&offset=` (omit `limit` for the full list), optionally windowed by `?from=&to=`; returns a `{items, total, limit, offset}` envelope. |
1327+| POST | `/holidays` | manager | Declare a school-wide holiday. Requires manager+. Past dates are allowed — the calendar is a record, and a school adopting the app mid-year backfills it legitimately. |
1328+| GET | `/holidays/{id}` | student | Fetch a single holiday by id. |
1329+| PATCH | `/holidays/{id}` | manager | Update a holiday. Requires manager+. Omitted fields keep their value; the merged range must stay ordered. A holiday is a *record* of the calendar, so a past range is editable like a future one. |
1330+| DELETE | `/holidays/{id}` | manager | Delete a holiday. Requires manager+. Nothing references a holiday — the materializer only *reads* the calendar — so the delete is unconditional and the lessons already generated on those days stay where they are. |
13261331 | GET | `/homework` | student | List the homework across the caller's instances — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every instance's homework; a teacher sees the homework of instances they run; a student sees only the homework they are assigned (whole-roster ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. |
13271332 | GET | `/homework/report/{user}` | teacher | A student's homework report across the instances their class section carries, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they manage. Returns a `{items, total, limit, offset}` envelope. |
13281333 | GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its instance (its enrolled students, its teachers, its class section's homeroom teacher, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without instance-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. |
@@ -1380,6 +1385,7 @@ window filtering, before paging; negative values are a `400` naming the field.
13801385 | GET | `/instances/{id}/weekly-plan` | student | The section's resolved weekly plan plus whose rows it is. Visible to the same eyes as the instance read: enrolled students, its teachers, its şube's homeroom teacher, and managers/admins. |
13811386 | POST | `/instances/{id}/weekly-plan` | teacher | Add one slot to the section's own week. Requires teacher+ and a right over the instance; the write flips `weekly_plan_inherited` to `false` in the same statement, so from here the section's own rows — not the offering's template — are what every read resolves. Same overlap and cap refusals as the offering side. |
13821387 | DELETE | `/instances/{id}/weekly-plan` | teacher | Reset the section's weekly plan to inherit — delete every slot of its own week and flip `weekly_plan_inherited` back to `true` in one statement, so the offering's template week is what every read resolves again. Idempotent for a section that never overrode. |
1388+| POST | `/instances/{id}/weekly-plan/materialize` | teacher | Expand this section's **resolved** weekly plan into dated lessons over `from`–`to`. Requires teacher+ and a right over the instance (the same door as adding a slot, since this writes lessons). |
13831389 | DELETE | `/instances/{id}/weekly-plan/{slot}` | teacher | Drop one slot of the section's own week. Requires teacher+ and a right over the instance. The flag flip to `false` rides the delete in the same statement — dropping the last own row leaves the section with an authoritative *empty* plan, not a quiet return to the template (`DELETE /{id}/weekly-plan` is the way back to inherit). A slot of another instance, or one already gone, is a 404 that leaves the flag untouched. |
13841390 | GET | `/limits` | no | Every fixed validation bound the API enforces. Unauthenticated: the registration and login forms need the username and password bounds before a session exists, and none of these values are secrets — they are the same rules a 400 would spell out. |
13851391 | GET | `/marks/karne` | student | The current user's report card for one term: every instance of their sections that counts toward the report card, the `ders_saati`-weighted average across them, and the verdict. An archived term serves the snapshot the school froze when it was closed; an open one computes live. |
src/service/course_session.rsmodified+1 -1
@@ -277,7 +277,7 @@ pub async fn materialize(
277277 if candidates > MAX_MATERIALIZE_SESSIONS {
278278 return Err(AppError::Validation(ValidationError::Invalid {
279279 field: "to",
280- reason: "this range would create more than 500 lessons — narrow it".into(),
280+ reason: "this range would create more than 500 lessons — narrow it",
281281 }));
282282 }
283283 let created = if apply {
tests/integration.rsmodified+5 -2
@@ -10820,12 +10820,15 @@ async fn session_crud_follows_course_management() {
1082010820 assert_eq!(res.body["topic"], "limits");
1082110821 assert_eq!(res.body["starts_at"], start);
1082210822 assert!(res.body["ends_at"].is_null());
10823+ // A distinct instant on purpose: `UNIQUE (class_course, starts_at)` makes
10824+ // two lessons of one section unable to start together, so re-using
10825+ // `start` here would measure that wall, not the manager's rights.
1082310826 let res = send(
1082410827 &app,
1082510828 "POST",
1082610829 &format!("/instances/{}/sessions", t.instance),
1082710830 Some(&boss),
10828- Some(body.clone()),
10831+ Some(json!({ "topic": "limits", "starts_at": start + 60_000 })),
1082910832 )
1083010833 .await;
1083110834 assert_eq!(
@@ -10934,7 +10937,7 @@ async fn session_crud_follows_course_management() {
1093410937 .await;
1093510938 assert_eq!(res.status, StatusCode::OK);
1093610939 // owner's, the manager's, and the one taught by `rival` — newest starts_at
10937- // first, so the two `start` lessons precede the earlier `rival` one.
10940+ // first, so the two later lessons precede the earlier `rival` one.
1093810941 assert_eq!(common::items(&res.body).len(), 3);
1093910942 assert_eq!(common::items(&res.body)[2]["starts_at"], now + 120_000);
1094010943 let res = send(&app, "GET", "/courses/nope/sessions", Some(&student), None).await;
tests/regress_schedule.rsadded+976 -0
@@ -0,0 +1,976 @@
1+//! Regressions for the weekly-plan materializer, the holiday calendar, and
2+//! the per-section course lists. Router-level, same shape as the other
3+//! `regress_*` suites: every test mints its own school and drives the real
4+//! router over `tests/common`.
5+//!
6+//! Every instant here is derived from the clock plus the demo school's fixed
7+//! zone offset (`Europe/Istanbul`, +180 minutes): the next Monday is rounded
8+//! forward once per process, so the suite never ages into the past-`from`
9+//! refusal while two calls in one run still name the same day. Each named date
10+//! asserts its own weekday, so a bad derivation fails loudly instead of
11+//! quietly moving the lesson to a Tuesday.
12+
13+mod common;
14+
15+use axum::http::StatusCode;
16+use chrono::{DateTime, Datelike, NaiveDate, Weekday};
17+use common::{
18+ app_and_db, attach_instance, create_class, create_course, ensure_year, enroll, id_of, items,
19+ login, login_as, me_id, send, taught,
20+};
21+use serde_json::{json, Value};
22+
23+// ---- the calendar helpers ----------------------------------------------------
24+
25+/// The demo school's zone offset: `Europe/Istanbul`, +180 minutes.
26+const OFFSET_MIN: i64 = 180;
27+const DAY_MS: i64 = 86_400_000;
28+
29+/// A local-midnight instant for `day` in the school's zone.
30+fn day_start(day: NaiveDate) -> i64 {
31+ day.and_hms_opt(0, 0, 0)
32+ .unwrap()
33+ .and_utc()
34+ .timestamp_millis()
35+ - OFFSET_MIN * 60_000
36+}
37+
38+/// The school-zone day an instant lands on.
39+fn local_day(millis: i64) -> NaiveDate {
40+ DateTime::from_timestamp_millis(millis + OFFSET_MIN * 60_000)
41+ .unwrap()
42+ .date_naive()
43+}
44+
45+/// Minutes an instant sits past its local midnight — `540` is 09:00.
46+fn minute_of_day(millis: i64) -> i64 {
47+ (millis - day_start(local_day(millis))) / 60_000
48+}
49+
50+/// A whole local day, as a materialize request names it.
51+fn day_range(day: NaiveDate) -> (i64, i64) {
52+ (day_start(day), day_start(day) + DAY_MS - 1)
53+}
54+
55+fn date(y: i32, m: u32, d: u32) -> NaiveDate {
56+ NaiveDate::from_ymd_opt(y, m, d).unwrap()
57+}
58+
59+/// The Monday the generation tests materialize onto: the next Monday strictly
60+/// ahead of the clock, so the suite never ages into the past-`from` refusal.
61+/// Cached for the process, so every call in one run names the same day.
62+fn lesson_monday() -> NaiveDate {
63+ static DAY: std::sync::LazyLock<NaiveDate> = std::sync::LazyLock::new(|| {
64+ let today = local_day(hezarfen_backend::domain::timestamp::Timestamp::now().as_millis());
65+ // Days to the next Monday — 7 when today *is* Monday, because today's
66+ // midnight is already behind the clock.
67+ let ahead = (7 - today.weekday().num_days_from_monday() as i64) % 7;
68+ today + chrono::Duration::days(if ahead == 0 { 7 } else { ahead })
69+ });
70+ let day = *DAY;
71+ assert_eq!(day.weekday(), Weekday::Mon);
72+ day
73+}
74+
75+/// A second Monday, one week out.
76+fn later_monday() -> NaiveDate {
77+ let day = lesson_monday() + chrono::Duration::days(7);
78+ assert_eq!(day.weekday(), Weekday::Mon);
79+ day
80+}
81+
82+/// The Wednesday of that same week — the weekday a Monday-only range must not
83+/// touch, and the one a Wednesday slot must generate on.
84+fn some_wednesday() -> NaiveDate {
85+ let day = lesson_monday() + chrono::Duration::days(2);
86+ assert_eq!(day.weekday(), Weekday::Wed);
87+ day
88+}
89+
90+/// A Monday comfortably in the past, for the past-`from` refusal.
91+fn past_monday() -> NaiveDate {
92+ let day = date(2020, 1, 6);
93+ assert_eq!(day.weekday(), Weekday::Mon);
94+ day
95+}
96+
97+// ---- the fixtures ------------------------------------------------------------
98+
99+/// Add one slot to a section's own weekly plan (asserts 201); returns the
100+/// slot id. `topic` rides the request the way the contract's optional field
101+/// does — absent means the domain fallback names the generated lesson.
102+async fn add_slot(
103+ app: &axum::Router,
104+ cookie: &str,
105+ instance: &str,
106+ weekday: i16,
107+ starts_min: i64,
108+ ends_min: i64,
109+ topic: Option<&str>,
110+) -> String {
111+ let mut body = json!({ "weekday": weekday, "starts_at": starts_min, "ends_at": ends_min });
112+ if let Some(topic) = topic {
113+ body["topic"] = json!(topic);
114+ }
115+ let res = send(
116+ app,
117+ "POST",
118+ &format!("/instances/{instance}/weekly-plan"),
119+ Some(cookie),
120+ Some(body),
121+ )
122+ .await;
123+ assert_eq!(res.status, StatusCode::CREATED, "add slot: {}", res.body);
124+ id_of(&res.body)
125+}
126+
127+/// Assign `teacher_id` to run `instance` (asserts 200) — staffing is what the
128+/// materializer's teacher gate reads.
129+async fn assign_teacher(app: &axum::Router, manager: &str, instance: &str, teacher_id: &str) {
130+ let res = send(
131+ app,
132+ "POST",
133+ &format!("/instances/{instance}/teachers"),
134+ Some(manager),
135+ Some(json!({ "user_id": teacher_id })),
136+ )
137+ .await;
138+ assert_eq!(res.status, StatusCode::OK, "assign teacher: {}", res.body);
139+}
140+
141+/// One materialize call. `apply: None` omits the flag, exercising the
142+/// request's default (a dry run).
143+async fn materialize(
144+ app: &axum::Router,
145+ cookie: &str,
146+ instance: &str,
147+ from: i64,
148+ to: i64,
149+ apply: Option<bool>,
150+) -> common::Res {
151+ let mut body = json!({ "from": from, "to": to });
152+ if let Some(apply) = apply {
153+ body["apply"] = json!(apply);
154+ }
155+ send(
156+ app,
157+ "POST",
158+ &format!("/instances/{instance}/weekly-plan/materialize"),
159+ Some(cookie),
160+ Some(body),
161+ )
162+ .await
163+}
164+
165+/// The full sessions page of `instance` — the envelope a dry run must not
166+/// disturb. Compared whole, so any change in any row or count fails.
167+async fn sessions_page(app: &axum::Router, cookie: &str, instance: &str) -> Value {
168+ let res = send(
169+ app,
170+ "GET",
171+ &format!("/instances/{instance}/sessions"),
172+ Some(cookie),
173+ None,
174+ )
175+ .await;
176+ assert_eq!(res.status, StatusCode::OK, "list sessions: {}", res.body);
177+ res.body
178+}
179+
180+/// The one-holiday calendar: `name` spanning `[starts, ends)` as manager.
181+async fn create_holiday(
182+ app: &axum::Router,
183+ manager: &str,
184+ name: &str,
185+ starts: i64,
186+ ends: i64,
187+) -> Value {
188+ let res = send(
189+ app,
190+ "POST",
191+ "/holidays",
192+ Some(manager),
193+ Some(json!({ "name": name, "starts_at": starts, "ends_at": ends, "kind": "resmi" })),
194+ )
195+ .await;
196+ assert_eq!(res.status, StatusCode::CREATED, "create holiday: {}", res.body);
197+ res.body
198+}
199+
200+async fn list_holidays(
201+ app: &axum::Router,
202+ cookie: &str,
203+ from: Option<i64>,
204+ to: Option<i64>,
205+) -> Vec<Value> {
206+ let uri = match (from, to) {
207+ (Some(from), Some(to)) => format!("/holidays?from={from}&to={to}"),
208+ _ => "/holidays".to_string(),
209+ };
210+ let res = send(app, "GET", &uri, Some(cookie), None).await;
211+ assert_eq!(res.status, StatusCode::OK, "{uri}: {}", res.body);
212+ items(&res.body).clone()
213+}
214+
215+/// The materialize tests' shared setup: a taught instance whose own weekly
216+/// plan carries one Monday 09:00–09:40 slot, with `teacher` assigned to run
217+/// it when the test needs generation to pass the staffing gate. Returns the
218+/// academic stack and, when staffed, the assigned teacher's user id.
219+async fn planned_monday(
220+ app: &axum::Router,
221+ db: &hezarfen_backend::database::Database,
222+ manager: &str,
223+ staffed: bool,
224+) -> (common::Taught, Option<String>) {
225+ let t = taught(app, manager, "Matematik").await;
226+ add_slot(app, manager, &t.instance, 1, 540, 580, None).await;
227+ let teacher_id = if staffed {
228+ let teacher = login_as(app, db, "teach", "teacher").await;
229+ let teacher_id = me_id(app, &teacher).await;
230+ assign_teacher(app, manager, &t.instance, &teacher_id).await;
231+ Some(teacher_id)
232+ } else {
233+ None
234+ };
235+ (t, teacher_id)
236+}
237+
238+/// One catalogue course attached to two şubes — 9-A and 12-B — where the
239+/// 12-B section carries its own resolved-title override. This is the shape
240+/// the per-section course lists exist to show.
241+async fn two_sections(
242+ app: &axum::Router,
243+ manager: &str,
244+) -> (String, String, String, String, String) {
245+ let year = ensure_year(app, manager).await;
246+ let course = create_course(app, manager, "Fizik").await;
247+ let class_a = create_class(app, manager, "Fizik 9-A", json!({ "year": year })).await;
248+ let class_b =
249+ create_class(app, manager, "Fizik 12-B", json!({ "year": year, "grade_level": 12 })).await;
250+ let instance_a = attach_instance(app, manager, &class_a, &course).await;
251+ let instance_b = attach_instance(app, manager, &class_b, &course).await;
252+ let res = send(
253+ app,
254+ "PATCH",
255+ &format!("/instances/{instance_b}"),
256+ Some(manager),
257+ Some(json!({ "title": "12-B Fizik" })),
258+ )
259+ .await;
260+ assert_eq!(res.status, StatusCode::OK, "title override: {}", res.body);
261+ (course, class_a, class_b, instance_a, instance_b)
262+}
263+
264+// ---- the holiday calendar ------------------------------------------------------
265+
266+#[tokio::test]
267+async fn a_manager_creates_reads_patches_and_deletes_a_holiday() {
268+ let (app, db) = app_and_db().await;
269+ let manager = login_as(&app, &db, "mgr", "manager").await;
270+ let manager_id = me_id(&app, &manager).await;
271+
272+ let starts = day_start(lesson_monday());
273+ let ends = day_start(later_monday());
274+ let row = create_holiday(&app, &manager, "29 Ekim", starts, ends).await;
275+ assert_eq!(row["name"], "29 Ekim");
276+ assert_eq!(row["kind"], "resmi");
277+ assert_eq!(row["starts_at"], json!(starts));
278+ assert_eq!(row["ends_at"], json!(ends));
279+ assert_eq!(row["creator"]["id"], json!(manager_id), "creator: {}", row);
280+ assert!(
281+ row["created_at"].as_i64().is_some(),
282+ "created_at: {}",
283+ row
284+ );
285+ let id = id_of(&row);
286+
287+ let got = send(&app, "GET", &format!("/holidays/{id}"), Some(&manager), None).await;
288+ assert_eq!(got.status, StatusCode::OK, "{}", got.body);
289+ assert_eq!(got.body["name"], "29 Ekim");
290+
291+ // PATCH touches only the fields it names.
292+ let patched = send(
293+ &app,
294+ "PATCH",
295+ &format!("/holidays/{id}"),
296+ Some(&manager),
297+ Some(json!({ "name": "Cumhuriyet Bayramı" })),
298+ )
299+ .await;
300+ assert_eq!(patched.status, StatusCode::OK, "{}", patched.body);
301+ assert_eq!(patched.body["name"], "Cumhuriyet Bayramı");
302+ assert_eq!(patched.body["kind"], "resmi", "untouched kind: {}", patched.body);
303+ assert_eq!(patched.body["ends_at"], json!(ends), "untouched end: {}", patched.body);
304+
305+ let gone = send(&app, "DELETE", &format!("/holidays/{id}"), Some(&manager), None).await;
306+ assert_eq!(gone.status, StatusCode::NO_CONTENT, "{}", gone.body);
307+
308+ let list = list_holidays(&app, &manager, None, None).await;
309+ assert!(
310+ list.iter().all(|row| row["id"] != json!(id)),
311+ "deleted holiday still listed: {list:?}"
312+ );
313+ let missing = send(&app, "GET", &format!("/holidays/{id}"), Some(&manager), None).await;
314+ assert_eq!(missing.status, StatusCode::NOT_FOUND, "{}", missing.body);
315+}
316+
317+#[tokio::test]
318+async fn a_student_cannot_write_the_calendar_but_may_read_it() {
319+ let (app, db) = app_and_db().await;
320+ let manager = login_as(&app, &db, "mgr", "manager").await;
321+ let student = login(&app, "stu").await;
322+
323+ let starts = day_start(lesson_monday());
324+ let ends = day_start(later_monday());
325+ let row = create_holiday(&app, &manager, "29 Ekim", starts, ends).await;
326+ let id = id_of(&row);
327+
328+ let refused = send(
329+ &app,
330+ "POST",
331+ "/holidays",
332+ Some(&student),
333+ Some(json!({ "name": "x", "starts_at": starts, "ends_at": ends, "kind": "resmi" })),
334+ )
335+ .await;
336+ assert_eq!(refused.status, StatusCode::FORBIDDEN, "{}", refused.body);
337+ let patched = send(
338+ &app,
339+ "PATCH",
340+ &format!("/holidays/{id}"),
341+ Some(&student),
342+ Some(json!({ "name": "y" })),
343+ )
344+ .await;
345+ assert_eq!(patched.status, StatusCode::FORBIDDEN, "{}", patched.body);
346+ let deleted = send(&app, "DELETE", &format!("/holidays/{id}"), Some(&student), None).await;
347+ assert_eq!(deleted.status, StatusCode::FORBIDDEN, "{}", deleted.body);
348+
349+ // Reads are any-role: the calendar is school-wide structure.
350+ let list = list_holidays(&app, &student, None, None).await;
351+ assert_eq!(list.len(), 1, "the student reads the calendar: {list:?}");
352+ let got = send(&app, "GET", &format!("/holidays/{id}"), Some(&student), None).await;
353+ assert_eq!(got.status, StatusCode::OK, "{}", got.body);
354+}
355+
356+#[tokio::test]
357+async fn an_inverted_range_is_refused_on_create_and_patch() {
358+ let (app, db) = app_and_db().await;
359+ let manager = login_as(&app, &db, "mgr", "manager").await;
360+
361+ let starts = day_start(lesson_monday());
362+ let ends = day_start(later_monday());
363+ let refused = send(
364+ &app,
365+ "POST",
366+ "/holidays",
367+ Some(&manager),
368+ Some(json!({ "name": "ters", "starts_at": ends, "ends_at": starts, "kind": "resmi" })),
369+ )
370+ .await;
371+ assert_eq!(refused.status, StatusCode::BAD_REQUEST, "{}", refused.body);
372+ let list = list_holidays(&app, &manager, None, None).await;
373+ assert!(list.is_empty(), "the refused create wrote nothing: {list:?}");
374+
375+ let row = create_holiday(&app, &manager, "29 Ekim", starts, ends).await;
376+ let id = id_of(&row);
377+ for body in [
378+ json!({ "starts_at": ends + 1 }), // starts alone, past the stored end
379+ json!({ "ends_at": starts - 1 }), // end alone, before the stored start
380+ ] {
381+ let patched = send(
382+ &app,
383+ "PATCH",
384+ &format!("/holidays/{id}"),
385+ Some(&manager),
386+ Some(body.clone()),
387+ )
388+ .await;
389+ assert_eq!(
390+ patched.status,
391+ StatusCode::BAD_REQUEST,
392+ "patch {body}: {}",
393+ patched.body
394+ );
395+ }
396+ let intact = send(&app, "GET", &format!("/holidays/{id}"), Some(&manager), None).await;
397+ assert_eq!(intact.body["starts_at"], json!(starts), "{}", intact.body);
398+ assert_eq!(intact.body["ends_at"], json!(ends), "{}", intact.body);
399+}
400+
401+#[tokio::test]
402+async fn the_list_filter_keeps_a_holiday_touching_the_range_at_either_edge() {
403+ let (app, db) = app_and_db().await;
404+ let manager = login_as(&app, &db, "mgr", "manager").await;
405+
406+ // Overlap is `ends_at >= from && starts_at <= to` — both touching edges
407+ // are inside, one step past either is out.
408+ let starts = 1_790_000_000_000;
409+ let ends = starts + 10 * DAY_MS;
410+ let row = create_holiday(&app, &manager, "Bayram", starts, ends).await;
411+ let id = id_of(&row);
412+
413+ for (from, to, expect) in [
414+ (Some(starts), Some(starts + 5 * DAY_MS), true),
415+ (Some(ends), Some(ends + 10 * DAY_MS), true), // touches at ends_at == from
416+ (Some(ends + 1), Some(ends + 10 * DAY_MS), false),
417+ (Some(starts - 10 * DAY_MS), Some(starts), true), // touches at starts_at == to
418+ (Some(starts - 10 * DAY_MS), Some(starts - 1), false),
419+ (None, None, true),
420+ ] {
421+ let list = list_holidays(&app, &manager, from, to).await;
422+ let has = list.iter().any(|row| row["id"] == json!(id));
423+ assert_eq!(has, expect, "from={from:?} to={to:?}: {list:?}");
424+ }
425+}
426+
427+// ---- the materializer: the happy paths -----------------------------------------
428+
429+#[tokio::test]
430+async fn a_dry_run_counts_one_candidate_and_writes_nothing() {
431+ let (app, db) = app_and_db().await;
432+ let manager = login_as(&app, &db, "mgr", "manager").await;
433+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
434+
435+ let before = sessions_page(&app, &manager, &t.instance).await;
436+ let (from, to) = day_range(lesson_monday());
437+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
438+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
439+ assert_eq!(res.body["from"], json!(from), "{}", res.body);
440+ assert_eq!(res.body["to"], json!(to), "{}", res.body);
441+ assert_eq!(res.body["applied"], json!(false), "{}", res.body);
442+ assert_eq!(res.body["slots"], json!(1), "the resolved plan's size: {}", res.body);
443+ assert_eq!(res.body["candidates"], json!(1), "{}", res.body);
444+ assert_eq!(res.body["range_days"], json!(1), "{}", res.body);
445+ assert_eq!(res.body["skipped_existing"], json!(0), "{}", res.body);
446+ assert_eq!(res.body["skipped_holiday"], json!(0), "{}", res.body);
447+ assert_eq!(res.body["created"], json!([]), "{}", res.body);
448+ assert_eq!(res.body["blocked"], json!([]), "{}", res.body);
449+
450+ let after = sessions_page(&app, &manager, &t.instance).await;
451+ assert_eq!(before, after, "a dry run must not touch the session list");
452+ assert_eq!(after["total"], json!(0), "{}", after);
453+}
454+
455+#[tokio::test]
456+async fn an_apply_generates_the_slots_own_lesson_at_the_slots_own_time() {
457+ let (app, db) = app_and_db().await;
458+ let manager = login_as(&app, &db, "mgr", "manager").await;
459+ let teacher = login_as(&app, &db, "teach", "teacher").await;
460+ let teacher_id = me_id(&app, &teacher).await;
461+
462+ let t = taught(&app, &manager, "Matematik").await;
463+ add_slot(&app, &manager, &t.instance, 1, 540, 580, Some("Denklemler")).await;
464+ assign_teacher(&app, &manager, &t.instance, &teacher_id).await;
465+
466+ let (from, to) = day_range(lesson_monday());
467+ let res = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
468+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
469+ assert_eq!(res.body["applied"], json!(true), "{}", res.body);
470+ assert_eq!(res.body["candidates"], json!(1), "{}", res.body);
471+ assert_eq!(res.body["created"].as_array().unwrap().len(), 1, "{}", res.body);
472+
473+ let lesson = &res.body["created"][0];
474+ assert_eq!(lesson["topic"], "Denklemler", "the slot's topic rides: {}", lesson);
475+ assert_eq!(lesson["teacher"]["id"], json!(teacher_id), "teacher: {}", lesson);
476+ assert_eq!(lesson["class_course"], json!(t.instance), "{}", lesson);
477+ assert_eq!(lesson["ends_at"], json!(day_start(lesson_monday()) + 580 * 60_000));
478+ // The lesson lands on that Monday at 09:00 *school time* — minute-of-day
479+ // 540 against the +180 zone, not 09:00 UTC.
480+ let starts = lesson["starts_at"].as_i64().expect("starts_at");
481+ assert_eq!(starts, day_start(lesson_monday()) + 540 * 60_000, "{}", lesson);
482+ assert_eq!(local_day(starts), lesson_monday(), "{}", lesson);
483+ assert_eq!(minute_of_day(starts), 540, "{}", lesson);
484+
485+ let page = sessions_page(&app, &manager, &t.instance).await;
486+ assert_eq!(page["total"], json!(1), "{}", page);
487+ assert_eq!(page["items"][0]["id"], lesson["id"], "listed: {}", page);
488+}
489+
490+#[tokio::test]
491+async fn a_slot_without_a_topic_names_the_lesson_after_the_resolved_title() {
492+ let (app, db) = app_and_db().await;
493+ let manager = login_as(&app, &db, "mgr", "manager").await;
494+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
495+
496+ // The section's own title override is what every generated lesson of it
497+ // is named after when the slot carries no topic of its own.
498+ let patched = send(
499+ &app,
500+ "PATCH",
501+ &format!("/instances/{}", t.instance),
502+ Some(&manager),
503+ Some(json!({ "title": "9-A Matematik" })),
504+ )
505+ .await;
506+ assert_eq!(patched.status, StatusCode::OK, "{}", patched.body);
507+
508+ let (from, to) = day_range(lesson_monday());
509+ let res = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
510+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
511+ let lesson = &res.body["created"][0];
512+ assert_eq!(lesson["topic"], "9-A Matematik", "{}", lesson);
513+ assert_eq!(local_day(lesson["starts_at"].as_i64().unwrap()), lesson_monday());
514+}
515+
516+#[tokio::test]
517+async fn a_second_apply_reports_the_first_lessons_as_skipped() {
518+ let (app, db) = app_and_db().await;
519+ let manager = login_as(&app, &db, "mgr", "manager").await;
520+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
521+
522+ let (from, to) = day_range(lesson_monday());
523+ let first = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
524+ assert_eq!(first.status, StatusCode::OK, "{}", first.body);
525+ assert_eq!(first.body["created"].as_array().unwrap().len(), 1, "{}", first.body);
526+
527+ let second = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
528+ assert_eq!(second.status, StatusCode::OK, "{}", second.body);
529+ assert_eq!(second.body["applied"], json!(true), "{}", second.body);
530+ assert_eq!(second.body["created"], json!([]), "{}", second.body);
531+ assert_eq!(second.body["skipped_existing"], json!(1), "{}", second.body);
532+ // `candidates` counts the rows that would be *inserted*: an already
533+ // scheduled instant and a holiday-blocked day are excluded from it and
534+ // reported in their own `skipped_existing` / `skipped_holiday` fields.
535+ assert_eq!(second.body["candidates"], json!(0), "{}", second.body);
536+
537+ let page = sessions_page(&app, &manager, &t.instance).await;
538+ assert_eq!(page["total"], json!(1), "the re-apply wrote nothing: {}", page);
539+}
540+
541+#[tokio::test]
542+async fn a_holiday_blocks_its_days_and_the_report_names_it() {
543+ let (app, db) = app_and_db().await;
544+ let manager = login_as(&app, &db, "mgr", "manager").await;
545+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
546+
547+ let (from, to) = day_range(lesson_monday());
548+ let row = create_holiday(&app, &manager, "Bayram tatili", from, to).await;
549+ assert_eq!(row["name"], "Bayram tatili");
550+
551+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
552+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
553+ assert_eq!(res.body["candidates"], json!(0), "{}", res.body);
554+ assert_eq!(res.body["skipped_holiday"], json!(1), "{}", res.body);
555+ assert_eq!(res.body["created"], json!([]), "{}", res.body);
556+ let blocked = res.body["blocked"].as_array().expect("blocked");
557+ assert_eq!(blocked.len(), 1, "{}", res.body);
558+ assert_eq!(blocked[0]["date"], json!(lesson_monday().to_string()), "{}", res.body);
559+ assert_eq!(blocked[0]["holiday"], json!("Bayram tatili"), "{}", res.body);
560+
561+ let page = sessions_page(&app, &manager, &t.instance).await;
562+ assert_eq!(page["total"], json!(0), "a blocked day generates nothing: {}", page);
563+}
564+
565+// ---- the materializer: the refusals --------------------------------------------
566+
567+#[tokio::test]
568+async fn an_empty_own_plan_refuses_to_materialize() {
569+ let (app, db) = app_and_db().await;
570+ let manager = login_as(&app, &db, "mgr", "manager").await;
571+ let t = taught(&app, &manager, "Matematik").await;
572+
573+ // Adding then dropping one slot leaves the section with an authoritative
574+ // *own* plan that is empty — exactly the state the refusal exists for.
575+ // No teacher is assigned on purpose: the empty-plan refusal must win.
576+ let slot = add_slot(&app, &manager, &t.instance, 1, 540, 580, None).await;
577+ let dropped = send(
578+ &app,
579+ "DELETE",
580+ &format!("/instances/{}/weekly-plan/{slot}", t.instance),
581+ Some(&manager),
582+ None,
583+ )
584+ .await;
585+ assert_eq!(dropped.status, StatusCode::NO_CONTENT, "{}", dropped.body);
586+ let plan = send(
587+ &app,
588+ "GET",
589+ &format!("/instances/{}/weekly-plan", t.instance),
590+ Some(&manager),
591+ None,
592+ )
593+ .await;
594+ assert_eq!(plan.status, StatusCode::OK, "{}", plan.body);
595+ assert_eq!(plan.body["weekly_plan_inherited"], json!(false), "{}", plan.body);
596+ assert_eq!(plan.body["weekly_plan"], json!([]), "{}", plan.body);
597+
598+ let (from, to) = day_range(lesson_monday());
599+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
600+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
601+ assert_eq!(res.body["code"], "instance_has_no_weekly_plan", "{}", res.body);
602+}
603+
604+#[tokio::test]
605+async fn an_unstaffed_instance_refuses_to_materialize() {
606+ let (app, db) = app_and_db().await;
607+ let manager = login_as(&app, &db, "mgr", "manager").await;
608+ let t = taught(&app, &manager, "Matematik").await;
609+
610+ // Attaching seeds no teacher rows, so the plan is real (the section's own
611+ // slot) while the staffing gate has nobody to hand the lessons to.
612+ add_slot(&app, &manager, &t.instance, 1, 540, 580, None).await;
613+ let plan = send(
614+ &app,
615+ "GET",
616+ &format!("/instances/{}/weekly-plan", t.instance),
617+ Some(&manager),
618+ None,
619+ )
620+ .await;
621+ assert_eq!(plan.body["weekly_plan"].as_array().unwrap().len(), 1, "{}", plan.body);
622+
623+ let (from, to) = day_range(lesson_monday());
624+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
625+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
626+ assert_eq!(res.body["code"], "instance_has_no_teacher", "{}", res.body);
627+}
628+
629+#[tokio::test]
630+async fn materialize_rejects_a_bad_range_before_anything_runs() {
631+ let (app, db) = app_and_db().await;
632+ let manager = login_as(&app, &db, "mgr", "manager").await;
633+ // Staffed on purpose: the empty-plan and teacher gates run *before* the
634+ // range cap, so a bare instance would answer 409 and the 400 this test is
635+ // about would never fire.
636+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
637+
638+ // More than a year of days.
639+ let from = day_start(lesson_monday());
640+ let res = materialize(&app, &manager, &t.instance, from, from + 367 * DAY_MS, None).await;
641+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
642+
643+ // `from` in the past — the same rule a hand-created lesson answers to.
644+ let res = materialize(
645+ &app,
646+ &manager,
647+ &t.instance,
648+ day_start(past_monday()),
649+ day_start(later_monday()),
650+ None,
651+ )
652+ .await;
653+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
654+
655+ // A zero-width window (`from == to`) is *not* inverted: it names exactly
656+ // one school day, the same way `POST /holidays` and every other dated
657+ // route here treat `ends_at == starts_at` as a valid single instant
658+ // (`check_time_range` refuses only `ends < starts`). Assert the boundary
659+ // itself rather than guessing it.
660+ let res = materialize(&app, &manager, &t.instance, from, from, None).await;
661+ assert_eq!(res.status, StatusCode::OK, "one-instant range: {}", res.body);
662+ assert_eq!(res.body["range_days"], json!(1), "{}", res.body);
663+
664+ // An inverted window — `from` after `to` — is the 400 the range check
665+ // exists for.
666+ let res = materialize(
667+ &app,
668+ &manager,
669+ &t.instance,
670+ day_start(some_wednesday()),
671+ day_start(lesson_monday()),
672+ None,
673+ )
674+ .await;
675+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
676+
677+ let page = sessions_page(&app, &manager, &t.instance).await;
678+ assert_eq!(page["total"], json!(0), "nothing was written: {}", page);
679+}
680+
681+#[tokio::test]
682+async fn an_archived_year_refuses_to_materialize() {
683+ let (app, db) = app_and_db().await;
684+ let manager = login_as(&app, &db, "mgr", "manager").await;
685+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
686+
687+ let archived = send(
688+ &app,
689+ "POST",
690+ &format!("/academic-years/{}/archive", t.year),
691+ Some(&manager),
692+ None,
693+ )
694+ .await;
695+ assert!(
696+ archived.status.is_success(),
697+ "archive: {}",
698+ archived.body
699+ );
700+
701+ let (from, to) = day_range(lesson_monday());
702+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
703+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
704+ assert_eq!(res.body["code"], "academic_year_archived", "{}", res.body);
705+}
706+
707+// ---- the materializer: the uniqueness wall --------------------------------------
708+
709+#[tokio::test]
710+async fn a_hand_created_session_on_a_generated_slot_is_a_coded_conflict() {
711+ let (app, db) = app_and_db().await;
712+ let manager = login_as(&app, &db, "mgr", "manager").await;
713+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
714+
715+ let (from, to) = day_range(lesson_monday());
716+ let res = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
717+ assert_eq!(res.body["created"].as_array().unwrap().len(), 1, "{}", res.body);
718+ let starts = res.body["created"][0]["starts_at"].as_i64().unwrap();
719+
720+ // The unique index on (class_course, starts_at) comes back as the coded
721+ // 409, never a raw 500.
722+ let clash = send(
723+ &app,
724+ "POST",
725+ &format!("/instances/{}/sessions", t.instance),
726+ Some(&manager),
727+ Some(json!({ "starts_at": starts })),
728+ )
729+ .await;
730+ assert_eq!(clash.status, StatusCode::CONFLICT, "{}", clash.body);
731+ assert_eq!(clash.body["code"], "session_time_taken", "{}", clash.body);
732+
733+ // A different instant is not caught by the same wall.
734+ let ok = send(
735+ &app,
736+ "POST",
737+ &format!("/instances/{}/sessions", t.instance),
738+ Some(&manager),
739+ Some(json!({ "starts_at": starts + 60_000 })),
740+ )
741+ .await;
742+ assert_eq!(ok.status, StatusCode::CREATED, "{}", ok.body);
743+ let page = sessions_page(&app, &manager, &t.instance).await;
744+ assert_eq!(page["total"], json!(2), "{}", page);
745+}
746+
747+// ---- the materializer: shape of the generated set --------------------------------
748+
749+#[tokio::test]
750+async fn a_multi_candidate_dry_run_still_writes_nothing() {
751+ let (app, db) = app_and_db().await;
752+ let manager = login_as(&app, &db, "mgr", "manager").await;
753+ let (t, _) = planned_monday(&app, &db, &manager, true).await;
754+ add_slot(&app, &manager, &t.instance, 1, 600, 640, None).await;
755+
756+ let before = sessions_page(&app, &manager, &t.instance).await;
757+ let (from, to) = day_range(lesson_monday());
758+ let res = materialize(&app, &manager, &t.instance, from, to, None).await;
759+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
760+ assert_eq!(res.body["applied"], json!(false), "{}", res.body);
761+ assert_eq!(res.body["slots"], json!(2), "two Monday slots: {}", res.body);
762+ assert_eq!(res.body["candidates"], json!(2), "{}", res.body);
763+ assert_eq!(res.body["created"], json!([]), "{}", res.body);
764+
765+ let after = sessions_page(&app, &manager, &t.instance).await;
766+ assert_eq!(before, after, "a dry run with real candidates wrote nothing");
767+ assert_eq!(after["total"], json!(0), "{}", after);
768+}
769+
770+#[tokio::test]
771+async fn a_range_generates_only_on_the_slots_own_weekday() {
772+ let (app, db) = app_and_db().await;
773+ let manager = login_as(&app, &db, "mgr", "manager").await;
774+ let teacher = login_as(&app, &db, "teach", "teacher").await;
775+ let teacher_id = me_id(&app, &teacher).await;
776+
777+ let t = taught(&app, &manager, "Matematik").await;
778+ add_slot(&app, &manager, &t.instance, 3, 540, 580, None).await; // Wednesday
779+ assign_teacher(&app, &manager, &t.instance, &teacher_id).await;
780+
781+ // The range names only the Monday: no slot matches, and — the point —
782+ // no holiday was skipped either. The report must say *why* nothing came
783+ // out, not merely that nothing did.
784+ let (from, to) = day_range(lesson_monday());
785+ let res = materialize(&app, &manager, &t.instance, from, to, Some(true)).await;
786+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
787+ assert_eq!(res.body["applied"], json!(true), "{}", res.body);
788+ assert_eq!(res.body["candidates"], json!(0), "{}", res.body);
789+ assert_eq!(res.body["skipped_holiday"], json!(0), "{}", res.body);
790+ assert_eq!(res.body["created"], json!([]), "{}", res.body);
791+ assert_eq!(res.body["blocked"], json!([]), "{}", res.body);
792+
793+ let page = sessions_page(&app, &manager, &t.instance).await;
794+ assert_eq!(page["total"], json!(0), "{}", page);
795+
796+ // The mirror image, so the zero above is the weekday match and nothing
797+ // else: the same slot over the range that *does* name its weekday
798+ // generates exactly that day's lesson.
799+ let (wed_from, wed_to) = day_range(some_wednesday());
800+ let res = materialize(&app, &manager, &t.instance, wed_from, wed_to, Some(true)).await;
801+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
802+ assert_eq!(res.body["candidates"], json!(1), "{}", res.body);
803+ let lesson = &res.body["created"][0];
804+ let starts = lesson["starts_at"].as_i64().expect("starts_at");
805+ assert_eq!(local_day(starts), some_wednesday(), "{}", lesson);
806+ assert_eq!(minute_of_day(starts), 540, "{}", lesson);
807+
808+ let page = sessions_page(&app, &manager, &t.instance).await;
809+ assert_eq!(page["total"], json!(1), "{}", page);
810+}
811+
812+// ---- the per-section course lists ------------------------------------------------
813+
814+#[tokio::test]
815+async fn the_catalogue_page_lists_a_courses_sections_with_their_resolved_titles() {
816+ let (app, db) = app_and_db().await;
817+ let manager = login_as(&app, &db, "mgr", "manager").await;
818+ let (course, class_a, class_b, instance_a, instance_b) = two_sections(&app, &manager).await;
819+
820+ let res = send(&app, "GET", "/courses", Some(&manager), None).await;
821+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
822+ let row = items(&res.body)
823+ .iter()
824+ .find(|row| row["id"] == json!(course))
825+ .expect("the course is listed");
826+ assert_eq!(row["class_course_count"], json!(2), "{}", row);
827+
828+ let sections = row["sections"].as_array().expect("sections").clone();
829+ assert_eq!(sections.len(), 2, "{}", row);
830+ let mut titles: Vec<&str> = sections.iter().map(|s| s["title"].as_str().unwrap()).collect();
831+ titles.sort();
832+ titles.dedup();
833+ assert_eq!(
834+ titles,
835+ vec!["12-B Fizik", "Fizik"],
836+ "one section inherited, one overrode: {}",
837+ row
838+ );
839+
840+ for (class, instance, grade, title, class_name) in [
841+ (&class_a, &instance_a, 9, "Fizik", "Fizik 9-A"),
842+ (&class_b, &instance_b, 12, "12-B Fizik", "Fizik 12-B"),
843+ ] {
844+ let section = sections
845+ .iter()
846+ .find(|s| s["class"] == json!(class))
847+ .unwrap_or_else(|| panic!("no section for {class}: {row}"));
848+ assert_eq!(section["id"], json!(instance), "{}", section);
849+ assert_eq!(section["course"], json!(course), "{}", section);
850+ assert_eq!(section["class_name"], json!(class_name), "{}", section);
851+ assert_eq!(section["grade_level"], json!(grade), "{}", section);
852+ assert_eq!(section["title"], json!(title), "{}", section);
853+ assert_eq!(section["enrollment_count"], json!(0), "{}", section);
854+ assert_eq!(section["teachers"], json!([]), "attach seeds no teachers: {}", section);
855+ }
856+}
857+
858+#[tokio::test]
859+async fn a_student_sees_only_the_sections_of_the_courses_they_reach() {
860+ let (app, db) = app_and_db().await;
861+ let manager = login_as(&app, &db, "mgr", "manager").await;
862+ let (course, class_a, _, instance_a, _) = two_sections(&app, &manager).await;
863+
864+ let student = login(&app, "stu").await;
865+ let student_id = me_id(&app, &student).await;
866+ enroll(&app, &manager, &instance_a, &student_id).await;
867+
868+ let res = send(&app, "GET", "/courses", Some(&student), None).await;
869+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
870+ let row = items(&res.body)
871+ .iter()
872+ .find(|row| row["id"] == json!(course))
873+ .expect("the student's course is listed");
874+ let sections = row["sections"].as_array().expect("sections").clone();
875+ assert_eq!(sections.len(), 1, "only the enrolled section: {}", row);
876+ assert_eq!(sections[0]["id"], json!(instance_a), "{}", row);
877+ assert_eq!(sections[0]["class"], json!(class_a), "{}", row);
878+}
879+
880+#[tokio::test]
881+async fn courses_me_lists_one_row_per_section_with_the_resolved_title() {
882+ let (app, db) = app_and_db().await;
883+ let manager = login_as(&app, &db, "mgr", "manager").await;
884+ let (course, class_a, _, instance_a, instance_b) = two_sections(&app, &manager).await;
885+
886+ // One student standing in *both* sections of the same ders: two rows,
887+ // each resolved, not one catalogue row.
888+ let other = login(&app, "stu2").await;
889+ let other_id = me_id(&app, &other).await;
890+ enroll(&app, &manager, &instance_a, &other_id).await;
891+ enroll(&app, &manager, &instance_b, &other_id).await;
892+
893+ // The 9-A section gets its own title too, so both rows can be told apart
894+ // from the catalogue title they inherit from.
895+ let patched = send(
896+ &app,
897+ "PATCH",
898+ &format!("/instances/{instance_a}"),
899+ Some(&manager),
900+ Some(json!({ "title": "9-A Fizik" })),
901+ )
902+ .await;
903+ assert_eq!(patched.status, StatusCode::OK, "{}", patched.body);
904+
905+ let res = send(&app, "GET", "/courses/me", Some(&other), None).await;
906+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
907+ let rows = items(&res.body).clone();
908+ assert_eq!(rows.len(), 2, "one row per section: {}", res.body);
909+
910+ let section = rows
911+ .iter()
912+ .find(|row| row["id"] == json!(instance_a))
913+ .unwrap_or_else(|| panic!("no row for {instance_a}: {}", res.body));
914+ assert_eq!(section["course"], json!(course), "{}", section);
915+ assert_eq!(section["class"], json!(class_a), "{}", section);
916+ assert_eq!(section["class_name"], json!("Fizik 9-A"), "{}", section);
917+ assert_eq!(section["title"], json!("9-A Fizik"), "resolved, not catalogue: {}", section);
918+ assert_eq!(section["grade_level"], json!(9), "{}", section);
919+ // The hours are the section's *resolved* number, not merely an integer:
920+ // read the section's own `GET /instances/{id}` and compare the two.
921+ let own = send(
922+ &app,
923+ "GET",
924+ &format!("/instances/{instance_a}"),
925+ Some(&manager),
926+ None,
927+ )
928+ .await;
929+ assert_eq!(own.status, StatusCode::OK, "{}", own.body);
930+ assert_eq!(
931+ section["ders_saati"], own.body["ders_saati"],
932+ "resolved hours: {}",
933+ section
934+ );
935+ assert_eq!(section["enrollment_count"], json!(1), "{}", section);
936+
937+ let other_row = rows
938+ .iter()
939+ .find(|row| row["id"] == json!(instance_b))
940+ .unwrap_or_else(|| panic!("no row for {instance_b}: {}", res.body));
941+ assert_eq!(other_row["title"], json!("12-B Fizik"), "{}", other_row);
942+ assert_eq!(other_row["grade_level"], json!(12), "{}", other_row);
943+}
944+
945+#[tokio::test]
946+async fn the_profile_block_lists_sections_with_their_class_and_grade() {
947+ let (app, db) = app_and_db().await;
948+ let manager = login_as(&app, &db, "mgr", "manager").await;
949+ let (course, class_a, _, instance_a, _) = two_sections(&app, &manager).await;
950+
951+ let student = login(&app, "stu").await;
952+ let student_id = me_id(&app, &student).await;
953+ enroll(&app, &manager, &instance_a, &student_id).await;
954+
955+ // `GET /users/{id}/profile` is the surface that carries the course block;
956+ // the bare `/users/{id}` answers a `UserResponse` with no `courses` key.
957+ let res = send(
958+ &app,
959+ "GET",
960+ &format!("/users/{student_id}/profile"),
961+ Some(&manager),
962+ None,
963+ )
964+ .await;
965+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
966+ let rows = res.body["courses"].as_array().expect("profile courses").clone();
967+ assert_eq!(rows.len(), 1, "one section, one row: {}", res.body);
968+ let row = &rows[0];
969+ assert_eq!(row["id"], json!(instance_a), "the section is the row: {}", row);
970+ assert_eq!(row["course"], json!(course), "{}", row);
971+ assert_eq!(row["class"], json!(class_a), "{}", row);
972+ assert_eq!(row["class_name"], json!("Fizik 9-A"), "{}", row);
973+ assert_eq!(row["grade_level"], json!(9), "{}", row);
974+ assert_eq!(row["title"], json!("Fizik"), "resolved title (inherited here): {}", row);
975+ assert_eq!(row["kind"], json!("course"), "{}", row);
976+}