From 5d48a8d4350c220a04b1efec5bb7b228c9f5f165 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 24 Jul 2026 16:32:25 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(appointments):=20record=20who?= =?UTF-8?q?=20cancelled=20or=20rejected=20and=20why?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reject and cancel now take an optional free-text reason and stamp the actor: bookings gain cancelled_by, cancel_reason, and reject_reason, all #[surreal(default)] so rows written before these existed still read back as None. The reason is validated (400 if over-long) before it touches the row; a blank or absent one records nothing. AppointmentResponse exposes the new fields, and decline_reschedule cancels with no reason. --- src/database.rs | 3 ++ src/domain/appointment.rs | 38 +++++++++++++++++++++-- src/web/appointments.rs | 56 ++++++++++++++++++++++++++++++++-- tests/integration.rs | 64 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 155 insertions(+), 6 deletions(-) diff --git a/src/database.rs b/src/database.rs index 481018c..99cdd1c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -436,6 +436,9 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option; DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option>; DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option>; + DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option>; + DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option; + DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option; DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int; DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 4136466..f239609 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -153,6 +153,16 @@ pub struct Appointment { proposed_ends_at: Option, proposed_by: Option, decided_by: Option, + /// Who called the meeting off, and why, once it is `cancelled`. Both + /// `#[surreal(default)]` so bookings written before cancellation records + /// existed still read back (they resolve to `None`). + #[surreal(default)] + cancelled_by: Option, + #[surreal(default)] + cancel_reason: Option, + /// Why the request was turned down; the rejecter is already on `decided_by`. + #[surreal(default)] + reject_reason: Option, created_at: Timestamp, } @@ -193,6 +203,18 @@ impl Appointment { self.decided_by.as_ref() } + pub fn get_cancelled_by(&self) -> Option<&UserId> { + self.cancelled_by.as_ref() + } + + pub fn get_cancel_reason(&self) -> Option<&AppointmentReason> { + self.cancel_reason.as_ref() + } + + pub fn get_reject_reason(&self) -> Option<&AppointmentReason> { + self.reject_reason.as_ref() + } + pub fn get_created_at(&self) -> Timestamp { self.created_at } @@ -339,6 +361,9 @@ impl Appointment { proposed_ends_at: None, proposed_by: None, decided_by: None, + cancelled_by: None, + cancel_reason: None, + reject_reason: None, created_at: Timestamp::now(), }; let created: Option = db @@ -437,12 +462,14 @@ impl Appointment { pub async fn reject( id: &AppointmentId, decided_by: &UserId, + reason: Option, db: &Database, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; let mut appointment = Self::read_pending(id, db).await?; appointment.status = AppointmentStatus::Rejected; appointment.decided_by = Some(decided_by.clone()); + appointment.reject_reason = reason; Self::save(appointment, db).await } @@ -453,7 +480,12 @@ impl Appointment { /// began is history, not a plan. The guard lives here rather than in the /// handler so every caller inherits it: `decline_reschedule` cancels /// through this same door and used to slip past a handler-only check. - pub async fn cancel(id: &AppointmentId, db: &Database) -> Result { + pub async fn cancel( + id: &AppointmentId, + cancelled_by: &UserId, + reason: Option, + db: &Database, + ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?; if !appointment.status.is_live() { @@ -466,6 +498,8 @@ impl Appointment { return Err(AppError::Conflict("the appointment has already started")); } appointment.status = AppointmentStatus::Cancelled; + appointment.cancelled_by = Some(cancelled_by.clone()); + appointment.cancel_reason = reason; Self::save(appointment, db).await } @@ -730,7 +764,7 @@ mod tests { Err(AppError::Conflict(_)) )); - Appointment::reject(first.get_id(), &teacher, &db) + Appointment::reject(first.get_id(), &teacher, None, &db) .await .unwrap(); let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db) diff --git a/src/web/appointments.rs b/src/web/appointments.rs index f4c6050..9bfd53b 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -62,6 +62,22 @@ struct BookAppointment { 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(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(example = "Bu saatte müsait değilim")] + reason: Option, +} + #[derive(Deserialize, ToSchema)] struct Reschedule { /// Unix-millisecond timestamps. Must not be in the past. @@ -126,6 +142,12 @@ struct AppointmentResponse { proposed_by: Option, /// Who approved or rejected it; `null` while pending. decided_by: Option, + /// Who called it off; `null` unless `status` is `cancelled`. + cancelled_by: Option, + /// Optional free-text reason given when cancelling; `null` when none was. + cancel_reason: Option, + /// Optional free-text reason given when rejecting; `null` when none was. + reject_reason: Option, created_at: i64, } @@ -153,6 +175,15 @@ impl AppointmentResponse { 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(), } } @@ -177,6 +208,7 @@ async fn appointment_responses( ids.extend(slot.as_ref().map(|slot| slot.get_teacher().clone())); 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 @@ -551,8 +583,10 @@ async fn approve( 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), @@ -563,10 +597,17 @@ 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?; - let appointment = Appointment::reject(&id, user.get_id(), &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 = Appointment::reject(&id, user.get_id(), reason, &st.db).await?; one_appointment(appointment, &st.db).await } @@ -580,8 +621,10 @@ async fn reject( 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 = "Neither the requester nor the slot's teacher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -592,6 +635,7 @@ async fn cancel( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, + body: Option>, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); let appointment = Appointment::read(&id, &st.db) @@ -605,10 +649,16 @@ async fn cancel( "only the requester or the slot's teacher 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 `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 = Appointment::cancel(&id, &st.db).await?; + let appointment = Appointment::cancel(&id, user.get_id(), reason, &st.db).await?; one_appointment(appointment, &st.db).await } @@ -719,7 +769,7 @@ async fn decline_reschedule( if appointment.get_proposed_starts_at().is_none() { return Err(AppError::Conflict("no time has been proposed")); } - let appointment = Appointment::cancel(&id, &st.db).await?; + let appointment = Appointment::cancel(&id, user.get_id(), None, &st.db).await?; one_appointment(appointment, &st.db).await } diff --git a/tests/integration.rs b/tests/integration.rs index 199384d..bd6a034 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -15505,15 +15505,44 @@ async fn appointment_book_and_approve_holds_the_slot() { async fn rejecting_a_booking_frees_the_slot() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; + let ali_id = me_id(&app, &ali).await; let veli = login(&app, "veli").await; let ayse = login(&app, "ayse").await; let now = Timestamp::now().as_millis(); let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; + // A bodyless reject records the decider and no reason. let booking = book_ok(&app, &veli, &slot).await; let res = decide(&app, &ali, &booking, "reject").await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["status"], "rejected"); + assert_eq!(res.body["decided_by"]["id"], ali_id.as_str()); + assert!(res.body["reject_reason"].is_null(), "no reason was given"); + + // A reject carrying a reason records both the decider and the reason, and + // an over-long reason is refused before the row changes. + let booking = book_ok(&app, &ayse, &slot).await; + let res = send( + &app, + "PATCH", + &format!("/appointments/{booking}/reject"), + Some(&ali), + Some(json!({ "reason": "x".repeat(2000) })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/appointments/{booking}/reject"), + Some(&ali), + Some(json!({ "reason": "Bu saatte müsait değilim" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "rejected"); + assert_eq!(res.body["decided_by"]["id"], ali_id.as_str()); + assert_eq!(res.body["reject_reason"], "Bu saatte müsait değilim"); // Occupancy counts live rows only, so the next person may take it. let res = book_slot(&app, &ayse, &slot).await; @@ -15682,6 +15711,7 @@ async fn declining_a_reschedule_cancels_the_booking() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; let ayse = login(&app, "ayse").await; let now = Timestamp::now().as_millis(); let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; @@ -15700,6 +15730,9 @@ async fn declining_a_reschedule_cancels_the_booking() { let res = decide(&app, &veli, &booking, "reschedule/decline").await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["status"], "cancelled"); + // The decliner is recorded as the canceller, with no reason. + assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); + assert!(res.body["cancel_reason"].is_null()); // The refused proposal stays readable on the cancelled row. assert_eq!(res.body["proposed_starts_at"], now + 3 * HOUR_MS); @@ -15792,10 +15825,12 @@ async fn either_side_cancels_until_the_window_opens() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; let ayse = login(&app, "ayse").await; let now = Timestamp::now().as_millis(); - // The requester's own call, on an approved meeting. + // The requester's own call, on an approved meeting. A bodyless cancel + // records the actor and no reason. let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; let booking = book_ok(&app, &veli, &slot).await; assert_eq!( @@ -15805,6 +15840,33 @@ async fn either_side_cancels_until_the_window_opens() { let res = decide(&app, &veli, &booking, "cancel").await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["status"], "cancelled"); + assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); + assert!(res.body["cancel_reason"].is_null(), "no reason was given"); + + // A cancel carrying a reason records both the actor and the reason, and an + // over-long reason is refused before the row changes. + let booking = book_ok(&app, &veli, &slot).await; + let res = send( + &app, + "PATCH", + &format!("/appointments/{booking}/cancel"), + Some(&veli), + Some(json!({ "reason": "x".repeat(2000) })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/appointments/{booking}/cancel"), + Some(&veli), + Some(json!({ "reason": "Rahatsızlandım" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled"); + assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); + assert_eq!(res.body["cancel_reason"], "Rahatsızlandım"); // The slot's teacher may too. let booking = book_ok(&app, &ayse, &slot).await;