Skip to main content

meal_planner/
school_menus.rs

1//! Date-keyed, manually managed school lunch menu domain model.
2use chrono::NaiveDate;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum SchoolMenuStatus {
8    Known,
9    NotPublished,
10    Closed,
11    Unknown,
12}
13impl SchoolMenuStatus {
14    pub(crate) fn as_str(self) -> &'static str {
15        match self {
16            Self::Known => "known",
17            Self::NotPublished => "not_published",
18            Self::Closed => "closed",
19            Self::Unknown => "unknown",
20        }
21    }
22    pub(crate) fn parse(s: &str) -> Option<Self> {
23        match s {
24            "known" => Some(Self::Known),
25            "not_published" => Some(Self::NotPublished),
26            "closed" => Some(Self::Closed),
27            "unknown" => Some(Self::Unknown),
28            _ => None,
29        }
30    }
31}
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct SchoolMenuItem {
34    pub name: String,
35    pub notes: Option<String>,
36    pub allergens: Option<Vec<String>>,
37    pub dietary_alternatives: Vec<String>,
38}
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct SchoolMenuDraft {
41    pub date: NaiveDate,
42    pub status: SchoolMenuStatus,
43    pub items: Vec<SchoolMenuItem>,
44    pub notes: Option<String>,
45}
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct SchoolMenuEntry {
48    pub id: i64,
49    #[serde(flatten)]
50    pub draft: SchoolMenuDraft,
51    pub created_at: i64,
52    pub updated_at: i64,
53}
54impl SchoolMenuDraft {
55    pub(crate) fn validate(mut self) -> Result<Self, String> {
56        match self.status {
57            SchoolMenuStatus::Known if self.items.is_empty() => {
58                return Err(
59                    "a school menu with status `known` must contain at least one item".into(),
60                );
61            }
62            // A closure is authoritative: discard any menu items supplied by
63            // the caller so an existing menu is cleared when this draft is saved.
64            SchoolMenuStatus::Closed => self.items.clear(),
65            SchoolMenuStatus::NotPublished | SchoolMenuStatus::Unknown
66                if !self.items.is_empty() =>
67            {
68                return Err(format!(
69                    "a school menu with status `{}` cannot contain menu items; set `items` to an empty array ([]). Menu items are only valid when status is `known`",
70                    self.status.as_str()
71                ));
72            }
73            _ => {}
74        }
75        for item in &mut self.items {
76            item.name = item.name.trim().to_owned();
77            if item.name.is_empty() {
78                return Err("school menu item name must not be empty".into());
79            }
80            item.notes = clean(item.notes.take());
81            item.allergens = item.allergens.take().map(normalize);
82            item.dietary_alternatives = normalize(std::mem::take(&mut item.dietary_alternatives));
83        }
84        self.notes = clean(self.notes.take());
85        Ok(self)
86    }
87}
88fn clean(v: Option<String>) -> Option<String> {
89    v.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty())
90}
91fn normalize(v: Vec<String>) -> Vec<String> {
92    let mut out = Vec::new();
93    for s in v {
94        let s = s.trim();
95        if !s.is_empty() && !out.iter().any(|x: &String| x.eq_ignore_ascii_case(s)) {
96            out.push(s.to_owned())
97        }
98    }
99    out
100}
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    fn date() -> NaiveDate {
106        NaiveDate::from_ymd_opt(2026, 11, 2).unwrap()
107    }
108
109    #[test]
110    fn menu_states_are_explicit() {
111        assert!(
112            SchoolMenuDraft {
113                date: date(),
114                status: SchoolMenuStatus::Known,
115                items: vec![],
116                notes: None
117            }
118            .validate()
119            .is_err()
120        );
121        for status in [
122            SchoolMenuStatus::Unknown,
123            SchoolMenuStatus::NotPublished,
124            SchoolMenuStatus::Closed,
125        ] {
126            assert!(
127                SchoolMenuDraft {
128                    date: date(),
129                    status,
130                    items: vec![],
131                    notes: None
132                }
133                .validate()
134                .is_ok()
135            )
136        }
137    }
138
139    #[test]
140    fn closing_school_discards_supplied_menu_items_and_preserves_notes() {
141        let draft = SchoolMenuDraft {
142            date: date(),
143            status: SchoolMenuStatus::Closed,
144            items: vec![SchoolMenuItem {
145                name: "Festivo / Sin servicio de comedor".into(),
146                notes: None,
147                allergens: None,
148                dietary_alternatives: vec![],
149            }],
150            notes: Some("Festivo".into()),
151        };
152
153        let normalized = draft.validate().unwrap();
154
155        assert!(normalized.items.is_empty());
156        assert_eq!(normalized.notes.as_deref(), Some("Festivo"));
157    }
158
159    #[test]
160    fn non_known_status_with_items_returns_actionable_error() {
161        let error = SchoolMenuDraft {
162            date: date(),
163            status: SchoolMenuStatus::NotPublished,
164            items: vec![SchoolMenuItem {
165                name: "Some dish".into(),
166                notes: None,
167                allergens: None,
168                dietary_alternatives: vec![],
169            }],
170            notes: None,
171        }
172        .validate()
173        .unwrap_err();
174
175        assert!(error.contains("set `items` to an empty array ([])"));
176        assert!(error.contains("status is `known`"));
177    }
178}