forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

appointments.rs1570 lines, 65.2 KiBHistoryRawDownload
1use std::collections::{HashMap, HashSet};
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::{Path, Query};
6use axum::http::StatusCode;
7use serde::{Deserialize, Serialize};
8use utoipa::{IntoParams, ToSchema};
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::database::Database;
13use crate::domain::appointment::{
14 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
15};
16use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
17use crate::domain::role::Role;
18use crate::domain::timestamp::Timestamp;
19use crate::domain::user::{User, UserId};
20use crate::error::{AppError, ErrorResponse, ValidationError};
21use crate::service;
22use crate::state::AppState;
23
24use super::{
25 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range,
26 paginate, person_map,
27};
28
29pub fn routes() -> OpenApiRouter<AppState> {
30 OpenApiRouter::new()
31 .routes(routes!(publish_slots, list_slots))
32 .routes(routes!(delete_slot))
33 .routes(routes!(delete_slot_series))
34 .routes(routes!(book, list_appointments))
35 .routes(routes!(approve))
36 .routes(routes!(reject))
37 .routes(routes!(cancel))
38 .routes(routes!(reschedule))
39 .routes(routes!(accept_reschedule))
40 .routes(routes!(decline_reschedule))
41}
42
43#[derive(Deserialize, ToSchema)]
44struct PublishSlots {
45 /// Unix-millisecond timestamps. Must not be in the past.
46 #[schema(example = 1_900_000_000_000_i64)]
47 starts_at: i64,
48 ends_at: i64,
49 /// Free-text hint shown to requesters ("office hours", "parent meeting").
50 #[schema(max_length = 500)]
51 note: Option<String>,
52 /// Repeat the same window every week up to and including `until`.
53 #[serde(default)]
54 repeat_weekly: bool,
55 /// Required with `repeat_weekly`, ignored without it. Unix-milliseconds,
56 /// not in the past; at most 52 occurrences may be expanded.
57 until: Option<i64>,
58}
59
60#[derive(Deserialize, ToSchema)]
61struct BookAppointment {
62 /// The slot to take, from `GET /appointments/slots`.
63 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
64 slot: String,
65 /// Why you want the meeting — required, the teacher decides on it.
66 #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")]
67 reason: String,
68}
69
70#[derive(Deserialize, ToSchema)]
71struct CancelRequest {
72 /// Optional free-text reason. Blank or absent records no reason; over-long
73 /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`.
74 #[schema(max_length = 1000, example = "Rahatsızlandım, katılamayacağım")]
75 reason: Option<String>,
76}
77
78#[derive(Deserialize, ToSchema)]
79struct RejectRequest {
80 /// Optional free-text reason. Blank or absent records no reason; over-long
81 /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`.
82 #[schema(max_length = 1000, example = "Bu saatte müsait değilim")]
83 reason: Option<String>,
84}
85
86#[derive(Deserialize, ToSchema)]
87struct Reschedule {
88 /// Unix-millisecond timestamps. Must not be in the past.
89 #[schema(example = 1_900_000_000_000_i64)]
90 starts_at: i64,
91 ends_at: i64,
92}
93
94#[derive(Deserialize, ToSchema)]
95struct AcceptReschedule {
96 /// The proposal being accepted, copied from the booking's
97 /// `proposed_starts_at`/`proposed_ends_at` as it was read. Not a request to
98 /// move the meeting: it pins *which* proposal this answer is for, so one the
99 /// teacher has since replaced answers `409` instead of committing you to a
100 /// window you never saw.
101 #[schema(example = 1_900_000_000_000_i64)]
102 proposed_starts_at: i64,
103 proposed_ends_at: i64,
104}
105
106#[derive(Serialize, ToSchema)]
107struct SlotResponse {
108 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
109 id: String,
110 /// Whose calendar this is.
111 teacher: PersonRef,
112 /// Window open/close, UTC unix-milliseconds. Half-open: back-to-back slots
113 /// (10:00–10:30, 10:30–11:00) do not collide.
114 starts_at: i64,
115 ends_at: i64,
116 note: Option<String>,
117 /// The recurring publish this occurrence came from; `null` for a one-off.
118 /// `DELETE /appointments/slots/series/{series}` drops the whole group.
119 series: Option<String>,
120 created_at: i64,
121}
122
123impl SlotResponse {
124 fn new(slot: &AppointmentSlot, people: &HashMap<String, PersonRef>) -> Self {
125 Self {
126 id: slot.get_id().key().to_string(),
127 teacher: PersonRef::resolve(people, slot.get_teacher()),
128 starts_at: slot.get_starts_at().as_millis(),
129 ends_at: slot.get_ends_at().as_millis(),
130 note: slot.get_note().map(|note| note.as_str().to_string()),
131 series: slot.get_series().map(|series| series.as_str().to_string()),
132 created_at: slot.get_created_at().as_millis(),
133 }
134 }
135}
136
137#[derive(Serialize, ToSchema)]
138struct AppointmentResponse {
139 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
140 id: String,
141 /// The slot this booking sits on.
142 slot: String,
143 /// Whose slot it is; `null` only if that slot has since vanished.
144 teacher: Option<PersonRef>,
145 /// Who asked for the meeting (a student or a parent).
146 requester: PersonRef,
147 /// `pending`, `approved`, `rejected`, or `cancelled`. Only the first two
148 /// hold the slot — rejecting or cancelling frees it for someone else.
149 #[schema(example = "pending")]
150 status: String,
151 reason: String,
152 /// When the meeting actually happens, UTC unix-milliseconds: the accepted
153 /// counter-proposal when there is one, the slot's own window otherwise.
154 starts_at: Option<i64>,
155 ends_at: Option<i64>,
156 /// A standing counter-proposal awaiting the requester's answer.
157 proposed_starts_at: Option<i64>,
158 proposed_ends_at: Option<i64>,
159 proposed_by: Option<PersonRef>,
160 /// Who approved or rejected it; `null` while pending.
161 decided_by: Option<PersonRef>,
162 /// Who called it off — the requester, or a requester declining a
163 /// counter-proposal; `null` unless `status` is `cancelled`.
164 cancelled_by: Option<PersonRef>,
165 /// Optional free-text reason given when cancelling; `null` when none was
166 /// (a blank one records nothing). Bookings are only ever rendered to the
167 /// requester and to the slot's teacher, so this audit trail goes no wider.
168 cancel_reason: Option<String>,
169 /// Optional free-text reason given when rejecting; `null` when none was.
170 /// The rejecter is on `decided_by`. Same audience as `cancel_reason`.
171 reject_reason: Option<String>,
172 created_at: i64,
173}
174
175impl AppointmentResponse {
176 fn new(
177 appointment: &Appointment,
178 slot: Option<&AppointmentSlot>,
179 people: &HashMap<String, PersonRef>,
180 ) -> Self {
181 let window = slot.map(|slot| appointment.window(slot));
182 Self {
183 id: appointment.get_id().key().to_string(),
184 // A settled booking whose slot was withdrawn renders without a
185 // window and without a slot id — the dangling reference the old
186 // store permitted, now an explicit NULL.
187 slot: appointment
188 .get_slot()
189 .map(|slot| slot.key())
190 .unwrap_or_default(),
191 teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())),
192 requester: PersonRef::resolve(people, appointment.get_requester()),
193 status: appointment.get_status().as_str().to_string(),
194 reason: appointment.get_reason().as_str().to_string(),
195 starts_at: window.map(|(starts_at, _)| starts_at.as_millis()),
196 ends_at: window.map(|(_, ends_at)| ends_at.as_millis()),
197 proposed_starts_at: appointment.get_proposed_starts_at().map(|t| t.as_millis()),
198 proposed_ends_at: appointment.get_proposed_ends_at().map(|t| t.as_millis()),
199 proposed_by: appointment
200 .get_proposed_by()
201 .map(|id| PersonRef::resolve(people, id)),
202 decided_by: appointment
203 .get_decided_by()
204 .map(|id| PersonRef::resolve(people, id)),
205 cancelled_by: appointment
206 .get_cancelled_by()
207 .map(|id| PersonRef::resolve(people, id)),
208 cancel_reason: appointment
209 .get_cancel_reason()
210 .map(|reason| reason.as_str().to_string()),
211 reject_reason: appointment
212 .get_reject_reason()
213 .map(|reason| reason.as_str().to_string()),
214 created_at: appointment.get_created_at().as_millis(),
215 }
216 }
217}
218
219/// Join slots and people onto a run of bookings. The slot read is per row, so
220/// callers pass the page they are about to render, not the whole list.
221async fn appointment_responses(
222 rows: &[Appointment],
223 db: &Database,
224) -> Result<Vec<AppointmentResponse>, AppError> {
225 let mut slots = Vec::with_capacity(rows.len());
226 for row in rows {
227 let slot = match row.get_slot() {
228 Some(slot_id) => service::appointment_slot::read(db, slot_id).await?,
229 // A settled booking whose slot was withdrawn: no window.
230 None => None,
231 };
232 slots.push(slot);
233 }
234 // Collected eagerly rather than as a lazy iterator: a borrowing closure
235 // held across the `person_map` await makes the handler's future
236 // higher-ranked, which axum then refuses as not `Send` enough.
237 let mut ids = Vec::with_capacity(rows.len() * 2);
238 for (row, slot) in rows.iter().zip(&slots) {
239 ids.push(*row.get_requester());
240 ids.extend(slot.as_ref().map(|slot| *slot.get_teacher()));
241 ids.extend(row.get_proposed_by().cloned());
242 ids.extend(row.get_decided_by().cloned());
243 ids.extend(row.get_cancelled_by().cloned());
244 }
245 let people = person_map(ids, db).await?;
246 Ok(rows
247 .iter()
248 .zip(&slots)
249 .map(|(row, slot)| AppointmentResponse::new(row, slot.as_ref(), &people))
250 .collect())
251}
252
253/// The single-row form of [`appointment_responses`] — one rendering path, so a
254/// mutation's response can never drift from the list's.
255async fn one_appointment(
256 appointment: Appointment,
257 db: &Database,
258) -> Result<Json<AppointmentResponse>, AppError> {
259 appointment_responses(std::slice::from_ref(&appointment), db)
260 .await?
261 .pop()
262 .map(Json)
263 .ok_or_else(|| AppError::Internal("failed to render the appointment".into()))
264}
265
266/// Who may act on a slot (and on the bookings sitting on it): the teacher who
267/// published it, or anyone `manager` and above — in both cases only while the
268/// caller is *still* `teacher` or above.
269///
270/// The `teacher` floor is enforced here, not left to the extractors: a slot's
271/// `teacher` column is a historical fact no demotion rewrites, so a grant read
272/// off it has to re-read the live role or it outlives the role that earned it
273/// (see `courses::can_manage_course`, where trusting the callers instead cost
274/// exactly that). A demoted owner leaves nothing outstanding to strand: the
275/// demotion cancels their live bookings and deletes the slots under them
276/// ([`crate::domain::user::User::set_role`]) — which it must, since a manager+
277/// passes this gate but has no route that yields such a booking's id, and past
278/// its start the requester's own `cancel` is refused too.
279fn can_manage(slot: &AppointmentSlot, user: &User) -> bool {
280 user.get_role().at_least(Role::Teacher)
281 && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager))
282}
283
284/// The booking plus the slot it sits on, insisting the caller may decide it.
285async fn for_decision(
286 id: &AppointmentId,
287 user: &User,
288 db: &Database,
289) -> Result<Appointment, AppError> {
290 let appointment = service::appointment::read(db, id)
291 .await?
292 .ok_or(AppError::NotFound)?;
293 let slot_id = appointment.get_slot().ok_or(AppError::NotFound)?;
294 let slot = service::appointment_slot::read(db, slot_id)
295 .await?
296 .ok_or(AppError::NotFound)?;
297 if !can_manage(&slot, user) {
298 return Err(AppError::Forbidden(
299 "only the slot's teacher or a manager/admin can decide this appointment",
300 ));
301 }
302 Ok(appointment)
303}
304
305// ---- slots ----------------------------------------------------------------
306
307/// Publish availability. Requires the `teacher` role or higher; the slot lands
308/// on the caller's own calendar. With `repeat_weekly` the same window is
309/// expanded into one row per week up to and including `until` (at most 52),
310/// all sharing a `series` id — each occurrence is then independently bookable
311/// and independently deletable. The response is always an array: one element
312/// for a one-off publish, one per occurrence for a weekly one.
313///
314/// A window may not overlap another the *same teacher* has already published
315/// (`409`). The comparison is half-open, so 10:00–10:30 and 10:30–11:00 are two
316/// slots and not a collision — that is how an hour is carved into back-to-back
317/// slots. A weekly publish is all-or-nothing: it is validated in full (against
318/// stored slots *and* against its own earlier occurrences, which a window longer
319/// than a week collides with) before a single row is written, so a mid-series
320/// collision leaves no stray weeks behind.
321#[utoipa::path(
322 post,
323 path = "/slots",
324 tag = "appointments",
325 security(("session_cookie" = [])),
326 request_body = PublishSlots,
327 responses(
328 (status = 201, description = "Slots published", body = Vec<SlotResponse>),
329 (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),
330 (status = 401, description = "Not authenticated", body = ErrorResponse),
331 (status = 403, description = "Requires teacher role or higher — including an account demoted while this request ran, whose calendar the demotion is withdrawing", body = ErrorResponse),
332 (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),
333 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
334 ),
335)]
336async fn publish_slots(
337 State(st): State<AppState>,
338 RequireTeacher(user): RequireTeacher,
339 Json(req): Json<PublishSlots>,
340) -> Result<(StatusCode, Json<Vec<SlotResponse>>), AppError> {
341 let note = match req.note {
342 Some(ref note) => Some(SlotNote::try_new(note)?),
343 None => None,
344 };
345 let starts_at = Timestamp::from_millis(req.starts_at);
346 let ends_at = Timestamp::from_millis(req.ends_at);
347 check_not_past("starts_at", Some(starts_at))?;
348 check_not_past("ends_at", Some(ends_at))?;
349 check_time_range(Some(starts_at), Some(ends_at))?;
350
351 let slots = if req.repeat_weekly {
352 let until = req
353 .until
354 .map(Timestamp::from_millis)
355 .ok_or(AppError::Validation(ValidationError::Invalid {
356 field: "until",
357 reason: "is required with repeat_weekly",
358 }))?;
359 check_not_past("until", Some(until))?;
360 service::appointment_slot::publish_weekly(
361 &st.db,
362 user.get_id(),
363 starts_at,
364 ends_at,
365 note,
366 until,
367 )
368 .await?
369 } else {
370 vec![
371 service::appointment_slot::create(&st.db, user.get_id(), starts_at, ends_at, note)
372 .await?,
373 ]
374 };
375
376 let people = PersonRef::map_of(&[&user]);
377 let items = slots
378 .iter()
379 .map(|slot| SlotResponse::new(slot, &people))
380 .collect();
381 Ok((StatusCode::CREATED, Json(items)))
382}
383
384/// One teacher's window filter, shared by both doors: `me` is the caller,
385/// blank is refused, and a well-formed-but-unknown id stands — it names no
386/// row, so the filtered page is simply empty — while a malformed one is a
387/// 400. Never [`UserId::from_key`] into a nil id: that would read as an
388/// empty 200 instead of the caller's error.
389fn teacher_filter(raw: Option<&str>, caller: &UserId) -> Result<Option<UserId>, AppError> {
390 let Some(raw) = raw else {
391 return Ok(None);
392 };
393 let key = raw.trim();
394 if key.is_empty() {
395 return Err(AppError::Validation(ValidationError::Invalid {
396 field: "teacher",
397 reason: "must not be empty",
398 }));
399 }
400 Ok(Some(match key {
401 "me" => *caller,
402 other => {
403 let id = UserId::from_key(other);
404 if id.uuid().is_nil() {
405 return Err(AppError::Validation(ValidationError::Invalid {
406 field: "teacher",
407 reason: "must be a hyphenated uuid",
408 }));
409 }
410 id
411 }
412 }))
413}
414
415/// A `?starts_after=`/`?starts_before=` instant: unix milliseconds, negative
416/// refused, absent left absent.
417fn starts_bound_filter(field: &'static str, raw: Option<i64>) -> Result<Option<Timestamp>, AppError> {
418 match raw {
419 None => Ok(None),
420 Some(value) if value < 0 => Err(AppError::Validation(ValidationError::Invalid {
421 field,
422 reason: "must not be negative",
423 })),
424 Some(value) => Ok(Some(Timestamp::from_millis(value))),
425 }
426}
427
428/// Optional list filters on the slots door. Absent, the response is the
429/// unfiltered calendar exactly as it has always been.
430#[derive(Debug, Deserialize, IntoParams)]
431struct SlotFilter {
432 /// Narrow to one teacher's slots: `me` for the caller, else a user id.
433 #[param(example = "me")]
434 teacher: Option<String>,
435 /// Keep only slots starting at or after this unix-millisecond instant.
436 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
437 starts_after: Option<i64>,
438}
439
440impl SlotFilter {
441 fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> {
442 teacher_filter(self.teacher.as_deref(), caller)
443 }
444
445 fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> {
446 starts_bound_filter("starts_after", self.starts_after)
447 }
448}
449
450/// List slots, earliest first. Teacher+ see their own calendar, past occurrences
451/// included; everyone else sees every slot that has not started yet — the
452/// bookable calendar, bounded exactly as booking is, so a slot already underway
453/// is left out rather than offered for a request that could only answer `409`.
454/// A demotion below `teacher` withdraws that account's calendar outright, so
455/// there is normally nothing of theirs left to list; a slot an older build
456/// stranded is left out here too (and refused at book time). Whether a slot is
457/// already taken is not carried
458/// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit
459/// `limit` for every slot); returns a `{items, total, limit, offset}` envelope.
460///
461/// Optional filters narrow the answer without ever widening it. `?teacher=`
462/// names one teacher — `me` for the caller, else a user id — and
463/// `?starts_after=` (unix milliseconds, inclusive) keeps the windows that
464/// start at or after the instant, in the SQL so the past is never loaded to
465/// be thrown away. A teacher+ caller's universe is their own calendar, so
466/// `teacher=me` reads the same as absent and naming another teacher is the
467/// empty intersection: a colleague's slots, past ones included, stay
468/// private. For everyone else the universe is the bookable calendar, so a
469/// named teacher's upcoming slots are exactly what the absent call already
470/// offered.
471///
472/// Each slot carries its teacher's `PersonRef` (id, username, name) to *every*
473/// authenticated caller, parents included — deliberate, and not to be
474/// "tightened". A parent's three direct routes to that identity all refuse
475/// (`GET /users/{id}/profile` 403, `/users/search` and `/users` teacher+/admin),
476/// but you cannot pick whom to book a conference with from an anonymous
477/// calendar: this list *is* the staff directory for the booking flow, scoped to
478/// people who published bookable time. Same for the `teacher` / `proposed_by` /
479/// `decided_by` refs on a booking. Pinned by
480/// `tests/regress_appointments.rs::a_parent_reads_the_slot_teachers_identity`.
481// corner-cut: occupancy would be one query per slot with today's domain API; a
482// batch "live bookings for these slots" read would let the list carry it.
483#[utoipa::path(
484 get,
485 path = "/slots",
486 tag = "appointments",
487 security(("session_cookie" = [])),
488 params(PageParams, SlotFilter),
489 responses(
490 (status = 200, description = "A page of slots (all of them when unpaged)", body = Page<SlotResponse>),
491 (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
492 (status = 401, description = "Not authenticated", body = ErrorResponse),
493 ),
494)]
495async fn list_slots(
496 State(st): State<AppState>,
497 CurrentUser(user): CurrentUser,
498 Query(page): Query<PageParams>,
499 Query(filter): Query<SlotFilter>,
500) -> Result<Json<Page<SlotResponse>>, AppError> {
501 let (limit, offset) = page.resolve()?;
502 let narrow_to = filter.resolve_teacher(user.get_id())?;
503 let starts_after = filter.resolve_starts_after()?;
504 let (slots, people) = if user.get_role().at_least(Role::Teacher) {
505 // The calendar arm's universe is the caller's own published rows,
506 // past occurrences included. The `teacher` filter narrows inside it:
507 // `me` is the caller's own calendar (the same rows as absent), and
508 // naming anyone else is the empty intersection — which it must be,
509 // or the param would hand over a colleague's calendar.
510 match narrow_to {
511 Some(other) if other != *user.get_id() => {
512 (Vec::new(), PersonRef::map_of(&[&user]))
513 }
514 _ => (
515 service::appointment_slot::list_calendar(
516 &st.db,
517 user.get_id(),
518 starts_after,
519 )
520 .await?,
521 PersonRef::map_of(&[&user]),
522 ),
523 }
524 } else {
525 let mut slots = service::appointment_slot::list_upcoming(
526 &st.db,
527 Timestamp::now(),
528 narrow_to.as_ref(),
529 starts_after,
530 )
531 .await?;
532 // The teachers' live rows, not the slots' word for it: a demotion
533 // leaves the calendar behind, and an inert slot must not be offered.
534 // Keying the person map off that same read makes the filter free.
535 let mut seen = HashSet::new();
536 let teachers: Vec<UserId> = slots
537 .iter()
538 .map(AppointmentSlot::get_teacher)
539 .filter(|teacher| seen.insert(teacher.key().to_string()))
540 .cloned()
541 .collect();
542 let people: HashMap<String, PersonRef> =
543 crate::service::user::list_by_ids(&st.db, &teachers)
544 .await?
545 .iter()
546 .filter(|teacher| teacher.get_role().at_least(Role::Teacher))
547 .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher)))
548 .collect();
549 slots.retain(|slot| people.contains_key(slot.get_teacher().key().as_str()));
550 (slots, people)
551 };
552 let total = slots.len() as i64;
553 // Paged in the web layer: slots of demoted teachers are dropped above.
554 let items = paginate(&slots, limit, offset)
555 .iter()
556 .map(|slot| SlotResponse::new(slot, &people))
557 .collect();
558 Ok(Json(Page::new(items, total, limit, offset)))
559}
560
561/// Withdraw one slot. Requires teacher+; the publishing teacher may drop their
562/// own and managers/admins anyone's. A slot carrying a pending or approved
563/// booking is refused (`409`) — reject or cancel that booking first. Settled
564/// bookings (rejected/cancelled) go with the slot.
565#[utoipa::path(
566 delete,
567 path = "/slots/{id}",
568 tag = "appointments",
569 security(("session_cookie" = [])),
570 params(("id" = String, Path, description = "Slot id")),
571 responses(
572 (status = 204, description = "Deleted"),
573 (status = 401, description = "Not authenticated", body = ErrorResponse),
574 (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
575 (status = 404, description = "Not found", body = ErrorResponse),
576 (status = 409, description = "The slot has a pending or approved booking", body = ErrorResponse),
577 ),
578)]
579async fn delete_slot(
580 State(st): State<AppState>,
581 RequireTeacher(user): RequireTeacher,
582 Path(id): Path<String>,
583) -> Result<StatusCode, AppError> {
584 let slot = service::appointment_slot::read(&st.db, &AppointmentSlotId::from_key(&id))
585 .await?
586 .ok_or(AppError::NotFound)?;
587 if !can_manage(&slot, &user) {
588 return Err(AppError::Forbidden(
589 "only the slot's teacher or a manager/admin can delete it",
590 ));
591 }
592 service::appointment_slot::delete(&st.db, slot).await?;
593 Ok(StatusCode::NO_CONTENT)
594}
595
596/// Withdraw a whole recurring publish. Same rights as the single delete, and
597/// all-or-nothing: if *any* occurrence still carries a pending or approved
598/// booking the entire series is refused (`409`), so the person waiting is dealt
599/// with rather than silently left on a stray week.
600#[utoipa::path(
601 delete,
602 path = "/slots/series/{series}",
603 tag = "appointments",
604 security(("session_cookie" = [])),
605 params(("series" = String, Path, description = "Series id, from a slot's `series` field")),
606 responses(
607 (status = 204, description = "Deleted"),
608 (status = 401, description = "Not authenticated", body = ErrorResponse),
609 (status = 403, description = "Not the series' teacher (and not a manager/admin)", body = ErrorResponse),
610 (status = 404, description = "No such series", body = ErrorResponse),
611 (status = 409, description = "Some occurrence has a pending or approved booking", body = ErrorResponse),
612 ),
613)]
614async fn delete_slot_series(
615 State(st): State<AppState>,
616 RequireTeacher(user): RequireTeacher,
617 Path(series): Path<String>,
618) -> Result<StatusCode, AppError> {
619 let series = SlotSeries::from_key(&series);
620 // Every occurrence of one publish carries the same teacher, so the first
621 // row answers the ownership question for all of them.
622 let slot = service::appointment_slot::list_for_series(&st.db, &series)
623 .await?
624 .into_iter()
625 .next()
626 .ok_or(AppError::NotFound)?;
627 if !can_manage(&slot, &user) {
628 return Err(AppError::Forbidden(
629 "only the slot's teacher or a manager/admin can delete it",
630 ));
631 }
632 service::appointment_slot::delete_series(&st.db, &series).await?;
633 Ok(StatusCode::NO_CONTENT)
634}
635
636// ---- bookings -------------------------------------------------------------
637
638/// Ask for a meeting on a published slot. Students and parents only — a parent
639/// books for *themselves* (this is the parent-teacher conference), never on
640/// behalf of a child, and staff arrange between themselves off this API. The
641/// booking lands `pending`: publishing availability is not consent to a
642/// particular person and topic. Refused (`409`) when the slot's window has already
643/// opened, when it is already taken, when the requester is already committed at
644/// that time, or when the slot's teacher no longer holds a teaching role.
645#[utoipa::path(
646 post,
647 path = "/",
648 tag = "appointments",
649 security(("session_cookie" = [])),
650 request_body = BookAppointment,
651 responses(
652 (status = 201, description = "Booking requested", body = AppointmentResponse),
653 (status = 400, description = "Missing or over-long reason", body = ErrorResponse),
654 (status = 401, description = "Not authenticated", body = ErrorResponse),
655 (status = 403, description = "Only students and parents book appointments", body = ErrorResponse),
656 (status = 404, description = "Slot not found", body = ErrorResponse),
657 (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse),
658 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
659 ),
660)]
661async fn book(
662 State(st): State<AppState>,
663 CurrentUser(user): CurrentUser,
664 Json(req): Json<BookAppointment>,
665) -> Result<(StatusCode, Json<AppointmentResponse>), AppError> {
666 if !matches!(user.get_role(), Role::Student | Role::Parent) {
667 return Err(AppError::Forbidden(
668 "only students and parents can book an appointment",
669 ));
670 }
671 let slot_id = AppointmentSlotId::from_key(&req.slot);
672 let slot = service::appointment_slot::read(&st.db, &slot_id)
673 .await?
674 .ok_or(AppError::NotFound)?;
675 // The slot row is not the grant: a teacher demoted since publishing keeps
676 // their rows, and those rows must be inert. Their live role decides.
677 if !crate::service::user::read(&st.db, slot.get_teacher())
678 .await?
679 .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher))
680 {
681 return Err(AppError::Conflict(
682 "the slot's teacher no longer holds a teaching role",
683 ));
684 }
685 let reason = AppointmentReason::try_new(&req.reason)?;
686 let appointment = service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?;
687 Ok((
688 StatusCode::CREATED,
689 one_appointment(appointment, &st.db).await?,
690 ))
691}
692
693/// Optional list filters on the bookings door. Absent, the response is the
694/// caller's listing exactly as it has always been.
695#[derive(Debug, Deserialize, IntoParams)]
696struct AppointmentFilter {
697 /// Narrow to one booking state: `pending`, `approved`, `rejected` or
698 /// `cancelled`.
699 #[param(example = "pending")]
700 status: Option<String>,
701 /// Keep only meetings starting at or after this unix-millisecond instant.
702 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
703 starts_after: Option<i64>,
704 /// Keep only meetings starting before this unix-millisecond instant —
705 /// exclusive, so `[starts_after, starts_before)` is a closed-open month.
706 #[param(minimum = 0, example = 1_760_259_199_999_i64)]
707 starts_before: Option<i64>,
708 /// Narrow to bookings on one teacher's slots: `me` for the caller, else
709 /// a user id.
710 #[param(example = "me")]
711 teacher: Option<String>,
712}
713
714impl AppointmentFilter {
715 /// The wire word against the closed vocabulary the rows store
716 /// ([`AppointmentStatus::as_str`]): an unknown or blank word is a 400
717 /// naming the field, never a silent whole-list read.
718 fn resolve_status(&self) -> Result<Option<AppointmentStatus>, AppError> {
719 const STATUSES: [AppointmentStatus; 4] = [
720 AppointmentStatus::Pending,
721 AppointmentStatus::Approved,
722 AppointmentStatus::Rejected,
723 AppointmentStatus::Cancelled,
724 ];
725 let Some(raw) = self.status.as_deref() else {
726 return Ok(None);
727 };
728 let word = raw.trim();
729 if word.is_empty() {
730 return Err(AppError::Validation(ValidationError::Invalid {
731 field: "status",
732 reason: "must not be empty",
733 }));
734 }
735 STATUSES
736 .into_iter()
737 .find(|status| status.as_str() == word)
738 .map(Some)
739 .ok_or_else(|| {
740 AppError::Validation(ValidationError::Invalid {
741 field: "status",
742 reason: "must be one of: pending, approved, rejected, cancelled",
743 })
744 })
745 }
746
747 fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> {
748 starts_bound_filter("starts_after", self.starts_after)
749 }
750
751 fn resolve_starts_before(&self) -> Result<Option<Timestamp>, AppError> {
752 starts_bound_filter("starts_before", self.starts_before)
753 }
754
755 fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> {
756 teacher_filter(self.teacher.as_deref(), caller)
757 }
758}
759
760/// List bookings, newest first. Students and parents see the ones they
761/// requested; teacher+ see the ones aimed at their own slots — their request
762/// inbox. Managers and admins read their own inbox too (they may still decide
763/// any booking by id). Paged via `?limit=&offset=` (omit `limit` for every
764/// booking); returns a `{items, total, limit, offset}` envelope.
765///
766/// Optional filters narrow the answer without ever widening it. `?status=`
767/// is one of `pending`, `approved`, `rejected`, `cancelled`; `?starts_after=`
768/// and `?starts_before=` (unix milliseconds) keep the meetings whose start
769/// sits in `[after, before)` — a standing proposal's time when one stands,
770/// the slot's window otherwise, so a booking whose slot is gone (no window
771/// at all) is left out; `?teacher=` names the booked slot's teacher, `me` or
772/// a user id, joined through the slot. A teacher+ caller's universe is their
773/// own inbox, so `teacher=me` reads the same as absent and naming another
774/// teacher is the empty intersection rather than a read of that teacher's
775/// inbox.
776#[utoipa::path(
777 get,
778 path = "/",
779 tag = "appointments",
780 security(("session_cookie" = [])),
781 params(PageParams, AppointmentFilter),
782 responses(
783 (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<AppointmentResponse>),
784 (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
785 (status = 401, description = "Not authenticated", body = ErrorResponse),
786 ),
787)]
788async fn list_appointments(
789 State(st): State<AppState>,
790 CurrentUser(user): CurrentUser,
791 Query(page): Query<PageParams>,
792 Query(filter): Query<AppointmentFilter>,
793) -> Result<Json<Page<AppointmentResponse>>, AppError> {
794 let (limit, offset) = page.resolve()?;
795 let status = filter.resolve_status()?;
796 let starts_after = filter.resolve_starts_after()?;
797 let starts_before = filter.resolve_starts_before()?;
798 let narrow_to = filter.resolve_teacher(user.get_id())?;
799 let (rows, total) = if user.get_role().at_least(Role::Teacher) {
800 // The inbox arm's universe is the caller's own bookings; the
801 // `teacher` filter narrows inside it, so naming another teacher is
802 // the empty intersection — see the slots door, same rule.
803 match narrow_to {
804 Some(other) if other != *user.get_id() => (Vec::new(), 0),
805 _ => {
806 service::appointment::list_for_teacher(
807 &st.db,
808 user.get_id(),
809 status,
810 starts_after,
811 starts_before,
812 limit,
813 offset,
814 )
815 .await?
816 }
817 }
818 } else {
819 service::appointment::list_for_requester(
820 &st.db,
821 user.get_id(),
822 service::appointment::RequesterListParams {
823 status,
824 starts_after,
825 starts_before,
826 teacher: narrow_to.as_ref(),
827 limit,
828 offset,
829 },
830 )
831 .await?
832 };
833 // Join slots and people onto the page alone — the lookup shrinks with it.
834 let items = appointment_responses(&rows, &st.db).await?;
835 Ok(Json(Page::new(items, total, limit, offset)))
836}
837
838/// Confirm a pending booking. Requires teacher+ and ownership of the slot (or
839/// manager/admin). The double-booking guard runs here, against both sides:
840/// approval is what commits anyone, so a time colliding with another approved
841/// meeting of the teacher or of the requester is refused (`409`), as is a
842/// window that has already started — that meeting could never be cancelled.
843///
844/// Refused (`409`) too while a counter-proposal stands: the proposed time is
845/// the teacher's own, so confirming it here would commit the requester to a
846/// time they never agreed to. Answering a proposal is the requester's alone:
847/// `PATCH /{id}/reschedule/accept` (which *is* approval, at the proposed time)
848/// or `PATCH /{id}/reschedule/decline` (which cancels the booking).
849#[utoipa::path(
850 patch,
851 path = "/{id}/approve",
852 tag = "appointments",
853 security(("session_cookie" = [])),
854 params(("id" = String, Path, description = "Appointment id")),
855 responses(
856 (status = 200, description = "Approved", body = AppointmentResponse),
857 (status = 401, description = "Not authenticated", body = ErrorResponse),
858 (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
859 (status = 404, description = "Not found", body = ErrorResponse),
860 (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),
861 ),
862)]
863async fn approve(
864 State(st): State<AppState>,
865 RequireTeacher(user): RequireTeacher,
866 Path(id): Path<String>,
867) -> Result<Json<AppointmentResponse>, AppError> {
868 let id = AppointmentId::from_key(&id);
869 for_decision(&id, &user, &st.db).await?;
870 let appointment = service::appointment::approve(&st.db, &id, user.get_id()).await?;
871 one_appointment(appointment, &st.db).await
872}
873
874/// Turn a pending booking down. Requires teacher+ and ownership of the slot (or
875/// manager/admin). The slot frees up immediately — occupancy counts live
876/// bookings only, so someone else may take it.
877#[utoipa::path(
878 patch,
879 path = "/{id}/reject",
880 tag = "appointments",
881 security(("session_cookie" = [])),
882 params(("id" = String, Path, description = "Appointment id")),
883 request_body(content = RejectRequest, description = "Optional rejection reason; the whole body may be omitted"),
884 responses(
885 (status = 200, description = "Rejected", body = AppointmentResponse),
886 (status = 400, description = "Reason is over-long", body = ErrorResponse),
887 (status = 401, description = "Not authenticated", body = ErrorResponse),
888 (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
889 (status = 404, description = "Not found", body = ErrorResponse),
890 (status = 409, description = "No longer pending", body = ErrorResponse),
891 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
892 ),
893)]
894async fn reject(
895 State(st): State<AppState>,
896 RequireTeacher(user): RequireTeacher,
897 Path(id): Path<String>,
898 body: Option<Json<RejectRequest>>,
899) -> Result<Json<AppointmentResponse>, AppError> {
900 let id = AppointmentId::from_key(&id);
901 for_decision(&id, &user, &st.db).await?;
902 // A blank or absent reason records none; a present one is validated (400 if
903 // over-long) before it reaches the row.
904 let reason = match body.and_then(|Json(req)| req.reason) {
905 Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?),
906 _ => None,
907 };
908 let appointment = service::appointment::reject(&st.db, &id, user.get_id(), reason).await?;
909 one_appointment(appointment, &st.db).await
910}
911
912/// Call a meeting off. **The requester only** — the person who asked for it —
913/// from either live state, so an approved meeting can still be dropped and the
914/// slot freed. Anyone else is a `403`, the slot's teacher and a manager/admin
915/// included (the guard compares ids, not roles): a teacher ends a booking by
916/// **rejecting** it while it is `pending`, and an already-approved one by
917/// counter-proposing another time (`PATCH /{id}/reschedule` — which sends it
918/// back to `pending`) and then rejecting it. Refused (`409`) once the meeting's
919/// window has started: a meeting that already began is history, not a plan.
920#[utoipa::path(
921 patch,
922 path = "/{id}/cancel",
923 tag = "appointments",
924 security(("session_cookie" = [])),
925 params(("id" = String, Path, description = "Appointment id")),
926 request_body(content = CancelRequest, description = "Optional cancellation reason; the whole body may be omitted"),
927 responses(
928 (status = 200, description = "Cancelled", body = AppointmentResponse),
929 (status = 400, description = "Reason is over-long", body = ErrorResponse),
930 (status = 401, description = "Not authenticated", body = ErrorResponse),
931 (status = 403, description = "Not the requester", body = ErrorResponse),
932 (status = 404, description = "Not found", body = ErrorResponse),
933 (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse),
934 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
935 ),
936)]
937async fn cancel(
938 State(st): State<AppState>,
939 CurrentUser(user): CurrentUser,
940 Path(id): Path<String>,
941 body: Option<Json<CancelRequest>>,
942) -> Result<Json<AppointmentResponse>, AppError> {
943 let id = AppointmentId::from_key(&id);
944 let appointment = service::appointment::read(&st.db, &id)
945 .await?
946 .ok_or(AppError::NotFound)?;
947 // Only the requester (student/parent) may cancel. Teachers/managers end a
948 // booking by rejecting (while pending) or rescheduling — never cancelling.
949 if appointment.get_requester() != user.get_id() {
950 return Err(AppError::Forbidden(
951 "only the requester can cancel this appointment",
952 ));
953 }
954 // A blank or absent reason records none; a present one is validated (400 if
955 // over-long) before it reaches the row.
956 let reason = match body.and_then(|Json(req)| req.reason) {
957 Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?),
958 _ => None,
959 };
960 // The started-window guard lives in `service::appointment::cancel`, under
961 // the lock and on a fresh read — a pre-lock copy of it here would only be
962 // a staler second opinion, and `decline_reschedule` would still bypass it.
963 let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), reason).await?;
964 one_appointment(appointment, &st.db).await
965}
966
967/// Counter-propose another time for a booking, on the same row (the reason and
968/// the history stay in one place). Requires teacher+ and ownership of the slot
969/// (or manager/admin).
970///
971/// **The proposal sends the booking back to `pending` and clears
972/// `decided_by`** — an already-approved meeting is *not* committed at the new
973/// time until the requester accepts it at
974/// `PATCH /appointments/{id}/reschedule/accept`, since leaving it approved
975/// would silently move a confirmed appointment. The slot stays held meanwhile.
976///
977/// Refused (`409`) when the proposed window has already opened — the 60-second
978/// skew grace on the times is for clock drift, not for proposing into a meeting
979/// that is already underway, which `cancel` would then refuse to undo.
980#[utoipa::path(
981 patch,
982 path = "/{id}/reschedule",
983 tag = "appointments",
984 security(("session_cookie" = [])),
985 params(("id" = String, Path, description = "Appointment id")),
986 request_body = Reschedule,
987 responses(
988 (status = 200, description = "Proposed; the booking is pending again", body = AppointmentResponse),
989 (status = 400, description = "Invalid time range or times in the past", body = ErrorResponse),
990 (status = 401, description = "Not authenticated", body = ErrorResponse),
991 (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse),
992 (status = 404, description = "Not found", body = ErrorResponse),
993 (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse),
994 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
995 ),
996)]
997async fn reschedule(
998 State(st): State<AppState>,
999 RequireTeacher(user): RequireTeacher,
1000 Path(id): Path<String>,
1001 Json(req): Json<Reschedule>,
1002) -> Result<Json<AppointmentResponse>, AppError> {
1003 let starts_at = Timestamp::from_millis(req.starts_at);
1004 let ends_at = Timestamp::from_millis(req.ends_at);
1005 check_not_past("starts_at", Some(starts_at))?;
1006 check_not_past("ends_at", Some(ends_at))?;
1007 check_time_range(Some(starts_at), Some(ends_at))?;
1008
1009 let id = AppointmentId::from_key(&id);
1010 for_decision(&id, &user, &st.db).await?;
1011 let appointment =
1012 service::appointment::propose(&st.db, &id, starts_at, ends_at, user.get_id()).await?;
1013 one_appointment(appointment, &st.db).await
1014}
1015
1016/// Accept the teacher's counter-proposal. The requester's call alone — it is
1017/// their commitment. Accepting *is* approval at the proposed time, so the
1018/// double-booking guard runs again for both sides (`409` if the moved time now
1019/// collides with something else, or has already started — agreeing to a window
1020/// that began would mint a meeting nobody can cancel).
1021///
1022/// The body **names the proposal being accepted** (`proposed_starts_at` /
1023/// `proposed_ends_at`, copied from the booking as it was read). A teacher may
1024/// re-propose at any time, and the two calls are minutes apart, so without the
1025/// pin the teacher would choose which window the requester's click commits
1026/// them to. A superseded proposal answers `409` — re-read the booking and
1027/// accept (or decline) the new one.
1028#[utoipa::path(
1029 patch,
1030 path = "/{id}/reschedule/accept",
1031 tag = "appointments",
1032 security(("session_cookie" = [])),
1033 params(("id" = String, Path, description = "Appointment id")),
1034 request_body = AcceptReschedule,
1035 responses(
1036 (status = 200, description = "Approved at the proposed time", body = AppointmentResponse),
1037 (status = 400, description = "Missing or unreadable body", body = ErrorResponse),
1038 (status = 401, description = "Not authenticated", body = ErrorResponse),
1039 (status = 403, description = "Not the requester", body = ErrorResponse),
1040 (status = 404, description = "Not found", body = ErrorResponse),
1041 (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),
1042 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1043 ),
1044)]
1045async fn accept_reschedule(
1046 State(st): State<AppState>,
1047 CurrentUser(user): CurrentUser,
1048 Path(id): Path<String>,
1049 Json(req): Json<AcceptReschedule>,
1050) -> Result<Json<AppointmentResponse>, AppError> {
1051 let id = AppointmentId::from_key(&id);
1052 ensure_requester(&id, &user, &st.db).await?;
1053 // Unvalidated on purpose: these are not a time to meet, they are the
1054 // requester's answer to "which proposal?" — the domain compares them to the
1055 // row and refuses anything else, so a past or inverted pair is simply a
1056 // mismatch (409), never a booking.
1057 let appointment = service::appointment::accept_proposal(
1058 &st.db,
1059 &id,
1060 user.get_id(),
1061 Timestamp::from_millis(req.proposed_starts_at),
1062 Timestamp::from_millis(req.proposed_ends_at),
1063 )
1064 .await?;
1065 one_appointment(appointment, &st.db).await
1066}
1067
1068/// Refuse the teacher's counter-proposal. The requester's call alone, and it
1069/// **cancels the booking**: the proposal replaced the time that was asked for,
1070/// so there is nothing left to fall back to — book another slot instead. The
1071/// slot frees up, and the original request stays readable as `cancelled` with
1072/// the refused proposal still on it. Declining is a cancel, so it answers to
1073/// the same deadline: `409` once the meeting's effective window has started.
1074#[utoipa::path(
1075 patch,
1076 path = "/{id}/reschedule/decline",
1077 tag = "appointments",
1078 security(("session_cookie" = [])),
1079 params(("id" = String, Path, description = "Appointment id")),
1080 responses(
1081 (status = 200, description = "Cancelled", body = AppointmentResponse),
1082 (status = 401, description = "Not authenticated", body = ErrorResponse),
1083 (status = 403, description = "Not the requester", body = ErrorResponse),
1084 (status = 404, description = "Not found", body = ErrorResponse),
1085 (status = 409, description = "No time has been proposed, the booking is already settled, or the meeting's window has already started", body = ErrorResponse),
1086 ),
1087)]
1088async fn decline_reschedule(
1089 State(st): State<AppState>,
1090 CurrentUser(user): CurrentUser,
1091 Path(id): Path<String>,
1092) -> Result<Json<AppointmentResponse>, AppError> {
1093 let id = AppointmentId::from_key(&id);
1094 let appointment = ensure_requester(&id, &user, &st.db).await?;
1095 if appointment.get_proposed_starts_at().is_none() {
1096 return Err(AppError::Conflict("no time has been proposed"));
1097 }
1098 let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), None).await?;
1099 one_appointment(appointment, &st.db).await
1100}
1101
1102/// The booking, insisting the caller is the person who asked for it — the only
1103/// one who can answer a counter-proposal.
1104async fn ensure_requester(
1105 id: &AppointmentId,
1106 user: &User,
1107 db: &Database,
1108) -> Result<Appointment, AppError> {
1109 let appointment = service::appointment::read(db, id)
1110 .await?
1111 .ok_or(AppError::NotFound)?;
1112 if appointment.get_requester() != user.get_id() {
1113 return Err(AppError::Forbidden(
1114 "only the requester can answer a counter-proposal",
1115 ));
1116 }
1117 Ok(appointment)
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122 use super::*;
1123 use crate::database::init_test_db;
1124 use crate::domain::user::Username;
1125
1126 /// A user at `role`, minted through the real create path.
1127 async fn user(username: &str, role: Role, db: &Database) -> User {
1128 let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None)
1129 .await
1130 .unwrap();
1131 crate::service::user::set_role(db, user.get_id(), role)
1132 .await
1133 .unwrap()
1134 .0
1135 }
1136
1137 /// All five `can_manage` sites are `RequireTeacher` today, so this is
1138 /// pinned at the helper — the level where the floor is observable, and the
1139 /// level that has to hold when the next route arrives with `CurrentUser`.
1140 #[tokio::test]
1141 async fn demoted_slot_owner_loses_management() {
1142 let (db, _leases) = init_test_db().await;
1143 let owner = user("ogretmen", Role::Teacher, &db).await;
1144 let slot = service::appointment_slot::create(
1145 &db,
1146 owner.get_id(),
1147 Timestamp::from_millis(1_000),
1148 Timestamp::from_millis(2_000),
1149 None,
1150 )
1151 .await
1152 .unwrap();
1153 assert!(can_manage(&slot, &owner));
1154
1155 for role in [Role::Student, Role::Parent] {
1156 let demoted = crate::service::user::set_role(&db, owner.get_id(), role)
1157 .await
1158 .unwrap()
1159 .0;
1160 assert!(
1161 !can_manage(&slot, &demoted),
1162 "{role:?} slot owner still decides its bookings"
1163 );
1164 }
1165 // Never orphaned: manager+ still decides everything on the slot.
1166 let boss = user("mudur", Role::Manager, &db).await;
1167 assert!(can_manage(&slot, &boss));
1168 }
1169
1170 // ---- the list filters ---------------------------------------------------
1171
1172 /// The handlers under test touch `db` alone, but [`AppState`] wants all
1173 /// of its pieces — built here off the sandboxed per-test database.
1174 async fn a_state(db: &Database) -> AppState {
1175 AppState {
1176 db: db.clone(),
1177 tenants: crate::database::init_test_tenants().await,
1178 files_path: std::env::temp_dir(),
1179 cookie_secure: false,
1180 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
1181 chatbot_limit: Default::default(),
1182 rag_limit: Default::default(),
1183 exam_presence: Default::default(),
1184 board_hub: Default::default(),
1185 ai: None,
1186 metrics: crate::telemetry::Metrics::noop(),
1187 }
1188 }
1189
1190 /// One published slot at an absolute instant.
1191 async fn a_slot(db: &Database, teacher: &UserId, starts_at: i64, ends_at: i64) {
1192 service::appointment_slot::create(
1193 db,
1194 teacher,
1195 Timestamp::from_millis(starts_at),
1196 Timestamp::from_millis(ends_at),
1197 None,
1198 )
1199 .await
1200 .unwrap();
1201 }
1202
1203 /// The slots door, unpaged.
1204 async fn slots(st: &AppState, who: &User, filter: SlotFilter) -> Page<SlotResponse> {
1205 list_slots(
1206 State(st.clone()),
1207 CurrentUser(who.clone()),
1208 Query(PageParams {
1209 limit: None,
1210 offset: None,
1211 }),
1212 Query(filter),
1213 )
1214 .await
1215 .unwrap()
1216 .0
1217 }
1218
1219 /// The bookings door, unpaged.
1220 async fn bookings(
1221 st: &AppState,
1222 who: &User,
1223 filter: AppointmentFilter,
1224 ) -> Page<AppointmentResponse> {
1225 list_appointments(
1226 State(st.clone()),
1227 CurrentUser(who.clone()),
1228 Query(PageParams {
1229 limit: None,
1230 offset: None,
1231 }),
1232 Query(filter),
1233 )
1234 .await
1235 .unwrap()
1236 .0
1237 }
1238
1239 /// Blank, malformed, and negative filter words are 400s naming the
1240 /// field; `me` is the caller; a well-formed stranger stands (and names
1241 /// an empty page — pinned by the handler-level tests).
1242 #[test]
1243 fn filter_words_refuse_blank_malformed_and_negative() {
1244 let caller = UserId::generate();
1245
1246 for word in ["", " ", "not-a-uuid"] {
1247 let filter = SlotFilter {
1248 teacher: Some(word.into()),
1249 starts_after: None,
1250 };
1251 assert!(
1252 matches!(
1253 filter.resolve_teacher(&caller),
1254 Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "teacher"
1255 ),
1256 "`{word}` must refuse as `teacher`"
1257 );
1258 }
1259 assert_eq!(
1260 SlotFilter {
1261 teacher: Some("me".into()),
1262 starts_after: None,
1263 }
1264 .resolve_teacher(&caller)
1265 .unwrap(),
1266 Some(caller)
1267 );
1268 let stranger = UserId::generate();
1269 assert_eq!(
1270 SlotFilter {
1271 teacher: Some(stranger.key()),
1272 starts_after: None,
1273 }
1274 .resolve_teacher(&caller)
1275 .unwrap(),
1276 Some(stranger)
1277 );
1278
1279 let filter = SlotFilter {
1280 teacher: None,
1281 starts_after: Some(-1),
1282 };
1283 assert!(matches!(
1284 filter.resolve_starts_after(),
1285 Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_after"
1286 ));
1287 assert_eq!(
1288 SlotFilter {
1289 teacher: None,
1290 starts_after: Some(0),
1291 }
1292 .resolve_starts_after()
1293 .unwrap()
1294 .map(|instant| instant.as_millis()),
1295 Some(0)
1296 );
1297
1298 let filter = AppointmentFilter {
1299 status: None,
1300 starts_after: None,
1301 starts_before: Some(-5),
1302 teacher: None,
1303 };
1304 assert!(matches!(
1305 filter.resolve_starts_before(),
1306 Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_before"
1307 ));
1308
1309 // The closed status vocabulary: exact wire words only — no case
1310 // play, no blank, no synonym — mirroring what the rows store.
1311 let status = |word: Option<&str>| AppointmentFilter {
1312 status: word.map(str::to_string),
1313 starts_after: None,
1314 starts_before: None,
1315 teacher: None,
1316 };
1317 assert_eq!(status(None).resolve_status().unwrap(), None);
1318 assert_eq!(
1319 status(Some(" pending ")).resolve_status().unwrap(),
1320 Some(AppointmentStatus::Pending)
1321 );
1322 assert_eq!(
1323 status(Some("cancelled")).resolve_status().unwrap(),
1324 Some(AppointmentStatus::Cancelled)
1325 );
1326 for word in ["", " ", "APPROVED", "live", "confirmed"] {
1327 assert!(
1328 matches!(
1329 status(Some(word)).resolve_status(),
1330 Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "status"
1331 ),
1332 "`{word}` must refuse as `status`"
1333 );
1334 }
1335 }
1336
1337 /// The slots door: absent filters are today's response per role —
1338 /// teacher+ read their own calendar with the past included, everyone
1339 /// else reads the bookable calendar — `teacher=me` is the caller's own
1340 /// set, a named other teacher narrows the bookable calendar but never
1341 /// opens a colleague's calendar, and `starts_after` cuts with `total`
1342 /// reporting the filtered count.
1343 #[tokio::test]
1344 async fn slot_filters_narrow_without_widening() {
1345 let (db, _leases) = init_test_db().await;
1346 let st = a_state(&db).await;
1347 let now = Timestamp::now().as_millis();
1348 let ali = user("ali-ogretmen", Role::Teacher, &db).await;
1349 let ayse = user("ayse-ogretmen", Role::Teacher, &db).await;
1350 let veli = user("veli-veli", Role::Student, &db).await;
1351
1352 a_slot(&db, ali.get_id(), now - 10_000, now - 5_000).await; // ali's past
1353 a_slot(&db, ali.get_id(), now + 5_000, now + 10_000).await;
1354 a_slot(&db, ali.get_id(), now + 60_000, now + 90_000).await;
1355 a_slot(&db, ayse.get_id(), now + 30_000, now + 40_000).await;
1356
1357 let none = || SlotFilter {
1358 teacher: None,
1359 starts_after: None,
1360 };
1361 let me = || SlotFilter {
1362 teacher: Some("me".into()),
1363 starts_after: None,
1364 };
1365 let of = |who: &UserId| SlotFilter {
1366 teacher: Some(who.key()),
1367 starts_after: None,
1368 };
1369
1370 // Student, no filters: the bookable calendar — ali's past stays out,
1371 // earliest first, exactly as the absent call has always answered.
1372 let page = slots(&st, &veli, none()).await;
1373 assert_eq!(page.total, 3);
1374 let starts: Vec<i64> = page.items.iter().map(|slot| slot.starts_at).collect();
1375 let mut sorted = starts.clone();
1376 sorted.sort_unstable();
1377 assert_eq!(starts, sorted);
1378
1379 // Student, teacher=me: they publish nothing — an empty page, not an
1380 // error.
1381 let page = slots(&st, &veli, me()).await;
1382 assert_eq!((page.items.len(), page.total), (0, 0));
1383
1384 // Student, teacher=ali: exactly ali's upcoming pair — a narrowing of
1385 // the calendar they may already see, his past slot still private.
1386 let page = slots(&st, &veli, of(ali.get_id())).await;
1387 assert_eq!(page.total, 2);
1388 assert!(
1389 page.items
1390 .iter()
1391 .all(|slot| slot.teacher.id == ali.get_id().key() && slot.starts_at > now)
1392 );
1393
1394 // Student, teacher=<well-formed nobody>: an empty page, not a 404.
1395 let page = slots(&st, &veli, of(&UserId::generate())).await;
1396 assert_eq!((page.items.len(), page.total), (0, 0));
1397
1398 // Teacher, no filters: their own calendar, past occurrences
1399 // included — today's arm.
1400 let page = slots(&st, &ali, none()).await;
1401 assert_eq!(page.total, 3);
1402
1403 // Teacher, teacher=me: the same calendar as absent.
1404 let page = slots(&st, &ali, me()).await;
1405 assert_eq!(page.total, 3);
1406
1407 // Teacher, teacher=ayse: the empty intersection. Naming a colleague
1408 // must not hand over their calendar, past rows included.
1409 let page = slots(&st, &ali, of(ayse.get_id())).await;
1410 assert_eq!((page.items.len(), page.total), (0, 0));
1411
1412 // Teacher, starts_after=now: the past occurrence is cut in the SQL,
1413 // and total is the filtered count.
1414 let page = slots(
1415 &st,
1416 &ali,
1417 SlotFilter {
1418 teacher: None,
1419 starts_after: Some(now),
1420 },
1421 )
1422 .await;
1423 assert_eq!(page.total, 2);
1424 assert!(page.items.iter().all(|slot| slot.starts_at >= now));
1425
1426 // Both filters together, on the student arm.
1427 let page = slots(
1428 &st,
1429 &veli,
1430 SlotFilter {
1431 teacher: Some(ayse.get_id().key()),
1432 starts_after: Some(now),
1433 },
1434 )
1435 .await;
1436 assert_eq!(page.total, 1);
1437 assert_eq!(page.items[0].starts_at, now + 30_000);
1438 }
1439
1440 /// The bookings door: `status` and `starts_after` (the meeting's
1441 /// effective start) narrow each side's own listing, `teacher` joins
1442 /// through the slot, and a teacher+ caller naming another teacher gets
1443 /// the empty intersection — never that teacher's inbox.
1444 #[tokio::test]
1445 async fn booking_filters_narrow_without_widening() {
1446 let (db, _leases) = init_test_db().await;
1447 let st = a_state(&db).await;
1448 let now = Timestamp::now().as_millis();
1449 let ali = user("ali-ogretmen", Role::Teacher, &db).await;
1450 let ayse = user("ayse-ogretmen", Role::Teacher, &db).await;
1451 let veli = user("veli-veli", Role::Student, &db).await;
1452 let reason = AppointmentReason::try_new("görüşme").unwrap();
1453
1454 let ali_slot = service::appointment_slot::create(
1455 &db,
1456 ali.get_id(),
1457 Timestamp::from_millis(now + 60_000),
1458 Timestamp::from_millis(now + 120_000),
1459 None,
1460 )
1461 .await
1462 .unwrap();
1463 let ayse_slot = service::appointment_slot::create(
1464 &db,
1465 ayse.get_id(),
1466 Timestamp::from_millis(now + 200_000),
1467 Timestamp::from_millis(now + 260_000),
1468 None,
1469 )
1470 .await
1471 .unwrap();
1472 let pending =
1473 service::appointment::book(&db, ali_slot.get_id(), veli.get_id(), reason.clone())
1474 .await
1475 .unwrap();
1476 let approved =
1477 service::appointment::book(&db, ayse_slot.get_id(), veli.get_id(), reason.clone())
1478 .await
1479 .unwrap();
1480 service::appointment::approve(&db, approved.get_id(), ayse.get_id())
1481 .await
1482 .unwrap();
1483
1484 let none = || AppointmentFilter {
1485 status: None,
1486 starts_after: None,
1487 starts_before: None,
1488 teacher: None,
1489 };
1490 let status = |word: &str| AppointmentFilter {
1491 status: Some(word.into()),
1492 starts_after: None,
1493 starts_before: None,
1494 teacher: None,
1495 };
1496 let after = |millis: i64| AppointmentFilter {
1497 status: None,
1498 starts_after: Some(millis),
1499 starts_before: None,
1500 teacher: None,
1501 };
1502 let with_teacher = |who: &User| AppointmentFilter {
1503 status: None,
1504 starts_after: None,
1505 starts_before: None,
1506 teacher: Some(who.get_id().key()),
1507 };
1508
1509 // Student, no filters: both bookings — today's response.
1510 let page = bookings(&st, &veli, none()).await;
1511 assert_eq!(page.total, 2);
1512
1513 // status: only the approved one; total is the filtered count.
1514 let page = bookings(&st, &veli, status("approved")).await;
1515 assert_eq!(page.total, 1);
1516 assert_eq!(page.items[0].id, approved.get_id().key());
1517 assert_eq!(page.items[0].status, "approved");
1518
1519 // A state nothing carries: an empty page, not an error.
1520 let page = bookings(&st, &veli, status("rejected")).await;
1521 assert_eq!((page.items.len(), page.total), (0, 0));
1522
1523 // teacher: joined through the slot — only the bookings on ali's.
1524 let page = bookings(&st, &veli, with_teacher(&ali)).await;
1525 assert_eq!(page.total, 1);
1526 assert_eq!(page.items[0].id, pending.get_id().key());
1527
1528 // starts_after judges the meeting's effective start: the slot's
1529 // window while no proposal stands.
1530 let page = bookings(&st, &veli, after(now + 150_000)).await;
1531 assert_eq!(page.total, 1);
1532 assert_eq!(page.items[0].id, approved.get_id().key());
1533
1534 // starts_before through the door: the late meeting sits outside a
1535 // window ending at now + 150_000, the early one inside it.
1536 let page = bookings(
1537 &st,
1538 &veli,
1539 AppointmentFilter {
1540 status: None,
1541 starts_after: None,
1542 starts_before: Some(now + 150_000),
1543 teacher: None,
1544 },
1545 )
1546 .await;
1547 assert_eq!(page.total, 1);
1548 assert_eq!(page.items[0].id, pending.get_id().key());
1549
1550 // Teacher+ inbox: only the bookings aimed at their own slots.
1551 let page = bookings(&st, &ali, none()).await;
1552 assert_eq!(page.total, 1);
1553 assert_eq!(page.items[0].id, pending.get_id().key());
1554
1555 // Inbox, teacher=me: the same rows.
1556 let page = bookings(&st, &ali, with_teacher(&ali)).await;
1557 assert_eq!(page.total, 1);
1558
1559 // Inbox, teacher=ayse: the empty intersection — never her inbox.
1560 let page = bookings(&st, &ali, with_teacher(&ayse)).await;
1561 assert_eq!((page.items.len(), page.total), (0, 0));
1562
1563 // Inbox, starts_after: ali's meeting is the earlier one, so a cut
1564 // past it empties his inbox while ayse keeps hers.
1565 let page = bookings(&st, &ali, after(now + 150_000)).await;
1566 assert_eq!((page.items.len(), page.total), (0, 0));
1567 let page = bookings(&st, &ayse, after(now + 150_000)).await;
1568 assert_eq!(page.total, 1);
1569 }
1570}