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

menu.rs353 lines, 14.1 KiBHistoryRawDownload
1//! A published menu: what the kitchen serves on one calendar day in one meal
2//! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)),
3//! and bookings hang off its `capacity`.
4//!
5//! Two things are deliberate:
6//!
7//! - **`date` is text** (`YYYY-MM-DD`), not a timestamp. The uniqueness rule is
8//! "one menu per day and slot", an equality test — and a midnight-in-millis
9//! day is only one school's day.
10//! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must
11//! never rewrite a menu already published under it.
12//!
13//! The queries live in [`crate::db::menu`]; the kitchen workflows (and the
14//! dish-cap gate) in [`crate::service::menu`].
15
16use sqlx::Type;
17
18use crate::constant::MAX_MENU_CAPACITY;
19use crate::domain::settings::MealSlotDef;
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::UserId;
22use crate::error::ValidationError;
23
24/// The reference counter for one meal slot — how many menus are published under
25/// that name, and whether the school has retired it (see
26/// [`crate::db::cap`]). The mirror of
27/// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot
28/// is snapshotted text on the menu, so this row is the only place the two
29/// tables' relationship is a single row concurrent writes can contend on.
30/// The `slot_ref` row is keyed by the slot's name.
31pub(crate) fn slot_ref(slot: &str) -> String {
32 slot.to_string()
33}
34
35/// Typed menu row id — the `{date}_{slot}` pair joined with `_`. Not a minted
36/// id: the pair *is* the identity, the same trick the enrollment tables use.
37/// `date` is fixed-width `YYYY-MM-DD`, and slot names never carry `_`-breaking
38/// ambiguity, so two requests publishing the same meal race on one row and the
39/// loser is told "already exists" by the store.
40#[derive(Debug, Clone, PartialEq, Eq, Type)]
41#[sqlx(transparent)]
42pub struct MenuId(String);
43
44impl MenuId {
45 /// The one id a menu for this day and slot can have. Deterministic on
46 /// purpose (the enrollment trick): two requests publishing the same meal
47 /// race on a single row instead of writing two, so the loser is told
48 /// "already exists" by the store and answered the same 409 the pre-check
49 /// gives.
50 pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self {
51 Self(format!("{}_{}", date.as_str(), slot.as_str()))
52 }
53
54 pub fn from_key(key: &str) -> Self {
55 Self(key.to_string())
56 }
57
58 pub fn key(&self) -> &str {
59 &self.0
60 }
61}
62
63/// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose:
64/// that makes the text sort chronologically, so the `?from=&to=` range filter
65/// and the newest-first ordering are plain string comparisons.
66#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Type)]
67#[sqlx(transparent)]
68pub struct MenuDate(String);
69
70impl MenuDate {
71 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
72 let invalid = ValidationError::Invalid {
73 field: "date",
74 reason: "must be a calendar day as YYYY-MM-DD",
75 };
76 let value = value.trim();
77 let bytes = value.as_bytes();
78 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
79 return Err(invalid);
80 }
81 // Parsed by **chrono** and compared back to the text it came from, so
82 // this parser and the one that computes the serving instant
83 // ([`served_at`](crate::domain::meal_booking)) agree by construction
84 // rather than by two independent checks that can drift apart. They did:
85 // a hand-rolled `"+1".parse::<u32>()` accepted a signed component (std
86 // does), `from_ymd_opt` was then handed the normalized number and said
87 // yes, and `2026-+1-01` became a *second* row id for the 1st of
88 // January — its own capacity and seat counter, invisible to every
89 // `date >= $from` range read ('+' sorts below '0'), and unbookable
90 // besides, since chrono refuses to parse it back.
91 //
92 // The round trip also keeps the day a **real** one, leap years and all
93 // (a 31st of February is fully actionable — seats, charges, dishes,
94 // marks — with no instant any cutoff can count back from), and pins the
95 // zero-padding the text ordering rests on.
96 let Ok(day) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") else {
97 return Err(invalid);
98 };
99 if day.format("%Y-%m-%d").to_string() != value {
100 return Err(invalid);
101 }
102 Ok(Self(value.to_string()))
103 }
104
105 pub fn as_str(&self) -> &str {
106 &self.0
107 }
108
109 /// The instant this calendar day is over: midnight UTC opening the next
110 /// one. UTC because the backend stores no school timezone, the same choice
111 /// [`served_at`](crate::domain::meal_booking) makes for the serving instant.
112 ///
113 /// This is the whole day's deadline, not the meal's: a menu for *today* is
114 /// still publishable and still bookable at any hour, whatever the slot's
115 /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s
116 /// separate business. `None` for a day that cannot be parsed.
117 pub fn day_end(&self) -> Option<Timestamp> {
118 let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?;
119 Some(Timestamp::from_millis(
120 day.succ_opt()?
121 .and_hms_opt(0, 0, 0)?
122 .and_utc()
123 .timestamp_millis(),
124 ))
125 }
126}
127
128/// The meal slot a menu was published for, snapshotted as text. Validated
129/// against the school's *current* list at write time — that list is the only
130/// place slot names are defined, and this is the sole funnel into the column.
131#[derive(Debug, Clone, PartialEq, Eq, Type)]
132#[sqlx(transparent)]
133pub struct MenuSlot(String);
134
135impl MenuSlot {
136 pub fn try_new(value: &str, allowed: &[MealSlotDef]) -> Result<Self, ValidationError> {
137 let value = value.trim();
138 if !allowed.iter().any(|slot| slot.get_name() == value) {
139 return Err(ValidationError::Invalid {
140 field: "slot",
141 reason: "not one of the school's meal slots (see GET /settings)",
142 });
143 }
144 // The slot goes verbatim into the menu's id ([`MenuId::for_slot`]),
145 // and that id is a URL path segment: a slot named `a/b` publishes a menu
146 // at `/meals/menus/2026-09-14_a/b`, which no route can ever address
147 // again — the menu could not be read, edited or deleted.
148 // `MealSlotDef::try_new` refuses the same characters, so no school can
149 // define such a slot; this is the second gate, and it is what a
150 // settings row written before that rule runs into.
151 if value
152 .chars()
153 .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%'))
154 {
155 return Err(ValidationError::Invalid {
156 field: "slot",
157 reason: "meal slot names used for menus must not contain / \\ ? # or %",
158 });
159 }
160 Ok(Self(value.to_string()))
161 }
162
163 pub fn as_str(&self) -> &str {
164 &self.0
165 }
166}
167
168/// How many students the menu may seat. `None` = uncapped, the shape a
169/// course's `capacity` already uses.
170pub fn validate_capacity(value: Option<i64>) -> Result<(), ValidationError> {
171 match value {
172 Some(capacity) if !(0..=MAX_MENU_CAPACITY).contains(&capacity) => {
173 Err(ValidationError::Invalid {
174 field: "capacity",
175 reason: "must be between 0 and 10000",
176 })
177 }
178 _ => Ok(()),
179 }
180}
181
182#[derive(Debug, Clone, sqlx::FromRow)]
183pub struct Menu {
184 pub(crate) id: MenuId,
185 pub(crate) date: MenuDate,
186 pub(crate) slot: MenuSlot,
187 pub(crate) capacity: Option<i64>,
188 /// The menu's revision. `NULL` (never written by the current code) reads
189 /// as revision zero — the same thing `(version ?? 0)` says in the claim's
190 /// `WHERE`. The seat counter is deliberately *not* here: it is the
191 /// database's to own, and a whole-row save must never carry a stale copy
192 /// of it.
193 pub(crate) version: Option<i64>,
194 pub(crate) created_by: UserId,
195 pub(crate) created_at: Timestamp,
196}
197
198impl Menu {
199 pub fn get_id(&self) -> &MenuId {
200 &self.id
201 }
202
203 pub fn get_date(&self) -> &MenuDate {
204 &self.date
205 }
206
207 pub fn get_slot(&self) -> &MenuSlot {
208 &self.slot
209 }
210
211 pub fn get_capacity(&self) -> Option<i64> {
212 self.capacity
213 }
214
215 /// The revision a booking must still find on the row when it claims its
216 /// seat. Absent is revision zero, exactly as the `WHERE` reads it.
217 pub fn get_version(&self) -> i64 {
218 self.version.unwrap_or(0)
219 }
220
221 pub fn get_created_by(&self) -> &UserId {
222 &self.created_by
223 }
224
225 pub fn get_created_at(&self) -> Timestamp {
226 self.created_at
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[test]
235 fn date_accepts_only_padded_calendar_days() {
236 assert!(MenuDate::try_new("2026-07-26").is_ok());
237 assert!(MenuDate::try_new("2026-7-26").is_err());
238 assert!(MenuDate::try_new("2026-13-01").is_err());
239 assert!(MenuDate::try_new("2026-00-01").is_err());
240 assert!(MenuDate::try_new("2026-01-32").is_err());
241 assert!(MenuDate::try_new("26-01-02").is_err());
242 assert!(MenuDate::try_new("").is_err());
243 // A day that no calendar has. Not a harmless typo: the serving instant
244 // a menu's cutoff counts back from cannot be computed for it, so such a
245 // menu used to be bookable and cancellable with no deadline at all.
246 for impossible in ["2026-02-29", "2026-04-31", "2026-06-31", "2026-11-31"] {
247 assert!(
248 MenuDate::try_new(impossible).is_err(),
249 "{impossible} is not a real day"
250 );
251 }
252 // …and the leap day that does exist is still a menu day.
253 assert!(MenuDate::try_new("2024-02-29").is_ok());
254 // Sorting the text must sort the calendar — the range filter relies on it.
255 assert!(
256 MenuDate::try_new("2026-01-09").unwrap() < MenuDate::try_new("2026-01-10").unwrap()
257 );
258 assert!(
259 MenuDate::try_new("2026-09-01").unwrap() < MenuDate::try_new("2026-10-01").unwrap()
260 );
261 }
262
263 /// A signed component is not a calendar day, however willingly
264 /// `"+1".parse::<u32>()` reads one out of it. Accepting one minted a
265 /// *second* row id for the same day — its own capacity and seat counter
266 /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and
267 /// that the serving-instant parser could not read at all.
268 #[test]
269 fn date_refuses_a_signed_component() {
270 for signed in ["2026-+1-01", "2026-01-+1", "+026-01-01", "2026-01-+2"] {
271 assert!(
272 MenuDate::try_new(signed).is_err(),
273 "{signed} is not a calendar day"
274 );
275 }
276 }
277
278 /// The drift guard: whatever this accepts must be exactly what the calendar
279 /// library writes back for that day. Two parsers that merely *agree today*
280 /// are what let the signed form through — one normalized the sign away
281 /// before the other ever saw it.
282 #[test]
283 fn every_accepted_date_round_trips_through_the_calendar() {
284 for candidate in [
285 "2026-07-26",
286 "2024-02-29",
287 "2026-+1-01",
288 "2026-1-1",
289 "0001-01-01",
290 "2026-02-29",
291 ] {
292 let stored = MenuDate::try_new(candidate).ok();
293 let round_tripped = chrono::NaiveDate::parse_from_str(candidate, "%Y-%m-%d")
294 .ok()
295 .map(|day| day.format("%Y-%m-%d").to_string())
296 .filter(|text| text == candidate);
297 assert_eq!(
298 stored.map(|date| date.as_str().to_string()),
299 round_tripped,
300 "{candidate} must be stored exactly as the calendar writes it, or not at all"
301 );
302 }
303 }
304
305 /// The day is over at midnight UTC opening the next one — not at the meal's
306 /// serving hour, which is the cutoff's separate business.
307 #[test]
308 fn a_day_ends_at_the_next_midnight_utc() {
309 let day = MenuDate::try_new("1970-01-01").unwrap();
310 assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000);
311 }
312
313 #[test]
314 fn slot_must_be_one_the_school_serves() {
315 let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()];
316 assert!(MenuSlot::try_new("lunch", &allowed).is_ok());
317 assert!(MenuSlot::try_new("brunch", &allowed).is_err());
318 assert!(MenuSlot::try_new("lunch", &[]).is_err());
319 }
320
321 /// The slot becomes the menu's id, and the id becomes a URL path
322 /// segment: a name carrying a separator publishes a menu at an address no
323 /// route can match again. `MealSlotDef::try_new` refuses the name too, so
324 /// no school can define such a slot any more — this gate is what a
325 /// settings row written *before* that rule still runs into. Ordinary names —
326 /// spaces and Turkish letters included — are untouched; they percent-encode
327 /// into one segment as they always have.
328 #[test]
329 fn a_slot_name_that_would_break_the_menu_url_is_refused() {
330 // The only shape that can still carry such a name: a stored slot,
331 // which `try_kept` admits exactly because it is already on the row.
332 let named = |name: &str| {
333 MenuSlot::try_new(name, &[MealSlotDef::try_kept(name, None).unwrap()])
334 .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot))
335 };
336 for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] {
337 assert!(named(broken).is_err(), "{broken} must not become an id");
338 }
339 assert_eq!(
340 named("öğle yemeği").unwrap().key(),
341 "2026-09-14_öğle yemeği"
342 );
343 }
344
345 #[test]
346 fn capacity_is_bounded_but_optional() {
347 assert!(validate_capacity(None).is_ok());
348 assert!(validate_capacity(Some(0)).is_ok());
349 assert!(validate_capacity(Some(MAX_MENU_CAPACITY)).is_ok());
350 assert!(validate_capacity(Some(-1)).is_err());
351 assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err());
352 }
353}