diff --git a/README.md b/README.md index 6b2e87a..72416b5 100644 --- a/README.md +++ b/README.md @@ -595,10 +595,23 @@ own seats by hand. Seats on lists that have already closed (the event started, or its `ends_at`-only deadline passed) are never touched — that roster is history, and re-registering is refused. +A demotion below `teacher` additionally **withdraws the published appointment +calendar** and cancels the live bookings on it. Nothing else could: a slot is +listed only on its own teacher's calendar and deleted only by a teacher+, so +after the demotion no route yields its id, and a booking on it can be decided +only by a teacher+ and cancelled only by its requester — who is refused once +the window opens, leaving the slot's seat held for good. The requester keeps +the booking, `cancelled`, with the ex-teacher on `cancelled_by` and the reason +on `cancel_reason`; its slot is gone, so it renders without a window. A slot +published while the demotion runs claims the publisher's own row, so either +the sweep sees the slot or the publish sees the new role (a `403`), and a +booking racing it collides on the slot row the sweep deletes. + The role write and every sweep it implies — class memberships and their counters, all enrollments and their seats, parent ties on both sides, a demoted parent's still-freeable event seats, whiteboard rosters, course -staffing and homeroom-teacher columns — commit as **one transaction**. It +staffing and homeroom-teacher columns, the appointment calendar and the +bookings on it — commit as **one transaction**. It either all lands or none of it does: a failure answers `500` with the account still holding its old role and every grant of it still standing, and the same `PATCH` retried applies the lot. Signup lists that have already frozen are @@ -803,7 +816,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path | | GET | `/users/{id}` | admin | Get one user | -| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists; demoting the school's **last** admin is refused (`409`) | +| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), a demotion below `teacher` withdraws their appointment slots and cancels the bookings on them, and a demotion to `parent` also frees their seats on still-open event signup lists; demoting the school's **last** admin is refused (`409`) | | PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | @@ -1475,9 +1488,13 @@ POST /appointments/slots **bookable** calendar — slots that have **not started yet**, earliest first. That bound is `starts_at`, the same one booking enforces, so a slot already underway is left out rather than offered for a request that could only answer -`409`; the 60-second publish-time skew grace does not widen it either. A teacher demoted -after publishing leaves **inert** slots: their live role is re-read, so those -slots drop out of the bookable list and booking one is refused with a `409`. +`409`; the 60-second publish-time skew grace does not widen it either. A +demotion below `teacher` **withdraws** that account's calendar outright, in the +role change's own transaction, and cancels the live bookings on it (see +`PATCH /users/{id}/role`): a slot nobody can list and nobody can delete would +otherwise sit there forever, holding a booking nobody can settle. The live-role +re-read stays as the belt for a slot an older build stranded — such a slot +drops out of the bookable list and booking one is refused with a `409`. The list does not say whether a slot is already taken — booking a taken one answers `409`. @@ -1497,8 +1514,9 @@ concurrent bookings can both read as free). The decisions: - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms; the slot's `teacher` is history, not a standing grant, so an owner demoted below - `teacher` decides nothing on it any more — manager+ still can, and the - requester can still cancel. Refused + `teacher` decides nothing on it any more — and nothing is left for anyone + else to decide either, since that demotion cancelled the bookings along with + the slots. Refused (`409`) when the effective window has already started, and refused while a counter-proposal stands: the proposal is the teacher's own, so approving it here would let them confirm a time the requester never accepted. diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index 4c7f174..c3af73d 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -200,6 +200,7 @@ impl MealBooking { for attempt in 0..CAP_WRITE_TRIES { backoff(attempt).await; let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; + check_day_not_past(fresh.get_date())?; check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; let existing: Option = db.select(id.record()).await?; // The seat is already held: same attempt, same price it was taken @@ -723,6 +724,40 @@ fn served_at(date: &MenuDate, serving_minute: Option) -> Option )) } +/// A meal whose **calendar day is over** takes no more seats, whatever the +/// school configured. The booking is what charges (attendance never moves +/// money), so a seat taken on a day already served mints a real ledger line for +/// food nobody can be served — the one thing no route may do. +/// +/// Deliberately **not** part of [`check_cutoff`], and deliberately not +/// configurable: +/// +/// - The cutoff is a *policy* about the serving hour, and it is unenforced by +/// design when the school sets no `meal_cancel_cutoff_minutes` or the slot no +/// `serving_minute` (all three shipped slots carry none) — see the note there +/// for why the canteen must not go offline over an unset hour. This is not a +/// deadline before the meal at all: it is the day itself having passed, which +/// no configuration can make untrue. **Today's menu is untouched by it** — +/// with or without a serving hour, at any time of day. +/// - It binds `book` only. Cancelling stays open on a past day, cutoff bypass +/// or not: a cancel *reverses* a charge, and money already taken has to stay +/// reachable (that is the same reason manager+ bypasses the cutoff in +/// [`cancel_booking`](crate::web::meals)). +fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> { + // An unparsable day is left to `check_cutoff`, which fails it closed + // whenever a cutoff is configured: guessing "past" from text no calendar + // can place would shut the canteen for a school that set no deadline. + let Some(over) = date.day_end() else { + return Ok(()); + }; + if Timestamp::now().as_millis() >= over.as_millis() { + return Err(AppError::Conflict( + "that meal's day has passed, so its menu takes no more bookings", + )); + } + Ok(()) +} + /// Booking and cancelling both close `cutoff.minutes` before the meal is /// served. `None` = the school set no cutoff, so neither ever closes. /// @@ -794,12 +829,18 @@ mod tests { } } - /// A published menu on a fresh in-memory database, plus a student. + /// A published menu on a fresh in-memory database, plus a student. Dated + /// well ahead on purpose: a menu whose day has passed refuses every + /// booking, so a date the calendar overtakes would fail this whole module. async fn menu(capacity: Option) -> (Database, MenuId) { + menu_on("2099-09-14", capacity).await + } + + async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { let db = crate::database::init_mem().await.unwrap(); let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; let menu = Menu::create( - MenuDate::try_new("2026-09-14").unwrap(), + MenuDate::try_new(date).unwrap(), MenuSlot::try_new("lunch", &slots).unwrap(), capacity, &UserId::generate(), @@ -1303,6 +1344,136 @@ mod tests { assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); } + fn today() -> String { + chrono::Utc::now() + .date_naive() + .format("%Y-%m-%d") + .to_string() + } + + /// The day being over is not the cutoff. It binds with no + /// `meal_cancel_cutoff_minutes` set and no `serving_minute` on the slot — + /// the shipped defaults, under which the cutoff deliberately closes nothing + /// — and it never binds today, at any hour. + #[test] + fn the_past_day_guard_is_not_the_serving_hour_cutoff() { + let yesterday = (chrono::Utc::now().date_naive() - chrono::Duration::days(1)) + .format("%Y-%m-%d") + .to_string(); + assert!(check_day_not_past(&MenuDate::try_new(&yesterday).unwrap()).is_err()); + assert!(check_day_not_past(&MenuDate::try_new(&today()).unwrap()).is_ok()); + assert!(check_day_not_past(&MenuDate::try_new("2999-01-01").unwrap()).is_ok()); + // Today's menu is open all day *and* carries no deadline at all under + // the shipped defaults — the two answers stay separate. + assert!( + check_cutoff( + &MenuDate::try_new(&today()).unwrap(), + &lunch(), + &cutoff(Some(60), None) + ) + .is_ok() + ); + // A day no calendar can place is left to the cutoff, which fails it + // closed when one is configured; guessing "past" here would shut the + // canteen for a school that set no deadline. + let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); + assert!(check_day_not_past(&impossible).is_ok()); + } + + /// The charge hole itself: a menu whose day has gone by must take no seat + /// and mint no ledger line, with the shipped defaults in force. + #[tokio::test] + async fn a_past_day_takes_no_seat_and_writes_no_charge() { + let (db, menu) = menu_on("2020-01-06", None).await; + let ali = UserId::generate(); + add_dish(&menu, 4550, &db).await; + + assert!(matches!( + MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await, + Err(AppError::Conflict(_)) + )); + assert_eq!(seats(&menu, &db).await, 0); + let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) + .await + .unwrap(); + assert!( + lines.is_empty() && total == 0, + "a refused booking bills nothing" + ); + } + + /// The documented decision the past-day guard must not swallow: today's + /// menu, on a slot with no serving hour, books exactly as it always did — + /// with the cutoff knob set *and* unset. + #[tokio::test] + async fn todays_menu_still_books_without_a_serving_hour() { + let (db, menu) = menu_on(&today(), None).await; + let ali = UserId::generate(); + MealBooking::book(&menu, &ali, &ali, &cutoff(Some(60), None), &db) + .await + .expect("an unset serving hour is an unenforced cutoff"); + assert_eq!(seats(&menu, &db).await, 1); + } + + /// Cancelling stays open on a day already gone — that is how money already + /// taken is given back, and it is the same reason manager+ bypasses the + /// cutoff. The guard binds `book` alone. + #[tokio::test] + async fn a_past_day_still_gives_the_seat_and_the_money_back() { + let (db, menu) = menu_on("2020-01-06", None).await; + let ali = UserId::generate(); + add_dish(&menu, 4550, &db).await; + // The seat this student is holding was taken while the day was still + // ahead — the shape the create-side check cannot reach. A test cannot + // age a menu (`date` is READONLY), so the seat is placed on an + // already-past menu by the very transaction `book` places it with. + let fresh = Menu::read(&menu, &db).await.unwrap().unwrap(); + let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); + let row = MealBooking { + id: MealBookingId::composite(&menu, &ali), + menu: menu.clone(), + student: ali.clone(), + booked_by: ali.clone(), + status: MealBookingStatus::Booked, + attempt: 1, + price_minor: price, + cancelled_at: None, + created_at: Timestamp::now(), + }; + let charge = MealLedger::charge_for(&row, &ali); + let booked = match MealBooking::claim_and_place( + &menu.record(), + cap::UNLIMITED, + fresh.get_version(), + &row, + price, + charge.as_ref(), + &db, + ) + .await + .unwrap() + { + Claimed::Made(booking) => booking, + _ => panic!("the seat was free"), + }; + assert_eq!(seats(&menu, &db).await, 1); + + assert!(matches!( + MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await, + Err(AppError::Conflict(_)), + )); + let cancelled = booked + .cancel(&MealCutoff::default(), &ali, &db) + .await + .expect("a cancel on a past day still frees the seat"); + assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled); + assert_eq!(seats(&menu, &db).await, 0); + let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db) + .await + .unwrap(); + assert_eq!(lines.len(), 2, "the charge and its reversal"); + } + /// The instant the deadline counts back from: midnight UTC of the day plus /// the slot's serving minute. The `None` case still resolves to midnight, /// but only as the date's validity probe — `check_cutoff` never counts a diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 8255b03..61c2268 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -173,20 +173,25 @@ impl MenuDate { if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { return Err(invalid); } - let digits = - |from: usize, to: usize| -> Option { value.get(from..to)?.parse::().ok() }; - let (Some(year), Some(month), Some(day)) = (digits(0, 4), digits(5, 7), digits(8, 10)) - else { + // Parsed by **chrono** and compared back to the text it came from, so + // this parser and the one that computes the serving instant + // ([`served_at`](crate::domain::meal_booking)) agree by construction + // rather than by two independent checks that can drift apart. They did: + // a hand-rolled `"+1".parse::()` accepted a signed component (std + // does), `from_ymd_opt` was then handed the normalized number and said + // yes, and `2026-+1-01` became a *second* record id for the 1st of + // January — its own capacity and seat counter, invisible to every + // `date >= $from` range read ('+' sorts below '0'), and unbookable + // besides, since chrono refuses to parse it back. + // + // The round trip also keeps the day a **real** one, leap years and all + // (a 31st of February is fully actionable — seats, charges, dishes, + // marks — with no instant any cutoff can count back from), and pins the + // zero-padding the text ordering rests on. + let Ok(day) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") else { return Err(invalid); }; - // The day has to be a **real** one, leap years and all. A 31st of - // February is not the harmless typo it looks: a menu is published on it - // and is then fully actionable — seats, charges, dishes, attendance - // marks — but no instant can be computed for it, so the booking and - // cancel cutoff has nothing to count back from and never closes at all. - // The month/day ranges are this check's own business, hence no separate - // bounds test above (`from_ymd_opt` refuses month 0 and day 32 alike). - if chrono::NaiveDate::from_ymd_opt(year as i32, month, day).is_none() { + if day.format("%Y-%m-%d").to_string() != value { return Err(invalid); } Ok(Self(value.to_string())) @@ -195,6 +200,25 @@ impl MenuDate { pub fn as_str(&self) -> &str { &self.0 } + + /// The instant this calendar day is over: midnight UTC opening the next + /// one. UTC because the backend stores no school timezone, the same choice + /// [`served_at`](crate::domain::meal_booking) makes for the serving instant. + /// + /// This is the whole day's deadline, not the meal's: a menu for *today* is + /// still publishable and still bookable at any hour, whatever the slot's + /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s + /// separate business. `None` for a day that cannot be parsed (a row written + /// before `try_new` rejected impossible days). + pub fn day_end(&self) -> Option { + let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?; + Some(Timestamp::from_millis( + day.succ_opt()? + .and_hms_opt(0, 0, 0)? + .and_utc() + .timestamp_millis(), + )) + } } /// The meal slot a menu was published for, snapshotted as text. Validated @@ -530,6 +554,59 @@ mod tests { ); } + /// A signed component is not a calendar day, however willingly + /// `"+1".parse::()` reads one out of it. Accepting one minted a + /// *second* record id for the same day — its own capacity and seat counter + /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and + /// that the serving-instant parser could not read at all. + #[test] + fn date_refuses_a_signed_component() { + for signed in ["2026-+1-01", "2026-01-+1", "+026-01-01", "2026-01-+2"] { + assert!( + MenuDate::try_new(signed).is_err(), + "{signed} is not a calendar day" + ); + } + } + + /// The drift guard: whatever this accepts must be exactly what the calendar + /// library writes back for that day. Two parsers that merely *agree today* + /// are what let the signed form through — one normalized the sign away + /// before the other ever saw it. + #[test] + fn every_accepted_date_round_trips_through_the_calendar() { + for candidate in [ + "2026-07-26", + "2024-02-29", + "2026-+1-01", + "2026-1-1", + "0001-01-01", + "2026-02-29", + ] { + let stored = MenuDate::try_new(candidate).ok(); + let round_tripped = chrono::NaiveDate::parse_from_str(candidate, "%Y-%m-%d") + .ok() + .map(|day| day.format("%Y-%m-%d").to_string()) + .filter(|text| text == candidate); + assert_eq!( + stored.map(|date| date.as_str().to_string()), + round_tripped, + "{candidate} must be stored exactly as the calendar writes it, or not at all" + ); + } + } + + /// The day is over at midnight UTC opening the next one — not at the meal's + /// serving hour, which is the cutoff's separate business. + #[test] + fn a_day_ends_at_the_next_midnight_utc() { + let day = MenuDate::try_new("1970-01-01").unwrap(); + assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000); + // A row written before `try_new` refused impossible days has no end. + let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); + assert!(impossible.day_end().is_none()); + } + #[test] fn slot_must_be_one_the_school_serves() { let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()]; diff --git a/src/lib.rs b/src/lib.rs index 614bccb..b74e855 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,7 +47,7 @@ use crate::state::AppState; (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — 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). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), - (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), + (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. 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. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=