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

appointment.rs285 lines, 10.7 KiBHistoryRawDownload
1//! A booking on a teacher's [`AppointmentSlot`]. A student or a parent asks
2//! for the meeting with a reason; the teacher approves, rejects, or
3//! counter-proposes another time.
4//!
5//! This module is the pure row shape: the validated reason and status, the
6//! id, and the two predicates every layer shares — [`Appointment::window`]
7//! (a proposal overrides the slot) and [`Appointment::overlaps`] (half-open
8//! windows, so back-to-back meetings do not collide).
9//!
10//! The *cross-record* invariants live one layer down:
11//!
12//! - **One live booking per slot** — the `occupied` counter on the slot row,
13//! a [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`]
14//! claims it *with* the booking row; rejecting or cancelling gives it back
15//! in the *same transaction* as the status flip
16//! ([`crate::db::appointment::save_if_unchanged`]), so the slot frees itself
17//! with nothing to sweep.
18//! - **No double-booked teacher window.** Two overlapping published windows
19//! cannot both exist — the `appointment_slot` exclusion constraint refuses
20//! the second insert at the store, which is what replaced the process
21//! lock the appointment workflows used to hold.
22//!
23//! The *single-row* invariant — a decision must be written onto the state it
24//! was validated against — is a compare-and-set
25//! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional
26//! `UPDATE`.
27
28use crate::constant::MAX_APPOINTMENT_REASON_LEN;
29use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
30use crate::domain::monotonic_id::next_uuid;
31use crate::domain::timestamp::Timestamp;
32use crate::domain::user::UserId;
33use crate::error::ValidationError;
34use crate::validate::validate_required;
35
36#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
37#[sqlx(transparent)]
38pub struct AppointmentId(uuid::Uuid);
39
40impl AppointmentId {
41 /// Mints in write order — the `id` tie-break of the newest-first listings
42 /// ([`crate::db::appointment::list_for_requester`]) must not scramble rows
43 /// minted inside one millisecond.
44 pub fn generate() -> Self {
45 Self(next_uuid())
46 }
47
48 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
49 /// cannot take the newtype. Static `query!` binds take `self` directly.
50 pub fn uuid(&self) -> uuid::Uuid {
51 self.0
52 }
53
54 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
55 /// which matches no row — a malformed path param stays a 404, exactly
56 /// like a well-formed one that names nothing.
57 pub fn from_key(key: &str) -> Self {
58 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
59 }
60
61 pub fn key(&self) -> String {
62 self.0.to_string()
63 }
64}
65
66/// Where a booking stands. Stored as the bare lowercase string the `status`
67/// column's CHECK allows; an unknown value comes back as a decode error,
68/// never a panic.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
70#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
71pub enum AppointmentStatus {
72 Pending,
73 Approved,
74 Rejected,
75 Cancelled,
76}
77
78impl AppointmentStatus {
79 /// The wire/storage form. Must stay in lockstep with `rename_all`.
80 pub fn as_str(self) -> &'static str {
81 match self {
82 AppointmentStatus::Pending => "pending",
83 AppointmentStatus::Approved => "approved",
84 AppointmentStatus::Rejected => "rejected",
85 AppointmentStatus::Cancelled => "cancelled",
86 }
87 }
88
89 /// Does a booking in this state still hold its slot? Rejected and
90 /// cancelled ones do not — that is what frees the slot for re-booking.
91 pub fn is_live(self) -> bool {
92 matches!(
93 self,
94 AppointmentStatus::Pending | AppointmentStatus::Approved
95 )
96 }
97}
98
99/// Why the requester wants the meeting. Required: a teacher approving a
100/// parent-teacher conference needs to know what it is about.
101#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
102#[sqlx(transparent)]
103pub struct AppointmentReason(String);
104
105impl AppointmentReason {
106 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
107 validate_required("reason", value, MAX_APPOINTMENT_REASON_LEN)?;
108 Ok(Self(value.to_string()))
109 }
110
111 pub fn as_str(&self) -> &str {
112 &self.0
113 }
114}
115
116/// Fields are crate-visible: [`crate::db::appointment`] reads the columns its
117/// compare-and-set discriminates on, and [`crate::service::appointment`]
118/// clones a fresh read and mutates the decision onto it.
119#[derive(Debug, Clone, sqlx::FromRow)]
120pub struct Appointment {
121 pub(crate) id: AppointmentId,
122 /// The booked slot. `NULL` only on a settled row whose slot was later
123 /// withdrawn (a demotion sweep or a delete after the seat came back):
124 /// the booking still renders, without a window — the dangling reference
125 /// the old store permitted, now an explicit NULL. A live booking's slot
126 /// is pinned by the `occupied` counter and can never be NULL.
127 pub(crate) slot: Option<AppointmentSlotId>,
128 pub(crate) requester: UserId,
129 pub(crate) status: AppointmentStatus,
130 pub(crate) reason: AppointmentReason,
131 /// A counter-proposal from the teacher (or a new time the requester asks
132 /// for). Set as a triple or not at all; once accepted it *is* the
133 /// meeting's time, overriding the slot's own window.
134 pub(crate) proposed_starts_at: Option<Timestamp>,
135 pub(crate) proposed_ends_at: Option<Timestamp>,
136 pub(crate) proposed_by: Option<UserId>,
137 pub(crate) decided_by: Option<UserId>,
138 /// Who called the meeting off, and why, once it is `cancelled`.
139 pub(crate) cancelled_by: Option<UserId>,
140 pub(crate) cancel_reason: Option<AppointmentReason>,
141 /// Why the request was turned down; the rejecter is already on `decided_by`.
142 pub(crate) reject_reason: Option<AppointmentReason>,
143 pub(crate) created_at: Timestamp,
144}
145
146impl Appointment {
147 pub fn get_id(&self) -> &AppointmentId {
148 &self.id
149 }
150
151 pub fn get_slot(&self) -> Option<&AppointmentSlotId> {
152 self.slot.as_ref()
153 }
154
155 pub fn get_requester(&self) -> &UserId {
156 &self.requester
157 }
158
159 pub fn get_status(&self) -> AppointmentStatus {
160 self.status
161 }
162
163 pub fn get_reason(&self) -> &AppointmentReason {
164 &self.reason
165 }
166
167 pub fn get_proposed_starts_at(&self) -> Option<Timestamp> {
168 self.proposed_starts_at
169 }
170
171 pub fn get_proposed_ends_at(&self) -> Option<Timestamp> {
172 self.proposed_ends_at
173 }
174
175 pub fn get_proposed_by(&self) -> Option<&UserId> {
176 self.proposed_by.as_ref()
177 }
178
179 pub fn get_decided_by(&self) -> Option<&UserId> {
180 self.decided_by.as_ref()
181 }
182
183 pub fn get_cancelled_by(&self) -> Option<&UserId> {
184 self.cancelled_by.as_ref()
185 }
186
187 pub fn get_cancel_reason(&self) -> Option<&AppointmentReason> {
188 self.cancel_reason.as_ref()
189 }
190
191 pub fn get_reject_reason(&self) -> Option<&AppointmentReason> {
192 self.reject_reason.as_ref()
193 }
194
195 pub fn get_created_at(&self) -> Timestamp {
196 self.created_at
197 }
198
199 /// When this booking actually happens: the proposed time if one is on the
200 /// row, the slot's window otherwise. `slot` must be this booking's slot.
201 pub fn window(&self, slot: &AppointmentSlot) -> (Timestamp, Timestamp) {
202 match (self.proposed_starts_at, self.proposed_ends_at) {
203 (Some(starts_at), Some(ends_at)) => (starts_at, ends_at),
204 _ => (slot.get_starts_at(), slot.get_ends_at()),
205 }
206 }
207
208 /// Do two half-open windows `[start, end)` collide? Touching windows
209 /// (one ends exactly where the next begins) do **not** — back-to-back
210 /// meetings are the normal way a teacher's hour is filled.
211 pub fn overlaps(
212 a_starts_at: Timestamp,
213 a_ends_at: Timestamp,
214 b_starts_at: Timestamp,
215 b_ends_at: Timestamp,
216 ) -> bool {
217 a_starts_at.as_millis() < b_ends_at.as_millis()
218 && a_ends_at.as_millis() > b_starts_at.as_millis()
219 }
220
221 /// Is a counter-proposal standing? Both halves, exactly as [`window`](Self::window)
222 /// prefers them: a half-written triple is not a proposal and the slot's own
223 /// window still rules.
224 pub(crate) fn has_proposal(&self) -> bool {
225 self.proposed_starts_at.is_some() && self.proposed_ends_at.is_some()
226 }
227
228 /// Is the standing proposal exactly this window? Milliseconds, the one form
229 /// both the API and the row speak.
230 pub(crate) fn proposes(&self, (starts_at, ends_at): (Timestamp, Timestamp)) -> bool {
231 self.proposed_starts_at == Some(starts_at) && self.proposed_ends_at == Some(ends_at)
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 fn at(millis: i64) -> Timestamp {
240 Timestamp::from_millis(millis)
241 }
242
243 #[tokio::test]
244 async fn reason_is_required_and_capped() {
245 assert!(AppointmentReason::try_new("").is_err());
246 assert!(AppointmentReason::try_new(" ").is_err());
247 assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN)).is_ok());
248 assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN + 1)).is_err());
249 }
250
251 /// The `status` column is `TEXT` with a CHECK listing exactly these
252 /// spellings: the occupancy query is written against them, so the storage
253 /// form may not drift from `as_str`.
254 #[test]
255 fn status_stores_as_a_bare_string() {
256 for (status, spelling) in [
257 (AppointmentStatus::Pending, "pending"),
258 (AppointmentStatus::Approved, "approved"),
259 (AppointmentStatus::Rejected, "rejected"),
260 (AppointmentStatus::Cancelled, "cancelled"),
261 ] {
262 assert_eq!(status.as_str(), spelling);
263 }
264 assert!(AppointmentStatus::Pending.is_live());
265 assert!(AppointmentStatus::Approved.is_live());
266 assert!(!AppointmentStatus::Rejected.is_live());
267 assert!(!AppointmentStatus::Cancelled.is_live());
268 }
269
270 #[tokio::test]
271 async fn touching_windows_do_not_overlap_but_one_millisecond_does() {
272 // 10:00–10:30 then 10:30–11:00: back to back, no conflict.
273 assert!(!Appointment::overlaps(at(0), at(30), at(30), at(60)));
274 assert!(!Appointment::overlaps(at(30), at(60), at(0), at(30)));
275 // One millisecond of genuine overlap, from either side.
276 assert!(Appointment::overlaps(at(0), at(31), at(30), at(60)));
277 assert!(Appointment::overlaps(at(30), at(60), at(0), at(31)));
278 // Containment, both ways, and an exact match.
279 assert!(Appointment::overlaps(at(10), at(20), at(0), at(60)));
280 assert!(Appointment::overlaps(at(0), at(60), at(10), at(20)));
281 assert!(Appointment::overlaps(at(0), at(30), at(0), at(30)));
282 // Disjoint by a whole hour.
283 assert!(!Appointment::overlaps(at(0), at(30), at(90), at(120)));
284 }
285}