use std::collections::{HashMap, HashSet}; use crate::web::tenant_state::State; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; use crate::domain::appointment::{ Appointment, AppointmentId, AppointmentReason, AppointmentStatus, }; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; use crate::state::AppState; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range, paginate, person_map, }; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(publish_slots, list_slots)) .routes(routes!(delete_slot)) .routes(routes!(delete_slot_series)) .routes(routes!(book, list_appointments)) .routes(routes!(approve)) .routes(routes!(reject)) .routes(routes!(cancel)) .routes(routes!(reschedule)) .routes(routes!(accept_reschedule)) .routes(routes!(decline_reschedule)) } #[derive(Deserialize, ToSchema)] struct PublishSlots { /// Unix-millisecond timestamps. Must not be in the past. #[schema(example = 1_900_000_000_000_i64)] starts_at: i64, ends_at: i64, /// Free-text hint shown to requesters ("office hours", "parent meeting"). #[schema(max_length = 500)] note: Option, /// Repeat the same window every week up to and including `until`. #[serde(default)] repeat_weekly: bool, /// Required with `repeat_weekly`, ignored without it. Unix-milliseconds, /// not in the past; at most 52 occurrences may be expanded. until: Option, } #[derive(Deserialize, ToSchema)] struct BookAppointment { /// The slot to take, from `GET /appointments/slots`. #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] slot: String, /// Why you want the meeting — required, the teacher decides on it. #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")] reason: String, } #[derive(Deserialize, ToSchema)] struct CancelRequest { /// Optional free-text reason. Blank or absent records no reason; over-long /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`. #[schema(max_length = 1000, example = "Rahatsızlandım, katılamayacağım")] reason: Option, } #[derive(Deserialize, ToSchema)] struct RejectRequest { /// Optional free-text reason. Blank or absent records no reason; over-long /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`. #[schema(max_length = 1000, example = "Bu saatte müsait değilim")] reason: Option, } #[derive(Deserialize, ToSchema)] struct Reschedule { /// Unix-millisecond timestamps. Must not be in the past. #[schema(example = 1_900_000_000_000_i64)] starts_at: i64, ends_at: i64, } #[derive(Deserialize, ToSchema)] struct AcceptReschedule { /// The proposal being accepted, copied from the booking's /// `proposed_starts_at`/`proposed_ends_at` as it was read. Not a request to /// move the meeting: it pins *which* proposal this answer is for, so one the /// teacher has since replaced answers `409` instead of committing you to a /// window you never saw. #[schema(example = 1_900_000_000_000_i64)] proposed_starts_at: i64, proposed_ends_at: i64, } #[derive(Serialize, ToSchema)] struct SlotResponse { #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, /// Whose calendar this is. teacher: PersonRef, /// Window open/close, UTC unix-milliseconds. Half-open: back-to-back slots /// (10:00–10:30, 10:30–11:00) do not collide. starts_at: i64, ends_at: i64, note: Option, /// The recurring publish this occurrence came from; `null` for a one-off. /// `DELETE /appointments/slots/series/{series}` drops the whole group. series: Option, created_at: i64, } impl SlotResponse { fn new(slot: &AppointmentSlot, people: &HashMap) -> Self { Self { id: slot.get_id().key().to_string(), teacher: PersonRef::resolve(people, slot.get_teacher()), starts_at: slot.get_starts_at().as_millis(), ends_at: slot.get_ends_at().as_millis(), note: slot.get_note().map(|note| note.as_str().to_string()), series: slot.get_series().map(|series| series.as_str().to_string()), created_at: slot.get_created_at().as_millis(), } } } #[derive(Serialize, ToSchema)] struct AppointmentResponse { #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, /// The slot this booking sits on. slot: String, /// Whose slot it is; `null` only if that slot has since vanished. teacher: Option, /// Who asked for the meeting (a student or a parent). requester: PersonRef, /// `pending`, `approved`, `rejected`, or `cancelled`. Only the first two /// hold the slot — rejecting or cancelling frees it for someone else. #[schema(example = "pending")] status: String, reason: String, /// When the meeting actually happens, UTC unix-milliseconds: the accepted /// counter-proposal when there is one, the slot's own window otherwise. starts_at: Option, ends_at: Option, /// A standing counter-proposal awaiting the requester's answer. proposed_starts_at: Option, proposed_ends_at: Option, proposed_by: Option, /// Who approved or rejected it; `null` while pending. decided_by: Option, /// Who called it off — the requester, or a requester declining a /// counter-proposal; `null` unless `status` is `cancelled`. cancelled_by: Option, /// Optional free-text reason given when cancelling; `null` when none was /// (a blank one records nothing). Bookings are only ever rendered to the /// requester and to the slot's teacher, so this audit trail goes no wider. cancel_reason: Option, /// Optional free-text reason given when rejecting; `null` when none was. /// The rejecter is on `decided_by`. Same audience as `cancel_reason`. reject_reason: Option, created_at: i64, } impl AppointmentResponse { fn new( appointment: &Appointment, slot: Option<&AppointmentSlot>, people: &HashMap, ) -> Self { let window = slot.map(|slot| appointment.window(slot)); Self { id: appointment.get_id().key().to_string(), // A settled booking whose slot was withdrawn renders without a // window and without a slot id — the dangling reference the old // store permitted, now an explicit NULL. slot: appointment .get_slot() .map(|slot| slot.key()) .unwrap_or_default(), teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())), requester: PersonRef::resolve(people, appointment.get_requester()), status: appointment.get_status().as_str().to_string(), reason: appointment.get_reason().as_str().to_string(), starts_at: window.map(|(starts_at, _)| starts_at.as_millis()), ends_at: window.map(|(_, ends_at)| ends_at.as_millis()), proposed_starts_at: appointment.get_proposed_starts_at().map(|t| t.as_millis()), proposed_ends_at: appointment.get_proposed_ends_at().map(|t| t.as_millis()), proposed_by: appointment .get_proposed_by() .map(|id| PersonRef::resolve(people, id)), decided_by: appointment .get_decided_by() .map(|id| PersonRef::resolve(people, id)), cancelled_by: appointment .get_cancelled_by() .map(|id| PersonRef::resolve(people, id)), cancel_reason: appointment .get_cancel_reason() .map(|reason| reason.as_str().to_string()), reject_reason: appointment .get_reject_reason() .map(|reason| reason.as_str().to_string()), created_at: appointment.get_created_at().as_millis(), } } } /// Join slots and people onto a run of bookings. The slot read is per row, so /// callers pass the page they are about to render, not the whole list. async fn appointment_responses( rows: &[Appointment], db: &Database, ) -> Result, AppError> { let mut slots = Vec::with_capacity(rows.len()); for row in rows { let slot = match row.get_slot() { Some(slot_id) => service::appointment_slot::read(db, slot_id).await?, // A settled booking whose slot was withdrawn: no window. None => None, }; slots.push(slot); } // Collected eagerly rather than as a lazy iterator: a borrowing closure // held across the `person_map` await makes the handler's future // higher-ranked, which axum then refuses as not `Send` enough. let mut ids = Vec::with_capacity(rows.len() * 2); for (row, slot) in rows.iter().zip(&slots) { ids.push(*row.get_requester()); ids.extend(slot.as_ref().map(|slot| *slot.get_teacher())); ids.extend(row.get_proposed_by().cloned()); ids.extend(row.get_decided_by().cloned()); ids.extend(row.get_cancelled_by().cloned()); } let people = person_map(ids, db).await?; Ok(rows .iter() .zip(&slots) .map(|(row, slot)| AppointmentResponse::new(row, slot.as_ref(), &people)) .collect()) } /// The single-row form of [`appointment_responses`] — one rendering path, so a /// mutation's response can never drift from the list's. async fn one_appointment( appointment: Appointment, db: &Database, ) -> Result, AppError> { appointment_responses(std::slice::from_ref(&appointment), db) .await? .pop() .map(Json) .ok_or_else(|| AppError::Internal("failed to render the appointment".into())) } /// Who may act on a slot (and on the bookings sitting on it): the teacher who /// published it, or anyone `manager` and above — in both cases only while the /// caller is *still* `teacher` or above. /// /// The `teacher` floor is enforced here, not left to the extractors: a slot's /// `teacher` column is a historical fact no demotion rewrites, so a grant read /// off it has to re-read the live role or it outlives the role that earned it /// (see `courses::can_manage_course`, where trusting the callers instead cost /// exactly that). A demoted owner leaves nothing outstanding to strand: the /// demotion cancels their live bookings and deletes the slots under them /// ([`crate::domain::user::User::set_role`]) — which it must, since a manager+ /// passes this gate but has no route that yields such a booking's id, and past /// its start the requester's own `cancel` is refused too. fn can_manage(slot: &AppointmentSlot, user: &User) -> bool { user.get_role().at_least(Role::Teacher) && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager)) } /// The booking plus the slot it sits on, insisting the caller may decide it. async fn for_decision( id: &AppointmentId, user: &User, db: &Database, ) -> Result { let appointment = service::appointment::read(db, id) .await? .ok_or(AppError::NotFound)?; let slot_id = appointment.get_slot().ok_or(AppError::NotFound)?; let slot = service::appointment_slot::read(db, slot_id) .await? .ok_or(AppError::NotFound)?; if !can_manage(&slot, user) { return Err(AppError::Forbidden( "only the slot's teacher or a manager/admin can decide this appointment", )); } Ok(appointment) } // ---- slots ---------------------------------------------------------------- /// Publish availability. Requires the `teacher` role or higher; the slot lands /// on the caller's own calendar. With `repeat_weekly` the same window is /// expanded into one row per week up to and including `until` (at most 52), /// all sharing a `series` id — each occurrence is then independently bookable /// and independently deletable. The response is always an array: one element /// for a one-off publish, one per occurrence for a weekly one. /// /// A window may not overlap another the *same teacher* has already published /// (`409`). The comparison is half-open, so 10:00–10:30 and 10:30–11:00 are two /// slots and not a collision — that is how an hour is carved into back-to-back /// slots. A weekly publish is all-or-nothing: it is validated in full (against /// stored slots *and* against its own earlier occurrences, which a window longer /// than a week collides with) before a single row is written, so a mid-series /// collision leaves no stray weeks behind. #[utoipa::path( post, path = "/slots", tag = "appointments", security(("session_cookie" = [])), request_body = PublishSlots, responses( (status = 201, description = "Slots published", body = Vec), (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), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher — including an account demoted while this request ran, whose calendar the demotion is withdrawing", body = ErrorResponse), (status = 409, description = "The window overlaps one the caller has already published, or (weekly) two occurrences overlap each other — the whole publish is refused, nothing is written", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn publish_slots( State(st): State, RequireTeacher(user): RequireTeacher, Json(req): Json, ) -> Result<(StatusCode, Json>), AppError> { let note = match req.note { Some(ref note) => Some(SlotNote::try_new(note)?), None => None, }; let starts_at = Timestamp::from_millis(req.starts_at); let ends_at = Timestamp::from_millis(req.ends_at); check_not_past("starts_at", Some(starts_at))?; check_not_past("ends_at", Some(ends_at))?; check_time_range(Some(starts_at), Some(ends_at))?; let slots = if req.repeat_weekly { let until = req .until .map(Timestamp::from_millis) .ok_or(AppError::Validation(ValidationError::Invalid { field: "until", reason: "is required with repeat_weekly", }))?; check_not_past("until", Some(until))?; service::appointment_slot::publish_weekly( &st.db, user.get_id(), starts_at, ends_at, note, until, ) .await? } else { vec![ service::appointment_slot::create(&st.db, user.get_id(), starts_at, ends_at, note) .await?, ] }; let people = PersonRef::map_of(&[&user]); let items = slots .iter() .map(|slot| SlotResponse::new(slot, &people)) .collect(); Ok((StatusCode::CREATED, Json(items))) } /// One teacher's window filter, shared by both doors: `me` is the caller, /// blank is refused, and a well-formed-but-unknown id stands — it names no /// row, so the filtered page is simply empty — while a malformed one is a /// 400. Never [`UserId::from_key`] into a nil id: that would read as an /// empty 200 instead of the caller's error. fn teacher_filter(raw: Option<&str>, caller: &UserId) -> Result, AppError> { let Some(raw) = raw else { return Ok(None); }; let key = raw.trim(); if key.is_empty() { return Err(AppError::Validation(ValidationError::Invalid { field: "teacher", reason: "must not be empty", })); } Ok(Some(match key { "me" => *caller, other => { let id = UserId::from_key(other); if id.uuid().is_nil() { return Err(AppError::Validation(ValidationError::Invalid { field: "teacher", reason: "must be a hyphenated uuid", })); } id } })) } /// A `?starts_after=`/`?starts_before=` instant: unix milliseconds, negative /// refused, absent left absent. fn starts_bound_filter(field: &'static str, raw: Option) -> Result, AppError> { match raw { None => Ok(None), Some(value) if value < 0 => Err(AppError::Validation(ValidationError::Invalid { field, reason: "must not be negative", })), Some(value) => Ok(Some(Timestamp::from_millis(value))), } } /// Optional list filters on the slots door. Absent, the response is the /// unfiltered calendar exactly as it has always been. #[derive(Debug, Deserialize, IntoParams)] struct SlotFilter { /// Narrow to one teacher's slots: `me` for the caller, else a user id. #[param(example = "me")] teacher: Option, /// Keep only slots starting at or after this unix-millisecond instant. #[param(minimum = 0, example = 1_760_000_000_000_i64)] starts_after: Option, } impl SlotFilter { fn resolve_teacher(&self, caller: &UserId) -> Result, AppError> { teacher_filter(self.teacher.as_deref(), caller) } fn resolve_starts_after(&self) -> Result, AppError> { starts_bound_filter("starts_after", self.starts_after) } } /// List slots, earliest first. Teacher+ see their own calendar, past occurrences /// included; everyone else sees every slot that has not started yet — the /// bookable calendar, bounded exactly as booking is, so a slot already underway /// is left out rather than offered for a request that could only answer `409`. /// A demotion below `teacher` withdraws that account's calendar outright, so /// there is normally nothing of theirs left to list; a slot an older build /// stranded is left out here too (and refused at book time). Whether a slot is /// already taken is not carried /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope. /// /// Optional filters narrow the answer without ever widening it. `?teacher=` /// names one teacher — `me` for the caller, else a user id — and /// `?starts_after=` (unix milliseconds, inclusive) keeps the windows that /// start at or after the instant, in the SQL so the past is never loaded to /// be thrown away. A teacher+ caller's universe is their own calendar, so /// `teacher=me` reads the same as absent and naming another teacher is the /// empty intersection: a colleague's slots, past ones included, stay /// private. For everyone else the universe is the bookable calendar, so a /// named teacher's upcoming slots are exactly what the absent call already /// offered. /// /// Each slot carries its teacher's `PersonRef` (id, username, name) to *every* /// authenticated caller, parents included — deliberate, and not to be /// "tightened". A parent's three direct routes to that identity all refuse /// (`GET /users/{id}/profile` 403, `/users/search` and `/users` teacher+/admin), /// but you cannot pick whom to book a conference with from an anonymous /// calendar: this list *is* the staff directory for the booking flow, scoped to /// people who published bookable time. Same for the `teacher` / `proposed_by` / /// `decided_by` refs on a booking. Pinned by /// `tests/regress_appointments.rs::a_parent_reads_the_slot_teachers_identity`. // corner-cut: occupancy would be one query per slot with today's domain API; a // batch "live bookings for these slots" read would let the list carry it. #[utoipa::path( get, path = "/slots", tag = "appointments", security(("session_cookie" = [])), params(PageParams, SlotFilter), responses( (status = 200, description = "A page of slots (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_slots( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let narrow_to = filter.resolve_teacher(user.get_id())?; let starts_after = filter.resolve_starts_after()?; let (slots, people) = if user.get_role().at_least(Role::Teacher) { // The calendar arm's universe is the caller's own published rows, // past occurrences included. The `teacher` filter narrows inside it: // `me` is the caller's own calendar (the same rows as absent), and // naming anyone else is the empty intersection — which it must be, // or the param would hand over a colleague's calendar. match narrow_to { Some(other) if other != *user.get_id() => { (Vec::new(), PersonRef::map_of(&[&user])) } _ => ( service::appointment_slot::list_calendar( &st.db, user.get_id(), starts_after, ) .await?, PersonRef::map_of(&[&user]), ), } } else { let mut slots = service::appointment_slot::list_upcoming( &st.db, Timestamp::now(), narrow_to.as_ref(), starts_after, ) .await?; // The teachers' live rows, not the slots' word for it: a demotion // leaves the calendar behind, and an inert slot must not be offered. // Keying the person map off that same read makes the filter free. let mut seen = HashSet::new(); let teachers: Vec = slots .iter() .map(AppointmentSlot::get_teacher) .filter(|teacher| seen.insert(teacher.key().to_string())) .cloned() .collect(); let people: HashMap = crate::service::user::list_by_ids(&st.db, &teachers) .await? .iter() .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher))) .collect(); slots.retain(|slot| people.contains_key(slot.get_teacher().key().as_str())); (slots, people) }; let total = slots.len() as i64; // Paged in the web layer: slots of demoted teachers are dropped above. let items = paginate(&slots, limit, offset) .iter() .map(|slot| SlotResponse::new(slot, &people)) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } /// Withdraw one slot. Requires teacher+; the publishing teacher may drop their /// own and managers/admins anyone's. A slot carrying a pending or approved /// booking is refused (`409`) — reject or cancel that booking first. Settled /// bookings (rejected/cancelled) go with the slot. #[utoipa::path( delete, path = "/slots/{id}", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Slot id")), responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "The slot has a pending or approved booking", body = ErrorResponse), ), )] async fn delete_slot( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { let slot = service::appointment_slot::read(&st.db, &AppointmentSlotId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage(&slot, &user) { return Err(AppError::Forbidden( "only the slot's teacher or a manager/admin can delete it", )); } service::appointment_slot::delete(&st.db, slot).await?; Ok(StatusCode::NO_CONTENT) } /// Withdraw a whole recurring publish. Same rights as the single delete, and /// all-or-nothing: if *any* occurrence still carries a pending or approved /// booking the entire series is refused (`409`), so the person waiting is dealt /// with rather than silently left on a stray week. #[utoipa::path( delete, path = "/slots/series/{series}", tag = "appointments", security(("session_cookie" = [])), params(("series" = String, Path, description = "Series id, from a slot's `series` field")), responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the series' teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such series", body = ErrorResponse), (status = 409, description = "Some occurrence has a pending or approved booking", body = ErrorResponse), ), )] async fn delete_slot_series( State(st): State, RequireTeacher(user): RequireTeacher, Path(series): Path, ) -> Result { let series = SlotSeries::from_key(&series); // Every occurrence of one publish carries the same teacher, so the first // row answers the ownership question for all of them. let slot = service::appointment_slot::list_for_series(&st.db, &series) .await? .into_iter() .next() .ok_or(AppError::NotFound)?; if !can_manage(&slot, &user) { return Err(AppError::Forbidden( "only the slot's teacher or a manager/admin can delete it", )); } service::appointment_slot::delete_series(&st.db, &series).await?; Ok(StatusCode::NO_CONTENT) } // ---- bookings ------------------------------------------------------------- /// Ask for a meeting on a published slot. Students and parents only — a parent /// books for *themselves* (this is the parent-teacher conference), never on /// behalf of a child, and staff arrange between themselves off this API. The /// booking lands `pending`: publishing availability is not consent to a /// particular person and topic. Refused (`409`) when the slot's window has already /// opened, when it is already taken, when the requester is already committed at /// that time, or when the slot's teacher no longer holds a teaching role. #[utoipa::path( post, path = "/", tag = "appointments", security(("session_cookie" = [])), request_body = BookAppointment, responses( (status = 201, description = "Booking requested", body = AppointmentResponse), (status = 400, description = "Missing or over-long reason", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Only students and parents book appointments", body = ErrorResponse), (status = 404, description = "Slot not found", body = ErrorResponse), (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn book( State(st): State, CurrentUser(user): CurrentUser, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { if !matches!(user.get_role(), Role::Student | Role::Parent) { return Err(AppError::Forbidden( "only students and parents can book an appointment", )); } let slot_id = AppointmentSlotId::from_key(&req.slot); let slot = service::appointment_slot::read(&st.db, &slot_id) .await? .ok_or(AppError::NotFound)?; // The slot row is not the grant: a teacher demoted since publishing keeps // their rows, and those rows must be inert. Their live role decides. if !crate::service::user::read(&st.db, slot.get_teacher()) .await? .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher)) { return Err(AppError::Conflict( "the slot's teacher no longer holds a teaching role", )); } let reason = AppointmentReason::try_new(&req.reason)?; let appointment = service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?; Ok(( StatusCode::CREATED, one_appointment(appointment, &st.db).await?, )) } /// Optional list filters on the bookings door. Absent, the response is the /// caller's listing exactly as it has always been. #[derive(Debug, Deserialize, IntoParams)] struct AppointmentFilter { /// Narrow to one booking state: `pending`, `approved`, `rejected` or /// `cancelled`. #[param(example = "pending")] status: Option, /// Keep only meetings starting at or after this unix-millisecond instant. #[param(minimum = 0, example = 1_760_000_000_000_i64)] starts_after: Option, /// Keep only meetings starting before this unix-millisecond instant — /// exclusive, so `[starts_after, starts_before)` is a closed-open month. #[param(minimum = 0, example = 1_760_259_199_999_i64)] starts_before: Option, /// Narrow to bookings on one teacher's slots: `me` for the caller, else /// a user id. #[param(example = "me")] teacher: Option, } impl AppointmentFilter { /// The wire word against the closed vocabulary the rows store /// ([`AppointmentStatus::as_str`]): an unknown or blank word is a 400 /// naming the field, never a silent whole-list read. fn resolve_status(&self) -> Result, AppError> { const STATUSES: [AppointmentStatus; 4] = [ AppointmentStatus::Pending, AppointmentStatus::Approved, AppointmentStatus::Rejected, AppointmentStatus::Cancelled, ]; let Some(raw) = self.status.as_deref() else { return Ok(None); }; let word = raw.trim(); if word.is_empty() { return Err(AppError::Validation(ValidationError::Invalid { field: "status", reason: "must not be empty", })); } STATUSES .into_iter() .find(|status| status.as_str() == word) .map(Some) .ok_or_else(|| { AppError::Validation(ValidationError::Invalid { field: "status", reason: "must be one of: pending, approved, rejected, cancelled", }) }) } fn resolve_starts_after(&self) -> Result, AppError> { starts_bound_filter("starts_after", self.starts_after) } fn resolve_starts_before(&self) -> Result, AppError> { starts_bound_filter("starts_before", self.starts_before) } fn resolve_teacher(&self, caller: &UserId) -> Result, AppError> { teacher_filter(self.teacher.as_deref(), caller) } } /// List bookings, newest first. Students and parents see the ones they /// requested; teacher+ see the ones aimed at their own slots — their request /// inbox. Managers and admins read their own inbox too (they may still decide /// any booking by id). Paged via `?limit=&offset=` (omit `limit` for every /// booking); returns a `{items, total, limit, offset}` envelope. /// /// Optional filters narrow the answer without ever widening it. `?status=` /// is one of `pending`, `approved`, `rejected`, `cancelled`; `?starts_after=` /// and `?starts_before=` (unix milliseconds) keep the meetings whose start /// sits in `[after, before)` — a standing proposal's time when one stands, /// the slot's window otherwise, so a booking whose slot is gone (no window /// at all) is left out; `?teacher=` names the booked slot's teacher, `me` or /// a user id, joined through the slot. A teacher+ caller's universe is their /// own inbox, so `teacher=me` reads the same as absent and naming another /// teacher is the empty intersection rather than a read of that teacher's /// inbox. #[utoipa::path( get, path = "/", tag = "appointments", security(("session_cookie" = [])), params(PageParams, AppointmentFilter), responses( (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_appointments( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let status = filter.resolve_status()?; let starts_after = filter.resolve_starts_after()?; let starts_before = filter.resolve_starts_before()?; let narrow_to = filter.resolve_teacher(user.get_id())?; let (rows, total) = if user.get_role().at_least(Role::Teacher) { // The inbox arm's universe is the caller's own bookings; the // `teacher` filter narrows inside it, so naming another teacher is // the empty intersection — see the slots door, same rule. match narrow_to { Some(other) if other != *user.get_id() => (Vec::new(), 0), _ => { service::appointment::list_for_teacher( &st.db, user.get_id(), status, starts_after, starts_before, limit, offset, ) .await? } } } else { service::appointment::list_for_requester( &st.db, user.get_id(), service::appointment::RequesterListParams { status, starts_after, starts_before, teacher: narrow_to.as_ref(), limit, offset, }, ) .await? }; // Join slots and people onto the page alone — the lookup shrinks with it. let items = appointment_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } /// Confirm a pending booking. Requires teacher+ and ownership of the slot (or /// manager/admin). The double-booking guard runs here, against both sides: /// approval is what commits anyone, so a time colliding with another approved /// meeting of the teacher or of the requester is refused (`409`), as is a /// window that has already started — that meeting could never be cancelled. /// /// Refused (`409`) too while a counter-proposal stands: the proposed time is /// the teacher's own, so confirming it here would commit the requester to a /// time they never agreed to. Answering a proposal is the requester's alone: /// `PATCH /{id}/reschedule/accept` (which *is* approval, at the proposed time) /// or `PATCH /{id}/reschedule/decline` (which cancels the booking). #[utoipa::path( patch, path = "/{id}/approve", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), responses( (status = 200, description = "Approved", body = AppointmentResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "No longer pending, a counter-proposal is standing (only the requester can accept it), the time has already started, or it collides with another approved appointment", body = ErrorResponse), ), )] async fn approve( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); for_decision(&id, &user, &st.db).await?; let appointment = service::appointment::approve(&st.db, &id, user.get_id()).await?; one_appointment(appointment, &st.db).await } /// Turn a pending booking down. Requires teacher+ and ownership of the slot (or /// manager/admin). The slot frees up immediately — occupancy counts live /// bookings only, so someone else may take it. #[utoipa::path( patch, path = "/{id}/reject", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), request_body(content = RejectRequest, description = "Optional rejection reason; the whole body may be omitted"), responses( (status = 200, description = "Rejected", body = AppointmentResponse), (status = 400, description = "Reason is over-long", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "No longer pending", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn reject( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, body: Option>, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); for_decision(&id, &user, &st.db).await?; // A blank or absent reason records none; a present one is validated (400 if // over-long) before it reaches the row. let reason = match body.and_then(|Json(req)| req.reason) { Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), _ => None, }; let appointment = service::appointment::reject(&st.db, &id, user.get_id(), reason).await?; one_appointment(appointment, &st.db).await } /// Call a meeting off. **The requester only** — the person who asked for it — /// from either live state, so an approved meeting can still be dropped and the /// slot freed. Anyone else is a `403`, the slot's teacher and a manager/admin /// included (the guard compares ids, not roles): a teacher ends a booking by /// **rejecting** it while it is `pending`, and an already-approved one by /// counter-proposing another time (`PATCH /{id}/reschedule` — which sends it /// back to `pending`) and then rejecting it. Refused (`409`) once the meeting's /// window has started: a meeting that already began is history, not a plan. #[utoipa::path( patch, path = "/{id}/cancel", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), request_body(content = CancelRequest, description = "Optional cancellation reason; the whole body may be omitted"), responses( (status = 200, description = "Cancelled", body = AppointmentResponse), (status = 400, description = "Reason is over-long", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the requester", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn cancel( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, body: Option>, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); let appointment = service::appointment::read(&st.db, &id) .await? .ok_or(AppError::NotFound)?; // Only the requester (student/parent) may cancel. Teachers/managers end a // booking by rejecting (while pending) or rescheduling — never cancelling. if appointment.get_requester() != user.get_id() { return Err(AppError::Forbidden( "only the requester can cancel this appointment", )); } // A blank or absent reason records none; a present one is validated (400 if // over-long) before it reaches the row. let reason = match body.and_then(|Json(req)| req.reason) { Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), _ => None, }; // The started-window guard lives in `service::appointment::cancel`, under // the lock and on a fresh read — a pre-lock copy of it here would only be // a staler second opinion, and `decline_reschedule` would still bypass it. let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), reason).await?; one_appointment(appointment, &st.db).await } /// Counter-propose another time for a booking, on the same row (the reason and /// the history stay in one place). Requires teacher+ and ownership of the slot /// (or manager/admin). /// /// **The proposal sends the booking back to `pending` and clears /// `decided_by`** — an already-approved meeting is *not* committed at the new /// time until the requester accepts it at /// `PATCH /appointments/{id}/reschedule/accept`, since leaving it approved /// would silently move a confirmed appointment. The slot stays held meanwhile. /// /// Refused (`409`) when the proposed window has already opened — the 60-second /// skew grace on the times is for clock drift, not for proposing into a meeting /// that is already underway, which `cancel` would then refuse to undo. #[utoipa::path( patch, path = "/{id}/reschedule", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), request_body = Reschedule, responses( (status = 200, description = "Proposed; the booking is pending again", body = AppointmentResponse), (status = 400, description = "Invalid time range or times in the past", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn reschedule( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, Json(req): Json, ) -> Result, AppError> { let starts_at = Timestamp::from_millis(req.starts_at); let ends_at = Timestamp::from_millis(req.ends_at); check_not_past("starts_at", Some(starts_at))?; check_not_past("ends_at", Some(ends_at))?; check_time_range(Some(starts_at), Some(ends_at))?; let id = AppointmentId::from_key(&id); for_decision(&id, &user, &st.db).await?; let appointment = service::appointment::propose(&st.db, &id, starts_at, ends_at, user.get_id()).await?; one_appointment(appointment, &st.db).await } /// Accept the teacher's counter-proposal. The requester's call alone — it is /// their commitment. Accepting *is* approval at the proposed time, so the /// double-booking guard runs again for both sides (`409` if the moved time now /// collides with something else, or has already started — agreeing to a window /// that began would mint a meeting nobody can cancel). /// /// The body **names the proposal being accepted** (`proposed_starts_at` / /// `proposed_ends_at`, copied from the booking as it was read). A teacher may /// re-propose at any time, and the two calls are minutes apart, so without the /// pin the teacher would choose which window the requester's click commits /// them to. A superseded proposal answers `409` — re-read the booking and /// accept (or decline) the new one. #[utoipa::path( patch, path = "/{id}/reschedule/accept", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), request_body = AcceptReschedule, responses( (status = 200, description = "Approved at the proposed time", body = AppointmentResponse), (status = 400, description = "Missing or unreadable body", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the requester", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "No time has been proposed, the proposal has since changed (re-read it), the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn accept_reschedule( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); ensure_requester(&id, &user, &st.db).await?; // Unvalidated on purpose: these are not a time to meet, they are the // requester's answer to "which proposal?" — the domain compares them to the // row and refuses anything else, so a past or inverted pair is simply a // mismatch (409), never a booking. let appointment = service::appointment::accept_proposal( &st.db, &id, user.get_id(), Timestamp::from_millis(req.proposed_starts_at), Timestamp::from_millis(req.proposed_ends_at), ) .await?; one_appointment(appointment, &st.db).await } /// Refuse the teacher's counter-proposal. The requester's call alone, and it /// **cancels the booking**: the proposal replaced the time that was asked for, /// so there is nothing left to fall back to — book another slot instead. The /// slot frees up, and the original request stays readable as `cancelled` with /// the refused proposal still on it. Declining is a cancel, so it answers to /// the same deadline: `409` once the meeting's effective window has started. #[utoipa::path( patch, path = "/{id}/reschedule/decline", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), responses( (status = 200, description = "Cancelled", body = AppointmentResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the requester", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "No time has been proposed, the booking is already settled, or the meeting's window has already started", body = ErrorResponse), ), )] async fn decline_reschedule( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); let appointment = ensure_requester(&id, &user, &st.db).await?; if appointment.get_proposed_starts_at().is_none() { return Err(AppError::Conflict("no time has been proposed")); } let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), None).await?; one_appointment(appointment, &st.db).await } /// The booking, insisting the caller is the person who asked for it — the only /// one who can answer a counter-proposal. async fn ensure_requester( id: &AppointmentId, user: &User, db: &Database, ) -> Result { let appointment = service::appointment::read(db, id) .await? .ok_or(AppError::NotFound)?; if appointment.get_requester() != user.get_id() { return Err(AppError::Forbidden( "only the requester can answer a counter-proposal", )); } Ok(appointment) } #[cfg(test)] mod tests { use super::*; use crate::database::init_test_db; use crate::domain::user::Username; /// A user at `role`, minted through the real create path. async fn user(username: &str, role: Role, db: &Database) -> User { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) .await .unwrap(); crate::service::user::set_role(db, user.get_id(), role) .await .unwrap() .0 } /// All five `can_manage` sites are `RequireTeacher` today, so this is /// pinned at the helper — the level where the floor is observable, and the /// level that has to hold when the next route arrives with `CurrentUser`. #[tokio::test] async fn demoted_slot_owner_loses_management() { let (db, _leases) = init_test_db().await; let owner = user("ogretmen", Role::Teacher, &db).await; let slot = service::appointment_slot::create( &db, owner.get_id(), Timestamp::from_millis(1_000), Timestamp::from_millis(2_000), None, ) .await .unwrap(); assert!(can_manage(&slot, &owner)); for role in [Role::Student, Role::Parent] { let demoted = crate::service::user::set_role(&db, owner.get_id(), role) .await .unwrap() .0; assert!( !can_manage(&slot, &demoted), "{role:?} slot owner still decides its bookings" ); } // Never orphaned: manager+ still decides everything on the slot. let boss = user("mudur", Role::Manager, &db).await; assert!(can_manage(&slot, &boss)); } // ---- the list filters --------------------------------------------------- /// The handlers under test touch `db` alone, but [`AppState`] wants all /// of its pieces — built here off the sandboxed per-test database. async fn a_state(db: &Database) -> AppState { AppState { db: db.clone(), tenants: crate::database::init_test_tenants().await, files_path: std::env::temp_dir(), cookie_secure: false, rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), rag_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), ai: None, metrics: crate::telemetry::Metrics::noop(), } } /// One published slot at an absolute instant. async fn a_slot(db: &Database, teacher: &UserId, starts_at: i64, ends_at: i64) { service::appointment_slot::create( db, teacher, Timestamp::from_millis(starts_at), Timestamp::from_millis(ends_at), None, ) .await .unwrap(); } /// The slots door, unpaged. async fn slots(st: &AppState, who: &User, filter: SlotFilter) -> Page { list_slots( State(st.clone()), CurrentUser(who.clone()), Query(PageParams { limit: None, offset: None, }), Query(filter), ) .await .unwrap() .0 } /// The bookings door, unpaged. async fn bookings( st: &AppState, who: &User, filter: AppointmentFilter, ) -> Page { list_appointments( State(st.clone()), CurrentUser(who.clone()), Query(PageParams { limit: None, offset: None, }), Query(filter), ) .await .unwrap() .0 } /// Blank, malformed, and negative filter words are 400s naming the /// field; `me` is the caller; a well-formed stranger stands (and names /// an empty page — pinned by the handler-level tests). #[test] fn filter_words_refuse_blank_malformed_and_negative() { let caller = UserId::generate(); for word in ["", " ", "not-a-uuid"] { let filter = SlotFilter { teacher: Some(word.into()), starts_after: None, }; assert!( matches!( filter.resolve_teacher(&caller), Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "teacher" ), "`{word}` must refuse as `teacher`" ); } assert_eq!( SlotFilter { teacher: Some("me".into()), starts_after: None, } .resolve_teacher(&caller) .unwrap(), Some(caller) ); let stranger = UserId::generate(); assert_eq!( SlotFilter { teacher: Some(stranger.key()), starts_after: None, } .resolve_teacher(&caller) .unwrap(), Some(stranger) ); let filter = SlotFilter { teacher: None, starts_after: Some(-1), }; assert!(matches!( filter.resolve_starts_after(), Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_after" )); assert_eq!( SlotFilter { teacher: None, starts_after: Some(0), } .resolve_starts_after() .unwrap() .map(|instant| instant.as_millis()), Some(0) ); let filter = AppointmentFilter { status: None, starts_after: None, starts_before: Some(-5), teacher: None, }; assert!(matches!( filter.resolve_starts_before(), Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_before" )); // The closed status vocabulary: exact wire words only — no case // play, no blank, no synonym — mirroring what the rows store. let status = |word: Option<&str>| AppointmentFilter { status: word.map(str::to_string), starts_after: None, starts_before: None, teacher: None, }; assert_eq!(status(None).resolve_status().unwrap(), None); assert_eq!( status(Some(" pending ")).resolve_status().unwrap(), Some(AppointmentStatus::Pending) ); assert_eq!( status(Some("cancelled")).resolve_status().unwrap(), Some(AppointmentStatus::Cancelled) ); for word in ["", " ", "APPROVED", "live", "confirmed"] { assert!( matches!( status(Some(word)).resolve_status(), Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "status" ), "`{word}` must refuse as `status`" ); } } /// The slots door: absent filters are today's response per role — /// teacher+ read their own calendar with the past included, everyone /// else reads the bookable calendar — `teacher=me` is the caller's own /// set, a named other teacher narrows the bookable calendar but never /// opens a colleague's calendar, and `starts_after` cuts with `total` /// reporting the filtered count. #[tokio::test] async fn slot_filters_narrow_without_widening() { let (db, _leases) = init_test_db().await; let st = a_state(&db).await; let now = Timestamp::now().as_millis(); let ali = user("ali-ogretmen", Role::Teacher, &db).await; let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; let veli = user("veli-veli", Role::Student, &db).await; a_slot(&db, ali.get_id(), now - 10_000, now - 5_000).await; // ali's past a_slot(&db, ali.get_id(), now + 5_000, now + 10_000).await; a_slot(&db, ali.get_id(), now + 60_000, now + 90_000).await; a_slot(&db, ayse.get_id(), now + 30_000, now + 40_000).await; let none = || SlotFilter { teacher: None, starts_after: None, }; let me = || SlotFilter { teacher: Some("me".into()), starts_after: None, }; let of = |who: &UserId| SlotFilter { teacher: Some(who.key()), starts_after: None, }; // Student, no filters: the bookable calendar — ali's past stays out, // earliest first, exactly as the absent call has always answered. let page = slots(&st, &veli, none()).await; assert_eq!(page.total, 3); let starts: Vec = page.items.iter().map(|slot| slot.starts_at).collect(); let mut sorted = starts.clone(); sorted.sort_unstable(); assert_eq!(starts, sorted); // Student, teacher=me: they publish nothing — an empty page, not an // error. let page = slots(&st, &veli, me()).await; assert_eq!((page.items.len(), page.total), (0, 0)); // Student, teacher=ali: exactly ali's upcoming pair — a narrowing of // the calendar they may already see, his past slot still private. let page = slots(&st, &veli, of(ali.get_id())).await; assert_eq!(page.total, 2); assert!( page.items .iter() .all(|slot| slot.teacher.id == ali.get_id().key() && slot.starts_at > now) ); // Student, teacher=: an empty page, not a 404. let page = slots(&st, &veli, of(&UserId::generate())).await; assert_eq!((page.items.len(), page.total), (0, 0)); // Teacher, no filters: their own calendar, past occurrences // included — today's arm. let page = slots(&st, &ali, none()).await; assert_eq!(page.total, 3); // Teacher, teacher=me: the same calendar as absent. let page = slots(&st, &ali, me()).await; assert_eq!(page.total, 3); // Teacher, teacher=ayse: the empty intersection. Naming a colleague // must not hand over their calendar, past rows included. let page = slots(&st, &ali, of(ayse.get_id())).await; assert_eq!((page.items.len(), page.total), (0, 0)); // Teacher, starts_after=now: the past occurrence is cut in the SQL, // and total is the filtered count. let page = slots( &st, &ali, SlotFilter { teacher: None, starts_after: Some(now), }, ) .await; assert_eq!(page.total, 2); assert!(page.items.iter().all(|slot| slot.starts_at >= now)); // Both filters together, on the student arm. let page = slots( &st, &veli, SlotFilter { teacher: Some(ayse.get_id().key()), starts_after: Some(now), }, ) .await; assert_eq!(page.total, 1); assert_eq!(page.items[0].starts_at, now + 30_000); } /// The bookings door: `status` and `starts_after` (the meeting's /// effective start) narrow each side's own listing, `teacher` joins /// through the slot, and a teacher+ caller naming another teacher gets /// the empty intersection — never that teacher's inbox. #[tokio::test] async fn booking_filters_narrow_without_widening() { let (db, _leases) = init_test_db().await; let st = a_state(&db).await; let now = Timestamp::now().as_millis(); let ali = user("ali-ogretmen", Role::Teacher, &db).await; let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; let veli = user("veli-veli", Role::Student, &db).await; let reason = AppointmentReason::try_new("görüşme").unwrap(); let ali_slot = service::appointment_slot::create( &db, ali.get_id(), Timestamp::from_millis(now + 60_000), Timestamp::from_millis(now + 120_000), None, ) .await .unwrap(); let ayse_slot = service::appointment_slot::create( &db, ayse.get_id(), Timestamp::from_millis(now + 200_000), Timestamp::from_millis(now + 260_000), None, ) .await .unwrap(); let pending = service::appointment::book(&db, ali_slot.get_id(), veli.get_id(), reason.clone()) .await .unwrap(); let approved = service::appointment::book(&db, ayse_slot.get_id(), veli.get_id(), reason.clone()) .await .unwrap(); service::appointment::approve(&db, approved.get_id(), ayse.get_id()) .await .unwrap(); let none = || AppointmentFilter { status: None, starts_after: None, starts_before: None, teacher: None, }; let status = |word: &str| AppointmentFilter { status: Some(word.into()), starts_after: None, starts_before: None, teacher: None, }; let after = |millis: i64| AppointmentFilter { status: None, starts_after: Some(millis), starts_before: None, teacher: None, }; let with_teacher = |who: &User| AppointmentFilter { status: None, starts_after: None, starts_before: None, teacher: Some(who.get_id().key()), }; // Student, no filters: both bookings — today's response. let page = bookings(&st, &veli, none()).await; assert_eq!(page.total, 2); // status: only the approved one; total is the filtered count. let page = bookings(&st, &veli, status("approved")).await; assert_eq!(page.total, 1); assert_eq!(page.items[0].id, approved.get_id().key()); assert_eq!(page.items[0].status, "approved"); // A state nothing carries: an empty page, not an error. let page = bookings(&st, &veli, status("rejected")).await; assert_eq!((page.items.len(), page.total), (0, 0)); // teacher: joined through the slot — only the bookings on ali's. let page = bookings(&st, &veli, with_teacher(&ali)).await; assert_eq!(page.total, 1); assert_eq!(page.items[0].id, pending.get_id().key()); // starts_after judges the meeting's effective start: the slot's // window while no proposal stands. let page = bookings(&st, &veli, after(now + 150_000)).await; assert_eq!(page.total, 1); assert_eq!(page.items[0].id, approved.get_id().key()); // starts_before through the door: the late meeting sits outside a // window ending at now + 150_000, the early one inside it. let page = bookings( &st, &veli, AppointmentFilter { status: None, starts_after: None, starts_before: Some(now + 150_000), teacher: None, }, ) .await; assert_eq!(page.total, 1); assert_eq!(page.items[0].id, pending.get_id().key()); // Teacher+ inbox: only the bookings aimed at their own slots. let page = bookings(&st, &ali, none()).await; assert_eq!(page.total, 1); assert_eq!(page.items[0].id, pending.get_id().key()); // Inbox, teacher=me: the same rows. let page = bookings(&st, &ali, with_teacher(&ali)).await; assert_eq!(page.total, 1); // Inbox, teacher=ayse: the empty intersection — never her inbox. let page = bookings(&st, &ali, with_teacher(&ayse)).await; assert_eq!((page.items.len(), page.total), (0, 0)); // Inbox, starts_after: ali's meeting is the earlier one, so a cut // past it empties his inbox while ayse keeps hers. let page = bookings(&st, &ali, after(now + 150_000)).await; assert_eq!((page.items.len(), page.total), (0, 0)); let page = bookings(&st, &ayse, after(now + 150_000)).await; assert_eq!(page.total, 1); } }