Skip to main content

meal_planner/
recipes.rs

1//! Provider-independent recipe domain types and deterministic validation.
2use serde::{Deserialize, Serialize};
3
4/// One structured ingredient. Unknown quantities remain `None`; no amount is inferred.
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct RecipeIngredient {
7    pub name: String,
8    pub amount: Option<f64>,
9    pub unit: Option<String>,
10    pub preparation_note: Option<String>,
11}
12
13/// Input accepted when creating or replacing a recipe.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct RecipeDraft {
16    #[serde(default)]
17    pub family_id: Option<String>,
18    pub title: String,
19    pub description: Option<String>,
20    pub servings: u32,
21    pub ingredients: Vec<RecipeIngredient>,
22    /// Ordered preparation instructions; vector order is the stable step order.
23    pub steps: Vec<String>,
24    #[serde(default)]
25    pub categories: Vec<String>,
26    #[serde(default)]
27    pub tags: Vec<String>,
28    pub source: Option<String>,
29    pub notes: Option<String>,
30    #[serde(default)]
31    pub dietary_information: Vec<String>,
32    /// None means unknown; Some([]) means explicitly checked and no allergens.
33    pub allergens: Option<Vec<String>>,
34}
35
36/// Persisted recipe.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct Recipe {
39    pub id: i64,
40    pub owner_id: String,
41    #[serde(flatten)]
42    pub draft: RecipeDraft,
43    pub created_at: i64,
44    pub updated_at: i64,
45}
46
47impl RecipeDraft {
48    pub(crate) fn validate(mut self) -> Result<Self, String> {
49        let title = self.title.trim();
50        if title.is_empty() {
51            return Err("recipe title must not be empty".into());
52        }
53        if self.servings == 0 {
54            return Err("servings must be greater than zero".into());
55        }
56        if self.ingredients.is_empty() {
57            return Err("a recipe must contain at least one ingredient".into());
58        }
59        if self.steps.is_empty() || self.steps.iter().any(|step| step.trim().is_empty()) {
60            return Err("a recipe must contain non-empty preparation steps".into());
61        }
62        for ingredient in &self.ingredients {
63            if ingredient.name.trim().is_empty() {
64                return Err("ingredient name must not be empty".into());
65            }
66            if ingredient
67                .amount
68                .is_some_and(|amount| !amount.is_finite() || amount <= 0.0)
69            {
70                return Err(format!(
71                    "ingredient '{}' has an invalid amount",
72                    ingredient.name
73                ));
74            }
75            if ingredient
76                .unit
77                .as_ref()
78                .is_some_and(|unit| unit.trim().is_empty())
79            {
80                return Err(format!(
81                    "ingredient '{}' has an empty unit",
82                    ingredient.name
83                ));
84            }
85        }
86        self.title = title.to_owned();
87        for ingredient in &mut self.ingredients {
88            ingredient.name = ingredient.name.trim().to_owned();
89            ingredient.unit = ingredient.unit.take().map(|value| value.trim().to_owned());
90            ingredient.preparation_note = ingredient
91                .preparation_note
92                .take()
93                .map(|value| value.trim().to_owned())
94                .filter(|value| !value.is_empty());
95        }
96        self.steps = self
97            .steps
98            .into_iter()
99            .map(|step| step.trim().to_owned())
100            .collect();
101        self.categories = normalize_labels(std::mem::take(&mut self.categories));
102        self.tags = normalize_labels(std::mem::take(&mut self.tags));
103        self.dietary_information = normalize_labels(std::mem::take(&mut self.dietary_information));
104        self.description = clean_optional(self.description.take());
105        self.source = clean_optional(self.source.take());
106        self.notes = clean_optional(self.notes.take());
107        self.allergens = self.allergens.take().map(normalize_labels);
108        Ok(self)
109    }
110}
111
112fn clean_optional(value: Option<String>) -> Option<String> {
113    value
114        .map(|value| value.trim().to_owned())
115        .filter(|value| !value.is_empty())
116}
117
118fn normalize_labels(values: Vec<String>) -> Vec<String> {
119    let mut result: Vec<String> = Vec::new();
120    for value in values {
121        let value = value.trim();
122        if !value.is_empty()
123            && !result
124                .iter()
125                .any(|existing| existing.eq_ignore_ascii_case(value))
126        {
127            result.push(value.to_owned());
128        }
129    }
130    result
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn draft() -> RecipeDraft {
138        RecipeDraft {
139            family_id: None,
140            title: "  Tomato pasta ".into(),
141            description: None,
142            servings: 2,
143            ingredients: vec![RecipeIngredient {
144                name: " Pasta ".into(),
145                amount: None,
146                unit: None,
147                preparation_note: None,
148            }],
149            steps: vec!["  Boil water ".into()],
150            categories: vec![" Dinner ".into(), "dinner".into()],
151            tags: vec![],
152            source: None,
153            notes: None,
154            dietary_information: vec![],
155            allergens: None,
156        }
157    }
158
159    #[test]
160    fn validation_normalizes_text_but_preserves_unknown_quantities_and_allergens() {
161        let recipe = draft().validate().unwrap();
162        assert_eq!(recipe.title, "Tomato pasta");
163        assert_eq!(recipe.ingredients[0].name, "Pasta");
164        assert_eq!(recipe.ingredients[0].amount, None);
165        assert_eq!(recipe.categories, ["Dinner"]);
166        assert_eq!(recipe.allergens, None);
167    }
168
169    #[test]
170    fn rejects_zero_servings_empty_steps_and_invalid_amounts() {
171        let mut value = draft();
172        value.servings = 0;
173        assert!(value.validate().is_err());
174        let mut value = draft();
175        value.steps.clear();
176        assert!(value.validate().is_err());
177        let mut value = draft();
178        value.ingredients[0].amount = Some(f64::NAN);
179        assert!(value.validate().is_err());
180    }
181
182    #[test]
183    fn empty_known_allergen_list_is_not_unknown() {
184        let mut value = draft();
185        value.allergens = Some(vec![]);
186        assert_eq!(value.validate().unwrap().allergens, Some(vec![]));
187    }
188}