forge
Explore
Log in

Don't you dare go Hollow

Teachers publish slots, students book them

Browse files at this commit

771936e58fba9e617c2cb06e344a0c2ac673ab08Ahmet Kaan GümüşParent: 79189b8
  • feat
    • teachers publish slots, students book them
Show full message
✨ feat(appointments): teachers publish slots, students book them

Teachers keep a calendar of availability windows; students and parents
book one with a reason. Publishing a window is not consent to a specific
person and topic, so a booking lands pending until the teacher approves,
rejects, or counter-proposes another time — a counter-proposal returns it
to pending for the requester to accept or decline.

A slot holds one live booking, with occupancy derived under
APPOINTMENT_LOCK rather than stored, so rejecting or cancelling frees the
slot for someone else. No two approved meetings may overlap for the
teacher or the requester.

Cancelling refuses a meeting whose window has opened, so every path that
could land a booking on a past window is closed at the source: booking a
started slot, approving a started window, and proposing a started time
all refuse. Otherwise a booking could exist that nobody was able to
cancel.

Weekly repetition expands eagerly into concrete rows sharing a series id,
capped at 52, so cancelling one occurrence is an ordinary delete.
README.mdmodified+150 -3
@@ -73,6 +73,14 @@ question is readable by the whole school with anyone free to offer
7373 the worked steps, both editable by the solution's author anytime; pending
7474 questions show only to their asker and to teacher+, and approval freezes the
7575 content so nothing unmoderated ever reaches the pool.
76+Teachers keep an **appointment calendar**: a teacher+ publishes availability
77+slots (one-off, or repeating weekly up to an `until` date as a series that
78+deletes as one), and students and parents book a slot with a reason — the
79+booking lands `pending` until the teacher approves it, rejects it, or
80+counter-proposes another time (which sends it back to `pending` for the
81+requester to accept or decline); either side may cancel until the meeting
82+starts, one live booking holds a slot, and no approved meeting may overlap
83+another for the teacher or the requester (see "Appointments").
7684 School-varying policy is data, not code: exam kinds (each with its weight in
7785 course averages), attendance statuses, grade-display bands, the note-file
7886 size limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**
@@ -452,6 +460,18 @@ their existing shapes: the student exam-room reads
452460 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
453461 | POST | `/events/{id}/register` | teacher | `{user_id?}` — seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |
454462 | DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |
463+| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` — publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≤ 52, sharing a `series`); `400` if a weekly shift would run off the end of time |
464+| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar — future slots only, demoted teachers' slots left out · paged |
465+| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |
466+| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |
467+| POST | `/appointments` | student | `{slot, reason}` — book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |
468+| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests · paged |
469+| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |
470+| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |
471+| PATCH | `/appointments/{id}/cancel` | student | Call it off — the requester or the slot's teacher (manager+ too); `409` once settled or the meeting has started |
472+| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` — counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |
473+| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |
474+| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal — this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |
455475 | POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` — `kind` is `course` (default), `study` (etüt), or `club` (kulüp); `capacity` caps the roster (creator manages it) |
456476 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
457477 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
@@ -662,6 +682,126 @@ back to `null` ("never chose" — the client then follows the device
662682 preference), anything else must be one of the listed values or the whole patch
663683 is a `400`.
664684
685+## Appointments
686+
687+Office hours and parent-teacher conferences, booked instead of arranged by
688+message. A teacher+ **publishes availability**; a student or a parent
689+**books** one of those windows with a reason; the teacher **decides**. Two
690+rows carry it: an `appointment_slot` (the offer) and an `appointment` (the
691+booking sitting on it) — a slot is never "half booked", and a refused request
692+stays readable instead of vanishing.
693+
694+A slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix
695+milliseconds, `starts_at` strictly before `ends_at`, neither in the past — the
696+usual 60-second grace) plus an optional `note` (≤ 500 chars) shown to
697+requesters ("office hours", "veli görüşmesi"). Windows are **half-open**, so
698+10:00–10:30 and 10:30–11:00 are two slots, not a collision. `POST
699+/appointments/slots` publishes on the caller's *own* calendar (managers and
700+admins included — the calendar always belongs to whoever posted) and **always
701+answers an array**: one element for a one-off, one per occurrence for a
702+recurring publish.
703+
704+`repeat_weekly: true` with an `until` expands the same window every seven days
705+up to and including `until`, server-side, into **concrete rows** sharing a
706+`series` id — no recurrence rule is stored, so one week can be cancelled
707+without touching the rest. At most 52 occurrences (a year); asking for more is
708+a `400`, as is `repeat_weekly` without `until` — and so is a window sitting so
709+far ahead that shifting it by a week would run off the end of representable
710+time (the shift is checked, never wrapped: a wrapped end would land *before*
711+its start, and an inverted window can never overlap anything, which would
712+quietly disable the double-booking guard). Delete one occurrence with
713+`DELETE /appointments/slots/{id}`, the whole publish with `DELETE
714+/appointments/slots/series/{series}`.
715+
716+```json
717+POST /appointments/slots
718+{ "starts_at": 1900000000000, "ends_at": 1900001800000,
719+ "note": "office hours", "repeat_weekly": true, "until": 1901209600000 }
720+
721+201 [ { "id": "01J8…A", "teacher": {"id": "01J8…T", "username": "ayse",
722+ "display_name": "Ayşe Yılmaz"},
723+ "starts_at": 1900000000000, "ends_at": 1900001800000,
724+ "note": "office hours", "series": "01J8…S", "created_at": 1899… },
725+ { "id": "01J8…B", …, "starts_at": 1900604800000, "series": "01J8…S" } ]
726+```
727+
728+`GET /appointments/slots` is two lists behind one path: a teacher+ reads
729+**their own** calendar, past occurrences included; everyone else reads the
730+**bookable** calendar — future slots only, earliest first. A teacher demoted
731+after publishing leaves **inert** slots: their live role is re-read, so those
732+slots drop out of the bookable list and booking one is refused with a `409`.
733+The list does not say whether a slot is already taken — booking a taken one
734+answers `409`.
735+
736+**Booking.** `POST /appointments` (`{slot, reason}` — the reason is required,
737+≤ 1000 chars) is for **students and parents only**; staff arrange between
738+themselves off this API. A parent books for *themselves* — this is the
739+parent-teacher conference, not a booking on behalf of a child. The request
740+lands `pending`, always: publishing availability is not consent to a
741+particular person and a particular topic, so approve/reject still applies.
742+
743+A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two
744+are **live** and hold the slot; rejecting or cancelling frees it for someone
745+else immediately (occupancy is counted live, never stored as a flag). The
746+decisions:
747+
748+- `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused
749+ (`409`) when the effective window has already started.
750+- `PATCH /{id}/reject` — turns it down; the slot frees up.
751+- `PATCH /{id}/cancel` — either side, the requester or the teacher, from
752+ either live state. Refused (`409`) once the meeting's window has started: a
753+ meeting that already began is history, not a plan. The guard sits in the
754+ domain's `cancel` itself, under the appointment lock and on a fresh read, so
755+ every way of cancelling — the decline below included — inherits it.
756+- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) — the teacher
757+ **counter-proposes**. The times land on the *same* row as
758+ `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`
759+ and `decided_by` clears, because leaving it `approved` would silently move a
760+ confirmed appointment. The slot stays held meanwhile. A window that has
761+ already opened is refused (`409`): the 60-second grace on the times is for
762+ clock skew, not for proposing into a meeting already underway — one nobody
763+ could then cancel.
764+- `PATCH /{id}/reschedule/accept` — the **requester** only: this *is* approval
765+ at the new time, so the overlap guard runs again — and so does the
766+ already-started guard (`409`). Agreeing to a window that has begun does not
767+ help: the meeting could never be cancelled. The booking stays `pending`, so
768+ the teacher just proposes a time that can still happen.
769+- `PATCH /{id}/reschedule/decline` — the requester only, and it **cancels the
770+ booking**: the proposal replaced the time that was asked for, so there is
771+ nothing to fall back to. The row stays readable as `cancelled` with the
772+ refused proposal still on it — book another slot instead. Declining *is* a
773+ cancel, so it answers to the cancel deadline too (`409` once the effective
774+ window has started).
775+
776+A booking's effective window is the accepted counter-proposal when there is
777+one and the slot's own window otherwise; that is what `starts_at`/`ends_at` on
778+an `AppointmentResponse` report, and what the cancel deadline is judged on.
779+
780+**No double-booking.** Two `approved` meetings may never overlap for the same
781+teacher *or* the same requester (`409`). The guard runs at approval — the
782+moment anyone is actually committed — and again on accepting a counter-proposal,
783+because the time moved. Approval also refuses (`409`) an **effective window
784+that has already started** (the proposal's when one stands, the slot's
785+otherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is
786+refused up front only when the slot's window has already started (booking it
787+would create a meeting `cancel` refuses to undo — the 60-second publish grace
788+is for clock skew, not for booking into the past), when the slot is already
789+taken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to
790+resolve when they decide, since refusing a request against a window they
791+themselves published would only confuse. Touching windows never conflict.
792+
793+Deletion follows the same rule as the rest of the codebase: a slot carrying a
794+live (pending or approved) booking refuses to go (`409`) — reject or cancel
795+that booking first — and a series delete is all-or-nothing, `409` if *any*
796+occurrence still carries one, so the person waiting is dealt with rather than
797+left stranded on a stray week. Settled (rejected/cancelled) bookings cascade
798+away with their slot.
799+
800+`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed
801+at their own slots (their request inbox), everyone else the ones they
802+requested, newest first, paged. Managers and admins read their own inbox here
803+too — they may still decide any booking by id.
804+
665805 ## Messaging
666806
667807 One-to-one, mail-style (subject + body + an optional free-text `label` the UI
@@ -1635,6 +1775,12 @@ src/
16351775 chat_message.rs ChatMessageId · ChatContent · MessageRole · MessageStatus ·
16361776 ChatMessage (one turn; the assistant row is written
16371777 `pending` before the AI call and settled after)
1778+ appointment_slot.rs AppointmentSlotId · SlotSeries · SlotNote ·
1779+ AppointmentSlot (a teacher's published availability; a
1780+ recurring publish is expanded into rows sharing a series id)
1781+ appointment.rs AppointmentId · AppointmentStatus · AppointmentReason ·
1782+ Appointment (a booking on a slot; occupancy and overlap are
1783+ derived under APPOINTMENT_LOCK, never stored)
16381784 pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log)
16391785 pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody ·
16401786 PoolQuestion (student-asked question; teacher-approved into
@@ -1658,9 +1804,10 @@ src/
16581804 dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas
16591805 exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)
16601806 page.rs PageParams · Page<T> (shared pagination)
1661- auth.rs users.rs notes.rs messages.rs events.rs courses.rs subjects.rs
1662- sessions.rs exams.rs homework.rs questions.rs marks.rs work.rs
1663- pomodoro.rs attendance.rs settings.rs terms.rs ai.rs chat.rs
1807+ auth.rs users.rs notes.rs messages.rs events.rs appointments.rs
1808+ courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
1809+ marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs
1810+ ai.rs chat.rs
16641811 ```
16651812
16661813 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
src/constant.rsmodified+12 -0
@@ -133,6 +133,18 @@ pub const SETTINGS_UPDATE_RETRIES: usize = 3;
133133
134134 pub const MAX_TERM_NAME_LEN: usize = 100;
135135
136+/// A published availability slot's optional note ("bring your report card").
137+pub const MAX_APPOINTMENT_NOTE_LEN: usize = 500;
138+
139+/// Why a requester wants the meeting — required, and read by a human, so it
140+/// stays short.
141+pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000;
142+
143+/// How many concrete slot rows one recurring publish may expand into. Weekly
144+/// occurrences over a full school year fit inside this; a runaway `until`
145+/// (a decade out) is refused instead of writing thousands of rows.
146+pub const MAX_SLOT_OCCURRENCES: usize = 52;
147+
136148 /// The only accepted course kinds. `course`: a regular class (ders). `study`:
137149 /// a supervised study session (etüt). Behaviorally identical — the kind is a
138150 /// label for the UI, everything else (enrollment, exams, sessions, marks)
src/database.rsmodified+34 -0
@@ -56,6 +56,8 @@ pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
5656 pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
5757 pub const CONVERSATION_TABLE: &str = "conversation";
5858 pub const CHAT_MESSAGE_TABLE: &str = "chat_message";
59+pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
60+pub const APPOINTMENT_TABLE: &str = "appointment";
5961
6062 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.
6163 /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
@@ -391,6 +393,38 @@ const MIGRATION: &str = "
391393 DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
392394 DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
393395 DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
396+
397+ -- Appointments (greenfield, 2026-07-23): a teacher publishes availability
398+ -- slots, a student or parent books one. `series` groups the occurrences a
399+ -- weekly repeat expanded into, so one cancel deletes one row and a series
400+ -- delete finds the rest. A booking's live/dead state is the `status`
401+ -- string; occupancy is derived from it under the appointment lock rather
402+ -- than stored, so a rejected or cancelled booking frees its slot again.
403+ -- The `proposed_*` fields carry a teacher's counter-proposal on the same
404+ -- row until the requester accepts. No BACKFILL: both tables are new.
405+ DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
406+ DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
407+ DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
408+ DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
409+ DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
410+ DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
411+ DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
412+ DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at;
413+ DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series;
414+
415+ DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL;
416+ DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>;
417+ DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>;
418+ DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending';
419+ DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string;
420+ DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>;
421+ DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>;
422+ DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>;
423+ DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>;
424+ DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int;
425+ DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
426+ DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
427+ DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
394428 ";
395429
396430 /// Data backfills for rows written by older binaries. Runs *after* (and apart
src/domain/appointment.rsadded+741 -0
@@ -0,0 +1,741 @@
1+//! A booking on a teacher's [`AppointmentSlot`]. A student or a parent asks
2+//! for the meeting with a reason; the teacher approves, rejects, or
3+//! counter-proposes another time.
4+//!
5+//! Two invariants live here, and both are guarded by [`APPOINTMENT_LOCK`]
6+//! rather than by the database:
7+//!
8+//! - **One live booking per slot.** Occupancy is counted from the rows, not
9+//! stored — so rejecting or cancelling frees the slot with nothing to reset.
10+//! - **No double-booked person.** An approved meeting may not overlap another
11+//! approved meeting of the same teacher *or* of the same requester.
12+//!
13+//! Both are count-then-write checks across records, which a `BEGIN…COMMIT`
14+//! does not serialize in SurrealDB (write-skew: two racing bookings each see a
15+//! free slot). This backend is the database's only writer, so one process-wide
16+//! lock closes it, exactly as `REGISTER_LOCK` does for event seats.
17+
18+use std::sync::LazyLock;
19+
20+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
21+use tokio::sync::Mutex;
22+use ulid::Generator;
23+
24+use crate::constant::MAX_APPOINTMENT_REASON_LEN;
25+use crate::database::{APPOINTMENT_TABLE, Database};
26+use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
27+use crate::domain::timestamp::Timestamp;
28+use crate::domain::user::UserId;
29+use crate::error::{AppError, ValidationError};
30+use crate::validate::validate_required;
31+
32+/// Serializes every occupancy/overlap decision: the check and the write it
33+/// authorizes must be one atomic step, and SurrealDB transactions do not
34+/// conflict-check a cross-record `count()` against a concurrent insert.
35+///
36+/// Lock order: no path ever holds this together with `ENROLL_LOCK`,
37+/// `TERM_LOCK`, `REGISTER_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments
38+/// touch no roster, term, event seat, or exam room, and none of those touch
39+/// appointments — so they cannot deadlock. Should a future path ever need two,
40+/// take this one *last*.
41+// ponytail: global lock; per-teacher locks if appointment traffic ever grows
42+// enough for the contention to matter.
43+pub(crate) static APPOINTMENT_LOCK: Mutex<()> = Mutex::const_new(());
44+
45+/// Mints booking ids in write order — `Ulid::new()`'s random low bits sort
46+/// arbitrarily within one millisecond, which would scramble the `id` tie-break
47+/// of the newest-first listings below.
48+static IDS: LazyLock<std::sync::Mutex<Generator>> =
49+ LazyLock::new(|| std::sync::Mutex::new(Generator::new()));
50+
51+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
52+pub struct AppointmentId(RecordId);
53+
54+impl AppointmentId {
55+ pub fn generate() -> Self {
56+ let mut ids = IDS.lock().expect("appointment id generator poisoned");
57+ // The only error is exhausting the random bits within one millisecond
58+ // (2^80 ids deep); it clears itself as the clock ticks, so retry.
59+ let ulid = loop {
60+ if let Ok(ulid) = ids.generate() {
61+ break ulid;
62+ }
63+ };
64+ Self(RecordId::new(APPOINTMENT_TABLE, ulid.to_string()))
65+ }
66+
67+ pub fn from_key(key: &str) -> Self {
68+ Self(RecordId::new(APPOINTMENT_TABLE, key))
69+ }
70+
71+ pub fn record(&self) -> RecordId {
72+ self.0.clone()
73+ }
74+
75+ pub fn key(&self) -> &str {
76+ match &self.0.key {
77+ RecordIdKey::String(key) => key,
78+ _ => "",
79+ }
80+ }
81+}
82+
83+/// Where a booking stands. `untagged` + `rename_all` store it as the bare
84+/// lowercase string the `status` column types as; an unknown value comes back
85+/// as a deserialization error, never a panic.
86+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
87+#[surreal(untagged, rename_all = "lowercase")]
88+pub enum AppointmentStatus {
89+ Pending,
90+ Approved,
91+ Rejected,
92+ Cancelled,
93+}
94+
95+impl AppointmentStatus {
96+ /// The wire/storage form. Must stay in lockstep with `rename_all`.
97+ pub fn as_str(self) -> &'static str {
98+ match self {
99+ AppointmentStatus::Pending => "pending",
100+ AppointmentStatus::Approved => "approved",
101+ AppointmentStatus::Rejected => "rejected",
102+ AppointmentStatus::Cancelled => "cancelled",
103+ }
104+ }
105+
106+ /// Does a booking in this state still hold its slot? Rejected and
107+ /// cancelled ones do not — that is what frees the slot for re-booking.
108+ pub fn is_live(self) -> bool {
109+ matches!(
110+ self,
111+ AppointmentStatus::Pending | AppointmentStatus::Approved
112+ )
113+ }
114+}
115+
116+/// Why the requester wants the meeting. Required: a teacher approving a
117+/// parent-teacher conference needs to know what it is about.
118+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
119+pub struct AppointmentReason(String);
120+
121+impl AppointmentReason {
122+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
123+ validate_required("reason", value, MAX_APPOINTMENT_REASON_LEN)?;
124+ Ok(Self(value.to_string()))
125+ }
126+
127+ pub fn as_str(&self) -> &str {
128+ &self.0
129+ }
130+}
131+
132+/// The window an approved booking actually occupies, as read back from the
133+/// database: the counter-proposed time when there is one, the slot's own
134+/// otherwise. Optional fields because a dangling slot reference resolves to
135+/// `NONE` — such a row is skipped rather than failing the whole guard.
136+#[derive(Debug, Clone, SurrealValue)]
137+struct BookedWindow {
138+ starts_at: Option<Timestamp>,
139+ ends_at: Option<Timestamp>,
140+}
141+
142+#[derive(Debug, Clone, SurrealValue)]
143+pub struct Appointment {
144+ id: AppointmentId,
145+ slot: AppointmentSlotId,
146+ requester: UserId,
147+ status: AppointmentStatus,
148+ reason: AppointmentReason,
149+ /// A counter-proposal from the teacher (or a new time the requester asks
150+ /// for). Set as a triple or not at all; once accepted it *is* the
151+ /// meeting's time, overriding the slot's own window.
152+ proposed_starts_at: Option<Timestamp>,
153+ proposed_ends_at: Option<Timestamp>,
154+ proposed_by: Option<UserId>,
155+ decided_by: Option<UserId>,
156+ created_at: Timestamp,
157+}
158+
159+impl Appointment {
160+ pub fn get_id(&self) -> &AppointmentId {
161+ &self.id
162+ }
163+
164+ pub fn get_slot(&self) -> &AppointmentSlotId {
165+ &self.slot
166+ }
167+
168+ pub fn get_requester(&self) -> &UserId {
169+ &self.requester
170+ }
171+
172+ pub fn get_status(&self) -> AppointmentStatus {
173+ self.status
174+ }
175+
176+ pub fn get_reason(&self) -> &AppointmentReason {
177+ &self.reason
178+ }
179+
180+ pub fn get_proposed_starts_at(&self) -> Option<Timestamp> {
181+ self.proposed_starts_at
182+ }
183+
184+ pub fn get_proposed_ends_at(&self) -> Option<Timestamp> {
185+ self.proposed_ends_at
186+ }
187+
188+ pub fn get_proposed_by(&self) -> Option<&UserId> {
189+ self.proposed_by.as_ref()
190+ }
191+
192+ pub fn get_decided_by(&self) -> Option<&UserId> {
193+ self.decided_by.as_ref()
194+ }
195+
196+ pub fn get_created_at(&self) -> Timestamp {
197+ self.created_at
198+ }
199+
200+ /// When this booking actually happens: the proposed time if one is on the
201+ /// row, the slot's window otherwise. `slot` must be this booking's slot.
202+ pub fn window(&self, slot: &AppointmentSlot) -> (Timestamp, Timestamp) {
203+ match (self.proposed_starts_at, self.proposed_ends_at) {
204+ (Some(starts_at), Some(ends_at)) => (starts_at, ends_at),
205+ _ => (slot.get_starts_at(), slot.get_ends_at()),
206+ }
207+ }
208+
209+ /// Do two half-open windows `[start, end)` collide? Touching windows
210+ /// (one ends exactly where the next begins) do **not** — back-to-back
211+ /// meetings are the normal way a teacher's hour is filled.
212+ pub fn overlaps(
213+ a_starts_at: Timestamp,
214+ a_ends_at: Timestamp,
215+ b_starts_at: Timestamp,
216+ b_ends_at: Timestamp,
217+ ) -> bool {
218+ a_starts_at.as_millis() < b_ends_at.as_millis()
219+ && a_ends_at.as_millis() > b_starts_at.as_millis()
220+ }
221+
222+ /// Is `[starts_at, ends_at)` already taken for either party? Both sides are
223+ /// checked: a teacher can't be in two meetings at once, and neither can a
224+ /// requester (a parent with two children's teachers, say).
225+ ///
226+ /// Only *approved* bookings block — a pending request is a wish, not a
227+ /// commitment, so several may queue on overlapping times and the first
228+ /// approval wins. `except` skips one row, so re-checking a booking against
229+ /// the world never trips over itself.
230+ ///
231+ /// Caller must hold [`APPOINTMENT_LOCK`] for the answer to still be true
232+ /// by the time it is acted on.
233+ pub async fn conflicts(
234+ teacher: &UserId,
235+ requester: &UserId,
236+ starts_at: Timestamp,
237+ ends_at: Timestamp,
238+ except: Option<&AppointmentId>,
239+ db: &Database,
240+ ) -> Result<bool, AppError> {
241+ // The effective window is computed in the query (proposal overrides
242+ // the slot) but compared here: one round trip, and the comparison
243+ // itself stays a plain, unit-tested Rust predicate.
244+ let mut result = db
245+ .query(
246+ "SELECT \
247+ (IF proposed_starts_at != NONE THEN proposed_starts_at \
248+ ELSE slot.starts_at END) AS starts_at, \
249+ (IF proposed_ends_at != NONE THEN proposed_ends_at \
250+ ELSE slot.ends_at END) AS ends_at \
251+ FROM appointment \
252+ WHERE status = 'approved' AND id != $except \
253+ AND (requester = $requester OR slot.teacher = $teacher)",
254+ )
255+ .bind(("teacher", teacher.record()))
256+ .bind(("requester", requester.record()))
257+ .bind(("except", except.map(AppointmentId::record)))
258+ .await?
259+ .check()?;
260+ Ok(result
261+ .take::<Vec<BookedWindow>>(0)?
262+ .into_iter()
263+ .filter_map(|window| Some((window.starts_at?, window.ends_at?)))
264+ .any(|(booked_starts_at, booked_ends_at)| {
265+ Self::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at)
266+ }))
267+ }
268+
269+ /// Does `slot` still hold a booking that keeps it occupied? The slot
270+ /// delete guard's question, and the re-booking gate's. Caller must hold
271+ /// [`APPOINTMENT_LOCK`].
272+ pub async fn has_live_booking(
273+ slot: &AppointmentSlotId,
274+ db: &Database,
275+ ) -> Result<bool, AppError> {
276+ let mut result = db
277+ .query(
278+ "SELECT * FROM appointment WHERE slot = $slot \
279+ AND status IN ['pending', 'approved'] LIMIT 1",
280+ )
281+ .bind(("slot", slot.record()))
282+ .await?
283+ .check()?;
284+ Ok(!result.take::<Vec<Appointment>>(0)?.is_empty())
285+ }
286+
287+ /// Request `slot`. Lands `pending`: publishing availability is not consent
288+ /// to a specific person and topic.
289+ ///
290+ /// Refused (409) when the slot's window has already opened, when it already
291+ /// carries a live booking, or when the requester is already committed
292+ /// elsewhere at that time — all re-derived
293+ /// from a fresh read under [`APPOINTMENT_LOCK`], so two racing requests
294+ /// cannot both find the slot free.
295+ pub async fn book(
296+ slot: &AppointmentSlotId,
297+ requester: &UserId,
298+ reason: AppointmentReason,
299+ db: &Database,
300+ ) -> Result<Appointment, AppError> {
301+ let _guard = APPOINTMENT_LOCK.lock().await;
302+ let slot_row = AppointmentSlot::read(slot, db)
303+ .await?
304+ .ok_or(AppError::NotFound)?;
305+ if Self::has_live_booking(slot, db).await? {
306+ return Err(AppError::Conflict("the slot is already booked"));
307+ }
308+ // A window that has opened is history, not a plan: `cancel` refuses to
309+ // call off a meeting that started, so such a booking would be stuck
310+ // forever. `list_upcoming` hides these slots, but a stale id still
311+ // reaches here. The publish-time 60s skew grace does not apply.
312+ if slot_row.get_starts_at().as_millis() <= Timestamp::now().as_millis() {
313+ return Err(AppError::Conflict("the slot has already started"));
314+ }
315+ // The teacher's own overlaps are not checked here — an approved
316+ // meeting of theirs elsewhere is the *approval*'s business, and
317+ // refusing the request outright would hide a slot they published.
318+ if Self::conflicts(
319+ requester,
320+ requester,
321+ slot_row.get_starts_at(),
322+ slot_row.get_ends_at(),
323+ None,
324+ db,
325+ )
326+ .await?
327+ {
328+ return Err(AppError::Conflict(
329+ "you already have an appointment at that time",
330+ ));
331+ }
332+ let appointment = Appointment {
333+ id: AppointmentId::generate(),
334+ slot: slot.clone(),
335+ requester: requester.clone(),
336+ status: AppointmentStatus::Pending,
337+ reason,
338+ proposed_starts_at: None,
339+ proposed_ends_at: None,
340+ proposed_by: None,
341+ decided_by: None,
342+ created_at: Timestamp::now(),
343+ };
344+ let created: Option<Appointment> = db
345+ .create(appointment.id.record())
346+ .content(appointment)
347+ .await?;
348+ created.ok_or_else(|| AppError::Internal("failed to book the appointment".into()))
349+ }
350+
351+ pub async fn read(id: &AppointmentId, db: &Database) -> Result<Option<Appointment>, AppError> {
352+ Ok(db.select(id.record()).await?)
353+ }
354+
355+ pub async fn list_for_requester(
356+ requester: &UserId,
357+ db: &Database,
358+ ) -> Result<Vec<Appointment>, AppError> {
359+ let mut result = db
360+ .query("SELECT * FROM appointment WHERE requester = $requester ORDER BY id DESC")
361+ .bind(("requester", requester.record()))
362+ .await?
363+ .check()?;
364+ Ok(result.take::<Vec<Appointment>>(0)?)
365+ }
366+
367+ /// Every booking aimed at `teacher`, across all their slots — the teacher's
368+ /// request inbox.
369+ pub async fn list_for_teacher(
370+ teacher: &UserId,
371+ db: &Database,
372+ ) -> Result<Vec<Appointment>, AppError> {
373+ let mut result = db
374+ .query("SELECT * FROM appointment WHERE slot.teacher = $teacher ORDER BY id DESC")
375+ .bind(("teacher", teacher.record()))
376+ .await?
377+ .check()?;
378+ Ok(result.take::<Vec<Appointment>>(0)?)
379+ }
380+
381+ pub async fn list_for_slot(
382+ slot: &AppointmentSlotId,
383+ db: &Database,
384+ ) -> Result<Vec<Appointment>, AppError> {
385+ let mut result = db
386+ .query("SELECT * FROM appointment WHERE slot = $slot ORDER BY id DESC")
387+ .bind(("slot", slot.record()))
388+ .await?
389+ .check()?;
390+ Ok(result.take::<Vec<Appointment>>(0)?)
391+ }
392+
393+ /// Confirm the meeting. Re-runs the double-booking guard for both teacher
394+ /// and requester against a fresh read under [`APPOINTMENT_LOCK`] — the
395+ /// authoritative check, since only approval commits anyone. Refused (409)
396+ /// when the effective window has already started; that also covers
397+ /// [`accept_proposal`], which lands here.
398+ pub async fn approve(
399+ id: &AppointmentId,
400+ decided_by: &UserId,
401+ db: &Database,
402+ ) -> Result<Appointment, AppError> {
403+ let _guard = APPOINTMENT_LOCK.lock().await;
404+ let mut appointment = Self::read_pending(id, db).await?;
405+ let slot = AppointmentSlot::read(&appointment.slot, db)
406+ .await?
407+ .ok_or(AppError::NotFound)?;
408+ let (starts_at, ends_at) = appointment.window(&slot);
409+ // The effective window — the proposal's when one stands — must still be
410+ // ahead. Mutual agreement does not help: `cancel` refuses a meeting
411+ // that started, so committing to a passed window would mint a booking
412+ // nobody can ever undo. Refused, the row stays `pending` and the
413+ // teacher can propose a time that can actually happen.
414+ if starts_at.as_millis() <= Timestamp::now().as_millis() {
415+ return Err(AppError::Conflict("that time has already started"));
416+ }
417+ if Self::conflicts(
418+ slot.get_teacher(),
419+ &appointment.requester,
420+ starts_at,
421+ ends_at,
422+ Some(id),
423+ db,
424+ )
425+ .await?
426+ {
427+ return Err(AppError::Conflict(
428+ "that time collides with another approved appointment",
429+ ));
430+ }
431+ appointment.status = AppointmentStatus::Approved;
432+ appointment.decided_by = Some(decided_by.clone());
433+ Self::save(appointment, db).await
434+ }
435+
436+ /// Turn the request down. Frees the slot: occupancy counts live rows only.
437+ pub async fn reject(
438+ id: &AppointmentId,
439+ decided_by: &UserId,
440+ db: &Database,
441+ ) -> Result<Appointment, AppError> {
442+ let _guard = APPOINTMENT_LOCK.lock().await;
443+ let mut appointment = Self::read_pending(id, db).await?;
444+ appointment.status = AppointmentStatus::Rejected;
445+ appointment.decided_by = Some(decided_by.clone());
446+ Self::save(appointment, db).await
447+ }
448+
449+ /// Call the meeting off. Legal from either side and from either live
450+ /// state, so an approved meeting can still be dropped; the slot frees up.
451+ ///
452+ /// Refused (409) once the *effective* window has opened — a meeting that
453+ /// began is history, not a plan. The guard lives here rather than in the
454+ /// handler so every caller inherits it: `decline_reschedule` cancels
455+ /// through this same door and used to slip past a handler-only check.
456+ pub async fn cancel(id: &AppointmentId, db: &Database) -> Result<Appointment, AppError> {
457+ let _guard = APPOINTMENT_LOCK.lock().await;
458+ let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
459+ if !appointment.status.is_live() {
460+ return Err(AppError::Conflict("the appointment is already settled"));
461+ }
462+ let slot = AppointmentSlot::read(&appointment.slot, db)
463+ .await?
464+ .ok_or(AppError::NotFound)?;
465+ if appointment.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {
466+ return Err(AppError::Conflict("the appointment has already started"));
467+ }
468+ appointment.status = AppointmentStatus::Cancelled;
469+ Self::save(appointment, db).await
470+ }
471+
472+ /// Counter-propose another time on the same booking (no second row, so the
473+ /// reason and the history stay in one place).
474+ ///
475+ /// The proposal sends the booking back to `pending`: a previously approved
476+ /// meeting is *not* committed at the new time until the other side accepts,
477+ /// and leaving it approved would silently move a confirmed appointment.
478+ ///
479+ /// Refused (409) when the proposed window has already opened. The handler's
480+ /// `check_not_past` carries a 60s clock-skew grace, which is enough to
481+ /// propose a window that is already underway; `cancel` would then refuse to
482+ /// undo the booking, so it must not be offered in the first place.
483+ pub async fn propose(
484+ id: &AppointmentId,
485+ starts_at: Timestamp,
486+ ends_at: Timestamp,
487+ proposed_by: &UserId,
488+ db: &Database,
489+ ) -> Result<Appointment, AppError> {
490+ if starts_at.as_millis() >= ends_at.as_millis() {
491+ return Err(ValidationError::Invalid {
492+ field: "proposed_ends_at",
493+ reason: "must be after proposed_starts_at",
494+ }
495+ .into());
496+ }
497+ let _guard = APPOINTMENT_LOCK.lock().await;
498+ let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
499+ if !appointment.status.is_live() {
500+ return Err(AppError::Conflict("the appointment is already settled"));
501+ }
502+ if starts_at.as_millis() <= Timestamp::now().as_millis() {
503+ return Err(AppError::Conflict("that time has already started"));
504+ }
505+ appointment.status = AppointmentStatus::Pending;
506+ appointment.decided_by = None;
507+ appointment.proposed_starts_at = Some(starts_at);
508+ appointment.proposed_ends_at = Some(ends_at);
509+ appointment.proposed_by = Some(proposed_by.clone());
510+ Self::save(appointment, db).await
511+ }
512+
513+ /// Accept the standing proposal — approval at the proposed time. The
514+ /// overlap guard runs again because the time moved.
515+ pub async fn accept_proposal(
516+ id: &AppointmentId,
517+ decided_by: &UserId,
518+ db: &Database,
519+ ) -> Result<Appointment, AppError> {
520+ {
521+ let appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
522+ if appointment.proposed_starts_at.is_none() || appointment.proposed_ends_at.is_none() {
523+ return Err(AppError::Conflict("no time has been proposed"));
524+ }
525+ }
526+ // `approve` re-reads under the lock and reads the proposed window off
527+ // the row, so accepting is approval — no second code path.
528+ Self::approve(id, decided_by, db).await
529+ }
530+
531+ /// The row, insisting it is still open for a decision.
532+ async fn read_pending(id: &AppointmentId, db: &Database) -> Result<Appointment, AppError> {
533+ let appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
534+ if appointment.status != AppointmentStatus::Pending {
535+ return Err(AppError::Conflict("the appointment is no longer pending"));
536+ }
537+ Ok(appointment)
538+ }
539+
540+ async fn save(appointment: Appointment, db: &Database) -> Result<Appointment, AppError> {
541+ let updated: Option<Appointment> = db
542+ .update(appointment.id.record())
543+ .content(appointment)
544+ .await?;
545+ updated.ok_or(AppError::NotFound)
546+ }
547+}
548+
549+#[cfg(test)]
550+mod tests {
551+ use super::*;
552+ use surrealdb::types::Value;
553+
554+ fn at(millis: i64) -> Timestamp {
555+ Timestamp::from_millis(millis)
556+ }
557+
558+ /// A window that has not opened yet — `book` refuses started ones.
559+ fn soon(offset: i64) -> Timestamp {
560+ at(Timestamp::now().as_millis() + offset)
561+ }
562+
563+ #[tokio::test]
564+ async fn reason_is_required_and_capped() {
565+ assert!(AppointmentReason::try_new("").is_err());
566+ assert!(AppointmentReason::try_new(" ").is_err());
567+ assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN)).is_ok());
568+ assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN + 1)).is_err());
569+ }
570+
571+ /// The `status` column is `TYPE string`: an object-wrapped enum would be
572+ /// rejected on write, and the `status IN ['pending','approved']` occupancy
573+ /// query is written against exactly these spellings.
574+ #[tokio::test]
575+ async fn status_stores_as_a_bare_string() {
576+ for status in [
577+ AppointmentStatus::Pending,
578+ AppointmentStatus::Approved,
579+ AppointmentStatus::Rejected,
580+ AppointmentStatus::Cancelled,
581+ ] {
582+ let value = status.into_value();
583+ assert_eq!(value, Value::String(status.as_str().to_string()));
584+ assert_eq!(AppointmentStatus::from_value(value).unwrap(), status);
585+ }
586+ assert!(AppointmentStatus::from_value(Value::String("declined".into())).is_err());
587+ assert!(AppointmentStatus::Pending.is_live());
588+ assert!(AppointmentStatus::Approved.is_live());
589+ assert!(!AppointmentStatus::Rejected.is_live());
590+ assert!(!AppointmentStatus::Cancelled.is_live());
591+ }
592+
593+ #[tokio::test]
594+ async fn touching_windows_do_not_overlap_but_one_millisecond_does() {
595+ // 10:00–10:30 then 10:30–11:00: back to back, no conflict.
596+ assert!(!Appointment::overlaps(at(0), at(30), at(30), at(60)));
597+ assert!(!Appointment::overlaps(at(30), at(60), at(0), at(30)));
598+ // One millisecond of genuine overlap, from either side.
599+ assert!(Appointment::overlaps(at(0), at(31), at(30), at(60)));
600+ assert!(Appointment::overlaps(at(30), at(60), at(0), at(31)));
601+ // Containment, both ways, and an exact match.
602+ assert!(Appointment::overlaps(at(10), at(20), at(0), at(60)));
603+ assert!(Appointment::overlaps(at(0), at(60), at(10), at(20)));
604+ assert!(Appointment::overlaps(at(0), at(30), at(0), at(30)));
605+ // Disjoint by a whole hour.
606+ assert!(!Appointment::overlaps(at(0), at(30), at(90), at(120)));
607+ }
608+
609+ #[tokio::test]
610+ async fn window_prefers_a_proposal_over_the_slot() {
611+ let db = crate::database::init_mem().await.unwrap();
612+ let teacher = UserId::from_key("t1");
613+ let (starts_at, ends_at) = (soon(60_000), soon(120_000));
614+ let slot = AppointmentSlot::create(&teacher, starts_at, ends_at, None, &db)
615+ .await
616+ .unwrap();
617+ let mut appointment = Appointment::book(
618+ slot.get_id(),
619+ &UserId::from_key("s1"),
620+ AppointmentReason::try_new("ödev").unwrap(),
621+ &db,
622+ )
623+ .await
624+ .unwrap();
625+
626+ assert_eq!(appointment.window(&slot), (starts_at, ends_at));
627+ appointment.proposed_starts_at = Some(at(5_000));
628+ appointment.proposed_ends_at = Some(at(6_000));
629+ assert_eq!(appointment.window(&slot), (at(5_000), at(6_000)));
630+ }
631+
632+ /// A slot whose window already opened is unbookable: `cancel` would refuse
633+ /// to undo the resulting meeting, so the booking would be stuck for good.
634+ #[tokio::test]
635+ async fn a_started_slot_cannot_be_booked() {
636+ let db = crate::database::init_mem().await.unwrap();
637+ let teacher = UserId::from_key("t1");
638+ let reason = || AppointmentReason::try_new("görüşme").unwrap();
639+ let started = AppointmentSlot::create(&teacher, soon(-30_000), soon(60_000), None, &db)
640+ .await
641+ .unwrap();
642+ assert!(matches!(
643+ Appointment::book(started.get_id(), &UserId::from_key("s1"), reason(), &db).await,
644+ Err(AppError::Conflict("the slot has already started"))
645+ ));
646+
647+ let upcoming = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
648+ .await
649+ .unwrap();
650+ assert!(
651+ Appointment::book(upcoming.get_id(), &UserId::from_key("s1"), reason(), &db)
652+ .await
653+ .is_ok()
654+ );
655+ }
656+
657+ /// Approval judges the *effective* window, so a proposal whose time has
658+ /// come and gone cannot be accepted — the meeting would be uncancellable.
659+ #[tokio::test]
660+ async fn a_started_proposal_cannot_be_accepted() {
661+ let db = crate::database::init_mem().await.unwrap();
662+ let teacher = UserId::from_key("t1");
663+ let student = UserId::from_key("s1");
664+ let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
665+ .await
666+ .unwrap();
667+ let booking = Appointment::book(
668+ slot.get_id(),
669+ &student,
670+ AppointmentReason::try_new("görüşme").unwrap(),
671+ &db,
672+ )
673+ .await
674+ .unwrap();
675+
676+ // Proposing a window that already opened is refused up front — the
677+ // handler's 60s skew grace would otherwise let one through.
678+ assert!(matches!(
679+ Appointment::propose(booking.get_id(), soon(-30_000), soon(30_000), &teacher, &db)
680+ .await,
681+ Err(AppError::Conflict("that time has already started"))
682+ ));
683+ // And approval judges the effective window again, for a proposal whose
684+ // time simply passed while it stood: forced onto the row directly,
685+ // since `propose` no longer mints one.
686+ let mut standing = Appointment::read(booking.get_id(), &db)
687+ .await
688+ .unwrap()
689+ .unwrap();
690+ standing.proposed_starts_at = Some(soon(-30_000));
691+ standing.proposed_ends_at = Some(soon(30_000));
692+ Appointment::save(standing, &db).await.unwrap();
693+ assert!(matches!(
694+ Appointment::accept_proposal(booking.get_id(), &student, &db).await,
695+ Err(AppError::Conflict("that time has already started"))
696+ ));
697+ // Refused, not half-applied: still pending, still decidable at a time
698+ // that can actually happen.
699+ let after = Appointment::read(booking.get_id(), &db).await.unwrap();
700+ assert_eq!(after.unwrap().get_status(), AppointmentStatus::Pending);
701+ Appointment::propose(booking.get_id(), soon(60_000), soon(120_000), &teacher, &db)
702+ .await
703+ .unwrap();
704+ let accepted = Appointment::accept_proposal(booking.get_id(), &student, &db)
705+ .await
706+ .unwrap();
707+ assert_eq!(accepted.get_status(), AppointmentStatus::Approved);
708+ }
709+
710+ /// Occupancy is derived, so a rejected booking must hand the slot back.
711+ #[tokio::test]
712+ async fn rejecting_frees_the_slot_for_re_booking() {
713+ let db = crate::database::init_mem().await.unwrap();
714+ let teacher = UserId::from_key("t1");
715+ let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
716+ .await
717+ .unwrap();
718+ let reason = || AppointmentReason::try_new("görüşme").unwrap();
719+
720+ let first = Appointment::book(slot.get_id(), &UserId::from_key("s1"), reason(), &db)
721+ .await
722+ .unwrap();
723+ assert!(matches!(
724+ Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db).await,
725+ Err(AppError::Conflict(_))
726+ ));
727+ // The live booking also blocks the slot delete.
728+ assert!(matches!(
729+ slot.clone().delete(&db).await,
730+ Err(AppError::Conflict(_))
731+ ));
732+
733+ Appointment::reject(first.get_id(), &teacher, &db)
734+ .await
735+ .unwrap();
736+ let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db)
737+ .await
738+ .unwrap();
739+ assert_eq!(second.get_status(), AppointmentStatus::Pending);
740+ }
741+}
src/domain/appointment_slot.rsadded+513 -0
@@ -0,0 +1,513 @@
1+//! A teacher's published availability: "I am free here, book me". A slot is
2+//! pure calendar — it carries no booking state at all. Whether it is taken is
3+//! *derived* from its [`Appointment`] rows under [`APPOINTMENT_LOCK`], so a
4+//! rejected or cancelled booking frees the slot again without any flag to
5+//! reset (and without a UNIQUE index, which would keep a dead booking's seat).
6+//!
7+//! A recurring publish is expanded into concrete rows here, at write time,
8+//! sharing one `series` id — no recurrence rule is ever evaluated at read
9+//! time. Cancelling one week is then a plain row delete, and the whole series
10+//! is still addressable through its id.
11+
12+use std::sync::{LazyLock, Mutex};
13+
14+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
15+use ulid::{Generator, Ulid};
16+
17+use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES};
18+use crate::database::{APPOINTMENT_SLOT_TABLE, Database};
19+use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment};
20+use crate::domain::timestamp::{MILLIS_PER_DAY, Timestamp};
21+use crate::domain::user::UserId;
22+use crate::error::{AppError, ValidationError};
23+use crate::validate::validate_optional;
24+
25+/// One week, the only recurrence step this backend expands.
26+const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
27+
28+/// Mints slot ids in write order. `Ulid::new()`'s random low bits sort
29+/// arbitrarily among ids minted in the same millisecond, and a recurring
30+/// publish writes its whole expansion inside one — which would scramble the
31+/// `id` tie-break of the `ORDER BY starts_at, id` listings.
32+static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
33+
34+fn next_ulid() -> Ulid {
35+ let mut ids = IDS.lock().expect("slot id generator poisoned");
36+ // The only error is exhausting the random bits *within* one millisecond
37+ // (2^80 ids deep); it clears itself as the clock ticks, so retry rather
38+ // than fall back to a random id and silently reintroduce the defect.
39+ loop {
40+ if let Ok(ulid) = ids.generate() {
41+ break ulid;
42+ }
43+ }
44+}
45+
46+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
47+pub struct AppointmentSlotId(RecordId);
48+
49+impl AppointmentSlotId {
50+ pub fn generate() -> Self {
51+ Self(RecordId::new(
52+ APPOINTMENT_SLOT_TABLE,
53+ next_ulid().to_string(),
54+ ))
55+ }
56+
57+ pub fn from_key(key: &str) -> Self {
58+ Self(RecordId::new(APPOINTMENT_SLOT_TABLE, key))
59+ }
60+
61+ pub fn record(&self) -> RecordId {
62+ self.0.clone()
63+ }
64+
65+ pub fn key(&self) -> &str {
66+ match &self.0.key {
67+ RecordIdKey::String(key) => key,
68+ _ => "",
69+ }
70+ }
71+}
72+
73+/// The id shared by every occurrence one recurring publish created. A plain
74+/// ULID string (not a record id): it names a group, never a row.
75+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
76+pub struct SlotSeries(String);
77+
78+impl SlotSeries {
79+ pub fn generate() -> Self {
80+ Self(next_ulid().to_string())
81+ }
82+
83+ pub fn from_key(key: &str) -> Self {
84+ Self(key.to_string())
85+ }
86+
87+ pub fn as_str(&self) -> &str {
88+ &self.0
89+ }
90+}
91+
92+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
93+pub struct SlotNote(String);
94+
95+impl SlotNote {
96+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
97+ validate_optional("note", value, MAX_APPOINTMENT_NOTE_LEN)?;
98+ Ok(Self(value.to_string()))
99+ }
100+
101+ pub fn as_str(&self) -> &str {
102+ &self.0
103+ }
104+}
105+
106+/// The half-open window `[starts_at, ends_at)` a slot offers. Half-open is the
107+/// whole point: back-to-back slots (10:00–10:30, 10:30–11:00) touch without
108+/// overlapping, which is exactly how a teacher's hour is carved up.
109+#[derive(Debug, Clone, SurrealValue)]
110+pub struct AppointmentSlot {
111+ id: AppointmentSlotId,
112+ teacher: UserId,
113+ starts_at: Timestamp,
114+ ends_at: Timestamp,
115+ note: Option<SlotNote>,
116+ series: Option<SlotSeries>,
117+ created_at: Timestamp,
118+}
119+
120+impl AppointmentSlot {
121+ pub fn get_id(&self) -> &AppointmentSlotId {
122+ &self.id
123+ }
124+
125+ pub fn get_teacher(&self) -> &UserId {
126+ &self.teacher
127+ }
128+
129+ pub fn get_starts_at(&self) -> Timestamp {
130+ self.starts_at
131+ }
132+
133+ pub fn get_ends_at(&self) -> Timestamp {
134+ self.ends_at
135+ }
136+
137+ pub fn get_note(&self) -> Option<&SlotNote> {
138+ self.note.as_ref()
139+ }
140+
141+ pub fn get_series(&self) -> Option<&SlotSeries> {
142+ self.series.as_ref()
143+ }
144+
145+ pub fn get_created_at(&self) -> Timestamp {
146+ self.created_at
147+ }
148+
149+ /// A slot must cover a real span of time — an empty or inverted window
150+ /// could never be booked, and would break the touching-is-not-overlapping
151+ /// rule the conflict guard rests on.
152+ fn check_window(starts_at: Timestamp, ends_at: Timestamp) -> Result<(), ValidationError> {
153+ if starts_at.as_millis() >= ends_at.as_millis() {
154+ return Err(ValidationError::Invalid {
155+ field: "ends_at",
156+ reason: "must be after starts_at",
157+ });
158+ }
159+ Ok(())
160+ }
161+
162+ /// The concrete windows a weekly publish expands into: the first one, then
163+ /// the same time each following week, up to and including `until`.
164+ /// Pure — no clock, no database — so the caller can size the write before
165+ /// making it. Refuses more than [`MAX_SLOT_OCCURRENCES`] occurrences.
166+ pub fn weekly_windows(
167+ starts_at: Timestamp,
168+ ends_at: Timestamp,
169+ until: Timestamp,
170+ ) -> Result<Vec<(Timestamp, Timestamp)>, AppError> {
171+ Self::check_window(starts_at, ends_at)?;
172+ if until.as_millis() < starts_at.as_millis() {
173+ return Err(ValidationError::Invalid {
174+ field: "until",
175+ reason: "must not be before the first slot",
176+ }
177+ .into());
178+ }
179+ let count = (until.as_millis() - starts_at.as_millis()) / MILLIS_PER_WEEK + 1;
180+ if count > MAX_SLOT_OCCURRENCES as i64 {
181+ return Err(ValidationError::TooLong {
182+ field: "until",
183+ max: MAX_SLOT_OCCURRENCES,
184+ got: count as usize,
185+ }
186+ .into());
187+ }
188+ // Checked, not plain, arithmetic: `ends_at` is a caller-supplied i64 and
189+ // a window near `i64::MAX` overflows on the very first shift — which in
190+ // release wraps the end *below* the start, and an inverted window can
191+ // never overlap anything, silently disabling the double-booking guard.
192+ // Same spirit as `Timestamp::in_days`, but refusing instead of
193+ // saturating: a saturated end would still invert.
194+ let shifted = |base: Timestamp, week: i64| -> Option<Timestamp> {
195+ week.checked_mul(MILLIS_PER_WEEK)
196+ .and_then(|shift| base.as_millis().checked_add(shift))
197+ .map(Timestamp::from_millis)
198+ };
199+ (0..count)
200+ .map(|week| {
201+ let (starts_at, ends_at) = shifted(starts_at, week)
202+ .zip(shifted(ends_at, week))
203+ .ok_or(ValidationError::Invalid {
204+ field: "ends_at",
205+ reason: "is too far ahead to repeat weekly",
206+ })?;
207+ Self::check_window(starts_at, ends_at)?;
208+ Ok((starts_at, ends_at))
209+ })
210+ .collect()
211+ }
212+
213+ async fn insert(slot: AppointmentSlot, db: &Database) -> Result<AppointmentSlot, AppError> {
214+ let created: Option<AppointmentSlot> = db.create(slot.id.record()).content(slot).await?;
215+ created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into()))
216+ }
217+
218+ /// Publish one slot.
219+ pub async fn create(
220+ teacher: &UserId,
221+ starts_at: Timestamp,
222+ ends_at: Timestamp,
223+ note: Option<SlotNote>,
224+ db: &Database,
225+ ) -> Result<AppointmentSlot, AppError> {
226+ Self::check_window(starts_at, ends_at)?;
227+ Self::insert(
228+ AppointmentSlot {
229+ id: AppointmentSlotId::generate(),
230+ teacher: teacher.clone(),
231+ starts_at,
232+ ends_at,
233+ note,
234+ series: None,
235+ created_at: Timestamp::now(),
236+ },
237+ db,
238+ )
239+ .await
240+ }
241+
242+ /// Publish the same weekly window repeatedly, up to `until`. Every row
243+ /// carries the same [`SlotSeries`], so the whole publish stays addressable
244+ /// (and deletable) as one thing while each occurrence remains an ordinary,
245+ /// independently bookable and independently cancellable slot.
246+ pub async fn publish_weekly(
247+ teacher: &UserId,
248+ starts_at: Timestamp,
249+ ends_at: Timestamp,
250+ note: Option<SlotNote>,
251+ until: Timestamp,
252+ db: &Database,
253+ ) -> Result<Vec<AppointmentSlot>, AppError> {
254+ let windows = Self::weekly_windows(starts_at, ends_at, until)?;
255+ let series = SlotSeries::generate();
256+ let now = Timestamp::now();
257+ let mut slots = Vec::with_capacity(windows.len());
258+ for (starts_at, ends_at) in windows {
259+ slots.push(
260+ Self::insert(
261+ AppointmentSlot {
262+ id: AppointmentSlotId::generate(),
263+ teacher: teacher.clone(),
264+ starts_at,
265+ ends_at,
266+ note: note.clone(),
267+ series: Some(series.clone()),
268+ created_at: now,
269+ },
270+ db,
271+ )
272+ .await?,
273+ );
274+ }
275+ Ok(slots)
276+ }
277+
278+ pub async fn read(
279+ id: &AppointmentSlotId,
280+ db: &Database,
281+ ) -> Result<Option<AppointmentSlot>, AppError> {
282+ Ok(db.select(id.record()).await?)
283+ }
284+
285+ /// A teacher's own calendar, earliest first.
286+ pub async fn list_for_teacher(
287+ teacher: &UserId,
288+ db: &Database,
289+ ) -> Result<Vec<AppointmentSlot>, AppError> {
290+ let mut result = db
291+ .query(
292+ "SELECT * FROM appointment_slot WHERE teacher = $teacher \
293+ ORDER BY starts_at ASC, id ASC",
294+ )
295+ .bind(("teacher", teacher.record()))
296+ .await?
297+ .check()?;
298+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
299+ }
300+
301+ /// Every slot published from `starts_at` onwards, earliest first — the
302+ /// bookable calendar a requester browses.
303+ pub async fn list_upcoming(
304+ from: Timestamp,
305+ db: &Database,
306+ ) -> Result<Vec<AppointmentSlot>, AppError> {
307+ let mut result = db
308+ .query(
309+ "SELECT * FROM appointment_slot WHERE ends_at > $from \
310+ ORDER BY starts_at ASC, id ASC",
311+ )
312+ .bind(("from", from.as_millis()))
313+ .await?
314+ .check()?;
315+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
316+ }
317+
318+ pub async fn list_for_series(
319+ series: &SlotSeries,
320+ db: &Database,
321+ ) -> Result<Vec<AppointmentSlot>, AppError> {
322+ let mut result = db
323+ .query(
324+ "SELECT * FROM appointment_slot WHERE series = $series \
325+ ORDER BY starts_at ASC, id ASC",
326+ )
327+ .bind(("series", series.as_str().to_string()))
328+ .await?
329+ .check()?;
330+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
331+ }
332+
333+ /// Delete one slot, refusing (409) while a live booking sits on it — the
334+ /// requester is expecting that meeting, so it must be rejected first.
335+ /// Settled bookings (rejected/cancelled) are history of a slot that is
336+ /// going away, so they cascade out with it, like [`Event::delete`]'s rows.
337+ ///
338+ /// The occupancy read and the delete run under [`APPOINTMENT_LOCK`], so a
339+ /// booking cannot land between them and outlive its slot.
340+ pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {
341+ let _guard = APPOINTMENT_LOCK.lock().await;
342+ Self::delete_locked(std::slice::from_ref(&self.id), db).await?;
343+ Ok(self)
344+ }
345+
346+ /// Delete a whole recurring publish, all-or-nothing: if *any* occurrence
347+ /// still holds a live booking the entire series is refused, so the teacher
348+ /// deals with the person waiting instead of silently keeping a stray week.
349+ pub async fn delete_series(
350+ series: &SlotSeries,
351+ db: &Database,
352+ ) -> Result<Vec<AppointmentSlot>, AppError> {
353+ let _guard = APPOINTMENT_LOCK.lock().await;
354+ let slots = Self::list_for_series(series, db).await?;
355+ if slots.is_empty() {
356+ return Err(AppError::NotFound);
357+ }
358+ let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();
359+ Self::delete_locked(&ids, db).await?;
360+ Ok(slots)
361+ }
362+
363+ /// Shared body of both deletes. Caller must already hold
364+ /// [`APPOINTMENT_LOCK`]: the live-booking check is only meaningful while
365+ /// no booking can be written.
366+ async fn delete_locked(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> {
367+ for id in ids {
368+ if Appointment::has_live_booking(id, db).await? {
369+ return Err(AppError::Conflict(
370+ "the slot has a pending or approved booking",
371+ ));
372+ }
373+ }
374+ let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
375+ let mut result = db
376+ .query("DELETE appointment WHERE slot IN $slots; DELETE $slots RETURN BEFORE;")
377+ .bind(("slots", records))
378+ .await?
379+ .check()?;
380+ if result.take::<Vec<AppointmentSlot>>(1)?.is_empty() {
381+ return Err(AppError::NotFound);
382+ }
383+ Ok(())
384+ }
385+}
386+
387+#[cfg(test)]
388+mod tests {
389+ use super::*;
390+
391+ fn at(millis: i64) -> Timestamp {
392+ Timestamp::from_millis(millis)
393+ }
394+
395+ #[tokio::test]
396+ async fn note_is_optional_and_capped() {
397+ assert!(SlotNote::try_new("").is_ok());
398+ assert!(SlotNote::try_new(&"x".repeat(MAX_APPOINTMENT_NOTE_LEN)).is_ok());
399+ assert!(SlotNote::try_new(&"x".repeat(MAX_APPOINTMENT_NOTE_LEN + 1)).is_err());
400+ }
401+
402+ #[tokio::test]
403+ async fn window_must_be_a_real_span() {
404+ assert!(AppointmentSlot::check_window(at(10), at(20)).is_ok());
405+ assert!(AppointmentSlot::check_window(at(20), at(20)).is_err());
406+ assert!(AppointmentSlot::check_window(at(21), at(20)).is_err());
407+ }
408+
409+ #[tokio::test]
410+ async fn weekly_expansion_counts_whole_weeks_inclusive() {
411+ let start = at(0);
412+ let end = at(MILLIS_PER_DAY / 24);
413+ // `until` on the third occurrence's own start — that week is included.
414+ let windows = AppointmentSlot::weekly_windows(start, end, at(2 * MILLIS_PER_WEEK)).unwrap();
415+ assert_eq!(windows.len(), 3);
416+ assert_eq!(windows[2].0.as_millis(), 2 * MILLIS_PER_WEEK);
417+ assert_eq!(
418+ windows[2].1.as_millis(),
419+ 2 * MILLIS_PER_WEEK + MILLIS_PER_DAY / 24
420+ );
421+ // One millisecond short of the next week does not add an occurrence.
422+ assert_eq!(
423+ AppointmentSlot::weekly_windows(start, end, at(3 * MILLIS_PER_WEEK - 1))
424+ .unwrap()
425+ .len(),
426+ 3
427+ );
428+ // A single-shot week is still one occurrence.
429+ assert_eq!(
430+ AppointmentSlot::weekly_windows(start, end, start)
431+ .unwrap()
432+ .len(),
433+ 1
434+ );
435+ assert!(AppointmentSlot::weekly_windows(at(MILLIS_PER_WEEK), end, at(0)).is_err());
436+ }
437+
438+ #[tokio::test]
439+ async fn weekly_expansion_refuses_more_than_the_cap() {
440+ let start = at(0);
441+ let end = at(1_000);
442+ let last_ok = at((MAX_SLOT_OCCURRENCES as i64 - 1) * MILLIS_PER_WEEK);
443+ assert_eq!(
444+ AppointmentSlot::weekly_windows(start, end, last_ok)
445+ .unwrap()
446+ .len(),
447+ MAX_SLOT_OCCURRENCES
448+ );
449+ assert!(matches!(
450+ AppointmentSlot::weekly_windows(start, end, at(last_ok.as_millis() + MILLIS_PER_WEEK)),
451+ Err(AppError::Validation(ValidationError::TooLong { .. }))
452+ ));
453+ }
454+
455+ /// A window ending near `i64::MAX` overflows on the first weekly shift.
456+ /// Unchecked, release builds wrapped the end *below* the start and stored
457+ /// inverted windows, which `Appointment::overlaps` can never flag — the
458+ /// double-booking guard would have gone quietly blind.
459+ #[tokio::test]
460+ async fn a_shift_that_would_overflow_is_refused() {
461+ let now = Timestamp::now();
462+ assert!(matches!(
463+ AppointmentSlot::weekly_windows(
464+ now,
465+ at(i64::MAX),
466+ at(now.as_millis() + 51 * MILLIS_PER_WEEK),
467+ ),
468+ Err(AppError::Validation(ValidationError::Invalid {
469+ field: "ends_at",
470+ ..
471+ }))
472+ ));
473+ // The un-shifted first occurrence alone is still fine.
474+ assert_eq!(
475+ AppointmentSlot::weekly_windows(now, at(i64::MAX), now)
476+ .unwrap()
477+ .len(),
478+ 1
479+ );
480+ }
481+
482+ /// Every occurrence of one publish must carry the same series id, and ids
483+ /// minted back-to-back must stay in write order (the `ORDER BY` tie-break).
484+ #[tokio::test]
485+ async fn a_publish_shares_one_series_and_orders_its_ids() {
486+ let db = crate::database::init_mem().await.unwrap();
487+ let teacher = UserId::from_key("t1");
488+ let slots = AppointmentSlot::publish_weekly(
489+ &teacher,
490+ at(1_000),
491+ at(2_000),
492+ Some(SlotNote::try_new("veli toplantısı").unwrap()),
493+ at(1_000 + 4 * MILLIS_PER_WEEK),
494+ &db,
495+ )
496+ .await
497+ .unwrap();
498+
499+ assert_eq!(slots.len(), 5);
500+ let series = slots[0].get_series().cloned().unwrap();
501+ assert!(slots.iter().all(|slot| slot.get_series() == Some(&series)));
502+ assert!(
503+ slots
504+ .windows(2)
505+ .all(|pair| pair[0].get_id().key() < pair[1].get_id().key())
506+ );
507+
508+ let listed = AppointmentSlot::list_for_series(&series, &db)
509+ .await
510+ .unwrap();
511+ assert_eq!(listed.len(), 5);
512+ }
513+}
src/domain/mod.rsmodified+2 -0
@@ -3,6 +3,8 @@
33 //! same typed value flows from HTTP input all the way into the database.
44
55 pub mod answer_image;
6+pub mod appointment;
7+pub mod appointment_slot;
68 pub mod attendance;
79 pub mod chat_message;
810 pub mod conversation;
src/lib.rsmodified+3 -1
@@ -35,7 +35,7 @@ use crate::state::AppState;
3535 info(
3636 title = "Hezarfen Backend API",
3737 version = env!("CARGO_PKG_VERSION"),
38- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
38+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); either side may cancel until the meeting starts, one live booking holds a slot, and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
3939 ),
4040 modifiers(&SecurityAddon),
4141 tags(
@@ -46,6 +46,7 @@ use crate::state::AppState;
4646 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). 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), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"),
4747 (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`)"),
4848 (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`/`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"),
49+ (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). 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, an underway time cannot be approved, accepted, or counter-proposed, and either side may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. 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"),
4950 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),
5051 (name = "courses", description = "Courses — kind `course` (regular class), `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. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
5152 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
@@ -94,6 +95,7 @@ pub fn build_router(state: AppState) -> Router {
9495 .nest("/notes", web::notes::routes())
9596 .nest("/messages", web::messages::routes())
9697 .nest("/events", web::events::routes())
98+ .nest("/appointments", web::appointments::routes())
9799 .nest("/courses", web::courses::routes())
98100 .nest("/sessions", web::sessions::routes())
99101 .nest("/exams", web::exams::routes())
src/web/appointments.rsadded+740 -0
@@ -0,0 +1,740 @@
1+use std::collections::{HashMap, HashSet};
2+
3+use axum::Json;
4+use axum::extract::{Path, Query, State};
5+use axum::http::StatusCode;
6+use serde::{Deserialize, Serialize};
7+use utoipa::ToSchema;
8+use utoipa_axum::router::OpenApiRouter;
9+use utoipa_axum::routes;
10+
11+use crate::database::Database;
12+use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason};
13+use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
14+use crate::domain::role::Role;
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::{User, UserId};
17+use crate::error::{AppError, ErrorResponse, ValidationError};
18+use crate::state::AppState;
19+
20+use super::{
21+ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range,
22+ paginate, person_map,
23+};
24+
25+pub fn routes() -> OpenApiRouter<AppState> {
26+ OpenApiRouter::new()
27+ .routes(routes!(publish_slots, list_slots))
28+ .routes(routes!(delete_slot))
29+ .routes(routes!(delete_slot_series))
30+ .routes(routes!(book, list_appointments))
31+ .routes(routes!(approve))
32+ .routes(routes!(reject))
33+ .routes(routes!(cancel))
34+ .routes(routes!(reschedule))
35+ .routes(routes!(accept_reschedule))
36+ .routes(routes!(decline_reschedule))
37+}
38+
39+#[derive(Deserialize, ToSchema)]
40+struct PublishSlots {
41+ /// Unix-millisecond timestamps. Must not be in the past.
42+ #[schema(example = 1_900_000_000_000_i64)]
43+ starts_at: i64,
44+ ends_at: i64,
45+ /// Free-text hint shown to requesters ("office hours", "veli görüşmesi").
46+ note: Option<String>,
47+ /// Repeat the same window every week up to and including `until`.
48+ #[serde(default)]
49+ repeat_weekly: bool,
50+ /// Required with `repeat_weekly`, ignored without it. Unix-milliseconds,
51+ /// not in the past; at most 52 occurrences may be expanded.
52+ until: Option<i64>,
53+}
54+
55+#[derive(Deserialize, ToSchema)]
56+struct BookAppointment {
57+ /// The slot to take, from `GET /appointments/slots`.
58+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
59+ slot: String,
60+ /// Why you want the meeting — required, the teacher decides on it.
61+ #[schema(example = "Ders notlarını konuşmak istiyorum")]
62+ reason: String,
63+}
64+
65+#[derive(Deserialize, ToSchema)]
66+struct Reschedule {
67+ /// Unix-millisecond timestamps. Must not be in the past.
68+ #[schema(example = 1_900_000_000_000_i64)]
69+ starts_at: i64,
70+ ends_at: i64,
71+}
72+
73+#[derive(Serialize, ToSchema)]
74+struct SlotResponse {
75+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
76+ id: String,
77+ /// Whose calendar this is.
78+ teacher: PersonRef,
79+ /// Window open/close, UTC unix-milliseconds. Half-open: back-to-back slots
80+ /// (10:00–10:30, 10:30–11:00) do not collide.
81+ starts_at: i64,
82+ ends_at: i64,
83+ note: Option<String>,
84+ /// The recurring publish this occurrence came from; `null` for a one-off.
85+ /// `DELETE /appointments/slots/series/{series}` drops the whole group.
86+ series: Option<String>,
87+ created_at: i64,
88+}
89+
90+impl SlotResponse {
91+ fn new(slot: &AppointmentSlot, people: &HashMap<String, PersonRef>) -> Self {
92+ Self {
93+ id: slot.get_id().key().to_string(),
94+ teacher: PersonRef::resolve(people, slot.get_teacher()),
95+ starts_at: slot.get_starts_at().as_millis(),
96+ ends_at: slot.get_ends_at().as_millis(),
97+ note: slot.get_note().map(|note| note.as_str().to_string()),
98+ series: slot.get_series().map(|series| series.as_str().to_string()),
99+ created_at: slot.get_created_at().as_millis(),
100+ }
101+ }
102+}
103+
104+#[derive(Serialize, ToSchema)]
105+struct AppointmentResponse {
106+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
107+ id: String,
108+ /// The slot this booking sits on.
109+ slot: String,
110+ /// Whose slot it is; `null` only if that slot has since vanished.
111+ teacher: Option<PersonRef>,
112+ /// Who asked for the meeting (a student or a parent).
113+ requester: PersonRef,
114+ /// `pending`, `approved`, `rejected`, or `cancelled`. Only the first two
115+ /// hold the slot — rejecting or cancelling frees it for someone else.
116+ #[schema(example = "pending")]
117+ status: String,
118+ reason: String,
119+ /// When the meeting actually happens, UTC unix-milliseconds: the accepted
120+ /// counter-proposal when there is one, the slot's own window otherwise.
121+ starts_at: Option<i64>,
122+ ends_at: Option<i64>,
123+ /// A standing counter-proposal awaiting the requester's answer.
124+ proposed_starts_at: Option<i64>,
125+ proposed_ends_at: Option<i64>,
126+ proposed_by: Option<PersonRef>,
127+ /// Who approved or rejected it; `null` while pending.
128+ decided_by: Option<PersonRef>,
129+ created_at: i64,
130+}
131+
132+impl AppointmentResponse {
133+ fn new(
134+ appointment: &Appointment,
135+ slot: Option<&AppointmentSlot>,
136+ people: &HashMap<String, PersonRef>,
137+ ) -> Self {
138+ let window = slot.map(|slot| appointment.window(slot));
139+ Self {
140+ id: appointment.get_id().key().to_string(),
141+ slot: appointment.get_slot().key().to_string(),
142+ teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())),
143+ requester: PersonRef::resolve(people, appointment.get_requester()),
144+ status: appointment.get_status().as_str().to_string(),
145+ reason: appointment.get_reason().as_str().to_string(),
146+ starts_at: window.map(|(starts_at, _)| starts_at.as_millis()),
147+ ends_at: window.map(|(_, ends_at)| ends_at.as_millis()),
148+ proposed_starts_at: appointment.get_proposed_starts_at().map(|t| t.as_millis()),
149+ proposed_ends_at: appointment.get_proposed_ends_at().map(|t| t.as_millis()),
150+ proposed_by: appointment
151+ .get_proposed_by()
152+ .map(|id| PersonRef::resolve(people, id)),
153+ decided_by: appointment
154+ .get_decided_by()
155+ .map(|id| PersonRef::resolve(people, id)),
156+ created_at: appointment.get_created_at().as_millis(),
157+ }
158+ }
159+}
160+
161+/// Join slots and people onto a run of bookings. The slot read is per row, so
162+/// callers pass the page they are about to render, not the whole list.
163+async fn appointment_responses(
164+ rows: &[Appointment],
165+ db: &Database,
166+) -> Result<Vec<AppointmentResponse>, AppError> {
167+ let mut slots = Vec::with_capacity(rows.len());
168+ for row in rows {
169+ slots.push(AppointmentSlot::read(row.get_slot(), db).await?);
170+ }
171+ // Collected eagerly rather than as a lazy iterator: a borrowing closure
172+ // held across the `person_map` await makes the handler's future
173+ // higher-ranked, which axum then refuses as not `Send` enough.
174+ let mut ids = Vec::with_capacity(rows.len() * 2);
175+ for (row, slot) in rows.iter().zip(&slots) {
176+ ids.push(row.get_requester().clone());
177+ ids.extend(slot.as_ref().map(|slot| slot.get_teacher().clone()));
178+ ids.extend(row.get_proposed_by().cloned());
179+ ids.extend(row.get_decided_by().cloned());
180+ }
181+ let people = person_map(ids, db).await?;
182+ Ok(rows
183+ .iter()
184+ .zip(&slots)
185+ .map(|(row, slot)| AppointmentResponse::new(row, slot.as_ref(), &people))
186+ .collect())
187+}
188+
189+/// The single-row form of [`appointment_responses`] — one rendering path, so a
190+/// mutation's response can never drift from the list's.
191+async fn one_appointment(
192+ appointment: Appointment,
193+ db: &Database,
194+) -> Result<Json<AppointmentResponse>, AppError> {
195+ appointment_responses(std::slice::from_ref(&appointment), db)
196+ .await?
197+ .pop()
198+ .map(Json)
199+ .ok_or_else(|| AppError::Internal("failed to render the appointment".into()))
200+}
201+
202+/// Who may act on a slot (and on the bookings sitting on it): the teacher who
203+/// published it, or anyone `manager` and above. This asks about *ownership*
204+/// only — it does not re-check the role bar, and `cancel` reaches it from a
205+/// plain `CurrentUser` handler. So a slot owner demoted to student or parent
206+/// still passes here and can cancel bookings on their now-inert slot; that is
207+/// deliberate — the slot is unbookable anyway (`book` refuses it) and calling
208+/// off a meeting they can no longer hold is the right outcome.
209+fn can_manage(slot: &AppointmentSlot, user: &User) -> bool {
210+ slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager)
211+}
212+
213+/// The booking plus the slot it sits on, insisting the caller may decide it.
214+async fn for_decision(
215+ id: &AppointmentId,
216+ user: &User,
217+ db: &Database,
218+) -> Result<Appointment, AppError> {
219+ let appointment = Appointment::read(id, db).await?.ok_or(AppError::NotFound)?;
220+ let slot = AppointmentSlot::read(appointment.get_slot(), db)
221+ .await?
222+ .ok_or(AppError::NotFound)?;
223+ if !can_manage(&slot, user) {
224+ return Err(AppError::Forbidden(
225+ "only the slot's teacher or a manager/admin can decide this appointment",
226+ ));
227+ }
228+ Ok(appointment)
229+}
230+
231+// ---- slots ----------------------------------------------------------------
232+
233+/// Publish availability. Requires the `teacher` role or higher; the slot lands
234+/// on the caller's own calendar. With `repeat_weekly` the same window is
235+/// expanded into one row per week up to and including `until` (at most 52),
236+/// all sharing a `series` id — each occurrence is then independently bookable
237+/// and independently deletable. The response is always an array: one element
238+/// for a one-off publish, one per occurrence for a weekly one.
239+#[utoipa::path(
240+ post,
241+ path = "/slots",
242+ tag = "appointments",
243+ security(("session_cookie" = [])),
244+ request_body = PublishSlots,
245+ responses(
246+ (status = 201, description = "Slots published", body = Vec<SlotResponse>),
247+ (status = 400, description = "Invalid note, time range, times in the past, `until` missing with `repeat_weekly`, more than 52 occurrences, or a window too far ahead to shift by a week", body = ErrorResponse),
248+ (status = 401, description = "Not authenticated", body = ErrorResponse),
249+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
250+ ),
251+)]
252+async fn publish_slots(
253+ State(st): State<AppState>,
254+ RequireTeacher(user): RequireTeacher,
255+ Json(req): Json<PublishSlots>,
256+) -> Result<(StatusCode, Json<Vec<SlotResponse>>), AppError> {
257+ let note = match req.note {
258+ Some(ref note) => Some(SlotNote::try_new(note)?),
259+ None => None,
260+ };
261+ let starts_at = Timestamp::from_millis(req.starts_at);
262+ let ends_at = Timestamp::from_millis(req.ends_at);
263+ check_not_past("starts_at", Some(starts_at))?;
264+ check_not_past("ends_at", Some(ends_at))?;
265+ check_time_range(Some(starts_at), Some(ends_at))?;
266+
267+ let slots = if req.repeat_weekly {
268+ let until = req
269+ .until
270+ .map(Timestamp::from_millis)
271+ .ok_or(AppError::Validation(ValidationError::Invalid {
272+ field: "until",
273+ reason: "is required with repeat_weekly",
274+ }))?;
275+ check_not_past("until", Some(until))?;
276+ AppointmentSlot::publish_weekly(user.get_id(), starts_at, ends_at, note, until, &st.db)
277+ .await?
278+ } else {
279+ vec![AppointmentSlot::create(user.get_id(), starts_at, ends_at, note, &st.db).await?]
280+ };
281+
282+ let people = PersonRef::map_of(&[&user]);
283+ let items = slots
284+ .iter()
285+ .map(|slot| SlotResponse::new(slot, &people))
286+ .collect();
287+ Ok((StatusCode::CREATED, Json(items)))
288+}
289+
290+/// List slots, earliest first. Teacher+ see their own calendar, past occurrences
291+/// included; everyone else sees every slot still open in the future — the
292+/// bookable calendar. A slot whose teacher has since been demoted is left out
293+/// (and refused at book time). Whether a slot is already taken is not carried
294+/// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit
295+/// `limit` for every slot); returns a `{items, total, limit, offset}` envelope.
296+// ponytail: occupancy would be one query per slot with today's domain API; a
297+// batch "live bookings for these slots" read would let the list carry it.
298+#[utoipa::path(
299+ get,
300+ path = "/slots",
301+ tag = "appointments",
302+ security(("session_cookie" = [])),
303+ params(PageParams),
304+ responses(
305+ (status = 200, description = "A page of slots (all of them when unpaged)", body = Page<SlotResponse>),
306+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
307+ (status = 401, description = "Not authenticated", body = ErrorResponse),
308+ ),
309+)]
310+async fn list_slots(
311+ State(st): State<AppState>,
312+ CurrentUser(user): CurrentUser,
313+ Query(page): Query<PageParams>,
314+) -> Result<Json<Page<SlotResponse>>, AppError> {
315+ let (limit, offset) = page.resolve()?;
316+ let (slots, people) = if user.get_role().at_least(Role::Teacher) {
317+ (
318+ AppointmentSlot::list_for_teacher(user.get_id(), &st.db).await?,
319+ PersonRef::map_of(&[&user]),
320+ )
321+ } else {
322+ let mut slots = AppointmentSlot::list_upcoming(Timestamp::now(), &st.db).await?;
323+ // The teachers' live rows, not the slots' word for it: a demotion
324+ // leaves the calendar behind, and an inert slot must not be offered.
325+ // Keying the person map off that same read makes the filter free.
326+ let mut seen = HashSet::new();
327+ let teachers: Vec<UserId> = slots
328+ .iter()
329+ .map(AppointmentSlot::get_teacher)
330+ .filter(|teacher| seen.insert(teacher.key().to_string()))
331+ .cloned()
332+ .collect();
333+ let people: HashMap<String, PersonRef> = User::list_by_ids(&teachers, &st.db)
334+ .await?
335+ .iter()
336+ .filter(|teacher| teacher.get_role().at_least(Role::Teacher))
337+ .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher)))
338+ .collect();
339+ slots.retain(|slot| people.contains_key(slot.get_teacher().key()));
340+ (slots, people)
341+ };
342+ let total = slots.len() as i64;
343+ let items = paginate(&slots, limit, offset)
344+ .iter()
345+ .map(|slot| SlotResponse::new(slot, &people))
346+ .collect();
347+ Ok(Json(Page::new(items, total, limit, offset)))
348+}
349+
350+/// Withdraw one slot. Requires teacher+; the publishing teacher may drop their
351+/// own and managers/admins anyone's. A slot carrying a pending or approved
352+/// booking is refused (`409`) — reject or cancel that booking first. Settled
353+/// bookings (rejected/cancelled) go with the slot.
354+#[utoipa::path(
355+ delete,
356+ path = "/slots/{id}",
357+ tag = "appointments",
358+ security(("session_cookie" = [])),
359+ params(("id" = String, Path, description = "Slot id")),
360+ responses(
361+ (status = 204, description = "Deleted"),
362+ (status = 401, description = "Not authenticated", body = ErrorResponse),
363+ (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
364+ (status = 404, description = "Not found", body = ErrorResponse),
365+ (status = 409, description = "The slot has a pending or approved booking", body = ErrorResponse),
366+ ),
367+)]
368+async fn delete_slot(
369+ State(st): State<AppState>,
370+ RequireTeacher(user): RequireTeacher,
371+ Path(id): Path<String>,
372+) -> Result<StatusCode, AppError> {
373+ let slot = AppointmentSlot::read(&AppointmentSlotId::from_key(&id), &st.db)
374+ .await?
375+ .ok_or(AppError::NotFound)?;
376+ if !can_manage(&slot, &user) {
377+ return Err(AppError::Forbidden(
378+ "only the slot's teacher or a manager/admin can delete it",
379+ ));
380+ }
381+ slot.delete(&st.db).await?;
382+ Ok(StatusCode::NO_CONTENT)
383+}
384+
385+/// Withdraw a whole recurring publish. Same rights as the single delete, and
386+/// all-or-nothing: if *any* occurrence still carries a pending or approved
387+/// booking the entire series is refused (`409`), so the person waiting is dealt
388+/// with rather than silently left on a stray week.
389+#[utoipa::path(
390+ delete,
391+ path = "/slots/series/{series}",
392+ tag = "appointments",
393+ security(("session_cookie" = [])),
394+ params(("series" = String, Path, description = "Series id, from a slot's `series` field")),
395+ responses(
396+ (status = 204, description = "Deleted"),
397+ (status = 401, description = "Not authenticated", body = ErrorResponse),
398+ (status = 403, description = "Not the series' teacher (and not a manager/admin)", body = ErrorResponse),
399+ (status = 404, description = "No such series", body = ErrorResponse),
400+ (status = 409, description = "Some occurrence has a pending or approved booking", body = ErrorResponse),
401+ ),
402+)]
403+async fn delete_slot_series(
404+ State(st): State<AppState>,
405+ RequireTeacher(user): RequireTeacher,
406+ Path(series): Path<String>,
407+) -> Result<StatusCode, AppError> {
408+ let series = SlotSeries::from_key(&series);
409+ // Every occurrence of one publish carries the same teacher, so the first
410+ // row answers the ownership question for all of them.
411+ let slot = AppointmentSlot::list_for_series(&series, &st.db)
412+ .await?
413+ .into_iter()
414+ .next()
415+ .ok_or(AppError::NotFound)?;
416+ if !can_manage(&slot, &user) {
417+ return Err(AppError::Forbidden(
418+ "only the slot's teacher or a manager/admin can delete it",
419+ ));
420+ }
421+ AppointmentSlot::delete_series(&series, &st.db).await?;
422+ Ok(StatusCode::NO_CONTENT)
423+}
424+
425+// ---- bookings -------------------------------------------------------------
426+
427+/// Ask for a meeting on a published slot. Students and parents only — a parent
428+/// books for *themselves* (this is the parent-teacher conference), never on
429+/// behalf of a child, and staff arrange between themselves off this API. The
430+/// booking lands `pending`: publishing availability is not consent to a
431+/// particular person and topic. Refused (`409`) when the slot's window has already
432+/// opened, when it is already taken, when the requester is already committed at
433+/// that time, or when the slot's teacher no longer holds a teaching role.
434+#[utoipa::path(
435+ post,
436+ path = "/",
437+ tag = "appointments",
438+ security(("session_cookie" = [])),
439+ request_body = BookAppointment,
440+ responses(
441+ (status = 201, description = "Booking requested", body = AppointmentResponse),
442+ (status = 400, description = "Missing or over-long reason", body = ErrorResponse),
443+ (status = 401, description = "Not authenticated", body = ErrorResponse),
444+ (status = 403, description = "Only students and parents book appointments", body = ErrorResponse),
445+ (status = 404, description = "Slot not found", body = ErrorResponse),
446+ (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse),
447+ ),
448+)]
449+async fn book(
450+ State(st): State<AppState>,
451+ CurrentUser(user): CurrentUser,
452+ Json(req): Json<BookAppointment>,
453+) -> Result<(StatusCode, Json<AppointmentResponse>), AppError> {
454+ if !matches!(user.get_role(), Role::Student | Role::Parent) {
455+ return Err(AppError::Forbidden(
456+ "only students and parents can book an appointment",
457+ ));
458+ }
459+ let slot_id = AppointmentSlotId::from_key(&req.slot);
460+ let slot = AppointmentSlot::read(&slot_id, &st.db)
461+ .await?
462+ .ok_or(AppError::NotFound)?;
463+ // The slot row is not the grant: a teacher demoted since publishing keeps
464+ // their rows, and those rows must be inert. Their live role decides.
465+ if !User::read(slot.get_teacher(), &st.db)
466+ .await?
467+ .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher))
468+ {
469+ return Err(AppError::Conflict(
470+ "the slot's teacher no longer holds a teaching role",
471+ ));
472+ }
473+ let reason = AppointmentReason::try_new(&req.reason)?;
474+ let appointment = Appointment::book(&slot_id, user.get_id(), reason, &st.db).await?;
475+ Ok((
476+ StatusCode::CREATED,
477+ one_appointment(appointment, &st.db).await?,
478+ ))
479+}
480+
481+/// List bookings, newest first. Students and parents see the ones they
482+/// requested; teacher+ see the ones aimed at their own slots — their request
483+/// inbox. Managers and admins read their own inbox too (they may still decide
484+/// any booking by id). Paged via `?limit=&offset=` (omit `limit` for every
485+/// booking); returns a `{items, total, limit, offset}` envelope.
486+#[utoipa::path(
487+ get,
488+ path = "/",
489+ tag = "appointments",
490+ security(("session_cookie" = [])),
491+ params(PageParams),
492+ responses(
493+ (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<AppointmentResponse>),
494+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
495+ (status = 401, description = "Not authenticated", body = ErrorResponse),
496+ ),
497+)]
498+async fn list_appointments(
499+ State(st): State<AppState>,
500+ CurrentUser(user): CurrentUser,
501+ Query(page): Query<PageParams>,
502+) -> Result<Json<Page<AppointmentResponse>>, AppError> {
503+ let (limit, offset) = page.resolve()?;
504+ let rows = if user.get_role().at_least(Role::Teacher) {
505+ Appointment::list_for_teacher(user.get_id(), &st.db).await?
506+ } else {
507+ Appointment::list_for_requester(user.get_id(), &st.db).await?
508+ };
509+ let total = rows.len() as i64;
510+ // Join slots and people onto the page alone — the lookup shrinks with it.
511+ let items = appointment_responses(paginate(&rows, limit, offset), &st.db).await?;
512+ Ok(Json(Page::new(items, total, limit, offset)))
513+}
514+
515+/// Confirm a pending booking. Requires teacher+ and ownership of the slot (or
516+/// manager/admin). The double-booking guard runs here, against both sides:
517+/// approval is what commits anyone, so a time colliding with another approved
518+/// meeting of the teacher or of the requester is refused (`409`), as is a
519+/// window that has already started — that meeting could never be cancelled.
520+#[utoipa::path(
521+ patch,
522+ path = "/{id}/approve",
523+ tag = "appointments",
524+ security(("session_cookie" = [])),
525+ params(("id" = String, Path, description = "Appointment id")),
526+ responses(
527+ (status = 200, description = "Approved", body = AppointmentResponse),
528+ (status = 401, description = "Not authenticated", body = ErrorResponse),
529+ (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
530+ (status = 404, description = "Not found", body = ErrorResponse),
531+ (status = 409, description = "No longer pending, the time has already started, or it collides with another approved appointment", body = ErrorResponse),
532+ ),
533+)]
534+async fn approve(
535+ State(st): State<AppState>,
536+ RequireTeacher(user): RequireTeacher,
537+ Path(id): Path<String>,
538+) -> Result<Json<AppointmentResponse>, AppError> {
539+ let id = AppointmentId::from_key(&id);
540+ for_decision(&id, &user, &st.db).await?;
541+ let appointment = Appointment::approve(&id, user.get_id(), &st.db).await?;
542+ one_appointment(appointment, &st.db).await
543+}
544+
545+/// Turn a pending booking down. Requires teacher+ and ownership of the slot (or
546+/// manager/admin). The slot frees up immediately — occupancy counts live
547+/// bookings only, so someone else may take it.
548+#[utoipa::path(
549+ patch,
550+ path = "/{id}/reject",
551+ tag = "appointments",
552+ security(("session_cookie" = [])),
553+ params(("id" = String, Path, description = "Appointment id")),
554+ responses(
555+ (status = 200, description = "Rejected", body = AppointmentResponse),
556+ (status = 401, description = "Not authenticated", body = ErrorResponse),
557+ (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
558+ (status = 404, description = "Not found", body = ErrorResponse),
559+ (status = 409, description = "No longer pending", body = ErrorResponse),
560+ ),
561+)]
562+async fn reject(
563+ State(st): State<AppState>,
564+ RequireTeacher(user): RequireTeacher,
565+ Path(id): Path<String>,
566+) -> Result<Json<AppointmentResponse>, AppError> {
567+ let id = AppointmentId::from_key(&id);
568+ for_decision(&id, &user, &st.db).await?;
569+ let appointment = Appointment::reject(&id, user.get_id(), &st.db).await?;
570+ one_appointment(appointment, &st.db).await
571+}
572+
573+/// Call a meeting off. Either side may — the requester or the slot's teacher
574+/// (managers/admins too) — and from either live state, so an approved meeting
575+/// can still be dropped and the slot freed. Refused (`409`) once the meeting's
576+/// window has started: a meeting that already began is history, not a plan.
577+#[utoipa::path(
578+ patch,
579+ path = "/{id}/cancel",
580+ tag = "appointments",
581+ security(("session_cookie" = [])),
582+ params(("id" = String, Path, description = "Appointment id")),
583+ responses(
584+ (status = 200, description = "Cancelled", body = AppointmentResponse),
585+ (status = 401, description = "Not authenticated", body = ErrorResponse),
586+ (status = 403, description = "Neither the requester nor the slot's teacher", body = ErrorResponse),
587+ (status = 404, description = "Not found", body = ErrorResponse),
588+ (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse),
589+ ),
590+)]
591+async fn cancel(
592+ State(st): State<AppState>,
593+ CurrentUser(user): CurrentUser,
594+ Path(id): Path<String>,
595+) -> Result<Json<AppointmentResponse>, AppError> {
596+ let id = AppointmentId::from_key(&id);
597+ let appointment = Appointment::read(&id, &st.db)
598+ .await?
599+ .ok_or(AppError::NotFound)?;
600+ let slot = AppointmentSlot::read(appointment.get_slot(), &st.db)
601+ .await?
602+ .ok_or(AppError::NotFound)?;
603+ if appointment.get_requester() != user.get_id() && !can_manage(&slot, &user) {
604+ return Err(AppError::Forbidden(
605+ "only the requester or the slot's teacher can cancel this appointment",
606+ ));
607+ }
608+ // The started-window guard lives in `Appointment::cancel`, under the lock
609+ // and on a fresh read — a pre-lock copy of it here would only be a staler
610+ // second opinion, and `decline_reschedule` would still bypass it.
611+ let appointment = Appointment::cancel(&id, &st.db).await?;
612+ one_appointment(appointment, &st.db).await
613+}
614+
615+/// Counter-propose another time for a booking, on the same row (the reason and
616+/// the history stay in one place). Requires teacher+ and ownership of the slot
617+/// (or manager/admin).
618+///
619+/// **The proposal sends the booking back to `pending` and clears
620+/// `decided_by`** — an already-approved meeting is *not* committed at the new
621+/// time until the requester accepts it at
622+/// `PATCH /appointments/{id}/reschedule/accept`, since leaving it approved
623+/// would silently move a confirmed appointment. The slot stays held meanwhile.
624+///
625+/// Refused (`409`) when the proposed window has already opened — the 60-second
626+/// skew grace on the times is for clock drift, not for proposing into a meeting
627+/// that is already underway, which `cancel` would then refuse to undo.
628+#[utoipa::path(
629+ patch,
630+ path = "/{id}/reschedule",
631+ tag = "appointments",
632+ security(("session_cookie" = [])),
633+ params(("id" = String, Path, description = "Appointment id")),
634+ request_body = Reschedule,
635+ responses(
636+ (status = 200, description = "Proposed; the booking is pending again", body = AppointmentResponse),
637+ (status = 400, description = "Invalid time range or times in the past", body = ErrorResponse),
638+ (status = 401, description = "Not authenticated", body = ErrorResponse),
639+ (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
640+ (status = 404, description = "Not found", body = ErrorResponse),
641+ (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse),
642+ ),
643+)]
644+async fn reschedule(
645+ State(st): State<AppState>,
646+ RequireTeacher(user): RequireTeacher,
647+ Path(id): Path<String>,
648+ Json(req): Json<Reschedule>,
649+) -> Result<Json<AppointmentResponse>, AppError> {
650+ let starts_at = Timestamp::from_millis(req.starts_at);
651+ let ends_at = Timestamp::from_millis(req.ends_at);
652+ check_not_past("starts_at", Some(starts_at))?;
653+ check_not_past("ends_at", Some(ends_at))?;
654+ check_time_range(Some(starts_at), Some(ends_at))?;
655+
656+ let id = AppointmentId::from_key(&id);
657+ for_decision(&id, &user, &st.db).await?;
658+ let appointment = Appointment::propose(&id, starts_at, ends_at, user.get_id(), &st.db).await?;
659+ one_appointment(appointment, &st.db).await
660+}
661+
662+/// Accept the teacher's counter-proposal. The requester's call alone — it is
663+/// their commitment. Accepting *is* approval at the proposed time, so the
664+/// double-booking guard runs again for both sides (`409` if the moved time now
665+/// collides with something else, or has already started — agreeing to a window
666+/// that began would mint a meeting nobody can cancel).
667+#[utoipa::path(
668+ patch,
669+ path = "/{id}/reschedule/accept",
670+ tag = "appointments",
671+ security(("session_cookie" = [])),
672+ params(("id" = String, Path, description = "Appointment id")),
673+ responses(
674+ (status = 200, description = "Approved at the proposed time", body = AppointmentResponse),
675+ (status = 401, description = "Not authenticated", body = ErrorResponse),
676+ (status = 403, description = "Not the requester", body = ErrorResponse),
677+ (status = 404, description = "Not found", body = ErrorResponse),
678+ (status = 409, description = "No time has been proposed, the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse),
679+ ),
680+)]
681+async fn accept_reschedule(
682+ State(st): State<AppState>,
683+ CurrentUser(user): CurrentUser,
684+ Path(id): Path<String>,
685+) -> Result<Json<AppointmentResponse>, AppError> {
686+ let id = AppointmentId::from_key(&id);
687+ ensure_requester(&id, &user, &st.db).await?;
688+ let appointment = Appointment::accept_proposal(&id, user.get_id(), &st.db).await?;
689+ one_appointment(appointment, &st.db).await
690+}
691+
692+/// Refuse the teacher's counter-proposal. The requester's call alone, and it
693+/// **cancels the booking**: the proposal replaced the time that was asked for,
694+/// so there is nothing left to fall back to — book another slot instead. The
695+/// slot frees up, and the original request stays readable as `cancelled` with
696+/// the refused proposal still on it. Declining is a cancel, so it answers to
697+/// the same deadline: `409` once the meeting's effective window has started.
698+#[utoipa::path(
699+ patch,
700+ path = "/{id}/reschedule/decline",
701+ tag = "appointments",
702+ security(("session_cookie" = [])),
703+ params(("id" = String, Path, description = "Appointment id")),
704+ responses(
705+ (status = 200, description = "Cancelled", body = AppointmentResponse),
706+ (status = 401, description = "Not authenticated", body = ErrorResponse),
707+ (status = 403, description = "Not the requester", body = ErrorResponse),
708+ (status = 404, description = "Not found", body = ErrorResponse),
709+ (status = 409, description = "No time has been proposed, the booking is already settled, or the meeting's window has already started", body = ErrorResponse),
710+ ),
711+)]
712+async fn decline_reschedule(
713+ State(st): State<AppState>,
714+ CurrentUser(user): CurrentUser,
715+ Path(id): Path<String>,
716+) -> Result<Json<AppointmentResponse>, AppError> {
717+ let id = AppointmentId::from_key(&id);
718+ let appointment = ensure_requester(&id, &user, &st.db).await?;
719+ if appointment.get_proposed_starts_at().is_none() {
720+ return Err(AppError::Conflict("no time has been proposed"));
721+ }
722+ let appointment = Appointment::cancel(&id, &st.db).await?;
723+ one_appointment(appointment, &st.db).await
724+}
725+
726+/// The booking, insisting the caller is the person who asked for it — the only
727+/// one who can answer a counter-proposal.
728+async fn ensure_requester(
729+ id: &AppointmentId,
730+ user: &User,
731+ db: &Database,
732+) -> Result<Appointment, AppError> {
733+ let appointment = Appointment::read(id, db).await?.ok_or(AppError::NotFound)?;
734+ if appointment.get_requester() != user.get_id() {
735+ return Err(AppError::Forbidden(
736+ "only the requester can answer a counter-proposal",
737+ ));
738+ }
739+ Ok(appointment)
740+}
src/web/mod.rsmodified+1 -0
@@ -4,6 +4,7 @@
44 //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`.
55
66 pub mod ai;
7+pub mod appointments;
78 pub mod attendance;
89 pub mod auth;
910 pub mod chat;