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_dish.rs218 lines, 6.6 KiBHistoryRawDownload
1//! One dish on a published [`Menu`](crate::domain::menu::Menu): what it is,
2//! what it costs, and which dietary tags it carries.
3//!
4//! Money is **minor units** as `i64` — never a float, never a decimal, at any
5//! layer. `tags` are validated against the school's `dietary_tags`
6//! list, the same contract a menu's `slot` has with `meal_slots`.
7//!
8//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in
9//! [`crate::service::menu`].
10
11use sqlx::Type;
12use uuid::Uuid;
13
14use crate::constant::{
15 MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS,
16};
17use crate::domain::menu::MenuId;
18use crate::domain::monotonic_id::next_uuid;
19use crate::domain::timestamp::Timestamp;
20use crate::error::ValidationError;
21use crate::validate::{validate_optional, validate_required};
22
23/// Typed menu-dish row id. A UUIDv7 minted by the process-wide monotonic
24/// generator, so `id` order is mint order.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
26#[sqlx(transparent)]
27pub struct MenuDishId(Uuid);
28
29impl MenuDishId {
30 /// Minted from the process-wide monotonic generator, not a random v4 —
31 /// the listings order by `id` within a menu, which random low bits would
32 /// scramble.
33 pub fn generate() -> Self {
34 Self(next_uuid())
35 }
36
37 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
38 /// cannot take the newtype. Static `query!` binds take `self` directly.
39 pub fn uuid(&self) -> Uuid {
40 self.0
41 }
42
43 /// Parse a wire key. A key that parses as no UUID — a malformed path
44 /// segment — reads as the nil id, which matches no row: exactly the 404 a
45 /// dangling record key produced under the old store, without turning a
46 /// typo into a panic.
47 pub fn from_key(key: &str) -> Self {
48 Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
49 }
50
51 /// The hyphenated wire form.
52 pub fn key(&self) -> String {
53 self.0.to_string()
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Type)]
58#[sqlx(transparent)]
59pub struct DishName(String);
60
61impl DishName {
62 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
63 validate_required("name", value, MAX_DISH_NAME_LEN)?;
64 Ok(Self(value.to_string()))
65 }
66
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Type)]
73#[sqlx(transparent)]
74pub struct DishDescription(String);
75
76impl DishDescription {
77 /// Blank (or whitespace-only) means "no description" — `None`, not an
78 /// empty string, so the column is NULL rather than falsely present.
79 pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> {
80 validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?;
81 let value = value.trim();
82 Ok((!value.is_empty()).then(|| Self(value.to_string())))
83 }
84
85 pub fn as_str(&self) -> &str {
86 &self.0
87 }
88}
89
90/// What one serving costs, in **minor units**. Never negative — a giveaway
91/// dish is `0`, and money that flows the other way is a ledger line.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
93#[sqlx(transparent)]
94pub struct DishPrice(i64);
95
96impl DishPrice {
97 pub fn try_new(value: i64) -> Result<Self, ValidationError> {
98 if !(0..=MAX_DISH_PRICE_MINOR).contains(&value) {
99 return Err(ValidationError::Invalid {
100 field: "price_minor",
101 reason: "must be between 0 and 1000000 minor units",
102 });
103 }
104 Ok(Self(value))
105 }
106
107 pub fn as_minor(self) -> i64 {
108 self.0
109 }
110}
111
112/// The dietary tags a dish carries, drawn from the school's `dietary_tags`
113/// list. Deduplicated, order preserved — the list is what a student's profile
114/// is matched against, so a repeat carries no extra meaning. Stored one row
115/// per tag in `menu_dish_tag` — an `ord` column keeps the given order, and
116/// reads re-aggregate in that order.
117#[derive(Debug, Clone, PartialEq, Eq, Type)]
118#[sqlx(transparent, no_pg_array)]
119pub struct DishTags(Vec<String>);
120
121impl DishTags {
122 pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> {
123 let mut tags: Vec<String> = Vec::new();
124 for value in values {
125 let value = value.trim();
126 if !allowed.iter().any(|tag| tag == value) {
127 return Err(ValidationError::Invalid {
128 field: "tags",
129 reason: "not one of the school's dietary tags (see GET /settings)",
130 });
131 }
132 if !tags.iter().any(|tag| tag == value) {
133 tags.push(value.to_string());
134 }
135 }
136 if tags.len() > MAX_DISH_TAGS {
137 return Err(ValidationError::Invalid {
138 field: "tags",
139 reason: "at most 10 tags per dish",
140 });
141 }
142 Ok(Self(tags))
143 }
144
145 pub fn as_slice(&self) -> &[String] {
146 &self.0
147 }
148}
149
150#[derive(Debug, Clone, sqlx::FromRow)]
151pub struct MenuDish {
152 pub(crate) id: MenuDishId,
153 pub(crate) menu: MenuId,
154 pub(crate) name: DishName,
155 pub(crate) description: Option<DishDescription>,
156 pub(crate) price_minor: DishPrice,
157 pub(crate) tags: DishTags,
158 pub(crate) created_at: Timestamp,
159}
160
161impl MenuDish {
162 pub fn get_id(&self) -> &MenuDishId {
163 &self.id
164 }
165
166 pub fn get_menu(&self) -> &MenuId {
167 &self.menu
168 }
169
170 pub fn get_name(&self) -> &DishName {
171 &self.name
172 }
173
174 pub fn get_description(&self) -> Option<&DishDescription> {
175 self.description.as_ref()
176 }
177
178 pub fn get_price_minor(&self) -> DishPrice {
179 self.price_minor
180 }
181
182 pub fn get_tags(&self) -> &DishTags {
183 &self.tags
184 }
185
186 pub fn get_created_at(&self) -> Timestamp {
187 self.created_at
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn price_is_bounded_non_negative_minor_units() {
197 assert_eq!(DishPrice::try_new(0).unwrap().as_minor(), 0);
198 assert_eq!(DishPrice::try_new(4550).unwrap().as_minor(), 4550);
199 assert!(DishPrice::try_new(-1).is_err());
200 assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR).is_ok());
201 assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR + 1).is_err());
202 }
203
204 #[test]
205 fn tags_must_come_from_the_school_list_and_dedupe() {
206 let allowed = vec!["vegan".to_string(), "nut_allergy".to_string()];
207 let tags =
208 DishTags::try_new(&["vegan".to_string(), "vegan".to_string()], &allowed).unwrap();
209 assert_eq!(tags.as_slice(), ["vegan"]);
210 assert!(DishTags::try_new(&["halal".to_string()], &allowed).is_err());
211 assert!(
212 DishTags::try_new(&[], &allowed)
213 .unwrap()
214 .as_slice()
215 .is_empty()
216 );
217 }
218}