Skip to main content

meal_planner/
plans.rs

1//! Mutable weekly meal plans and deterministic input validation.
2use crate::MealType;
3use chrono::{Datelike, Days, NaiveDate, Weekday};
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub struct PlanParticipant {
8    pub member_id: i64,
9    pub name: String,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct MealAssignment {
14    pub id: i64,
15    pub date: NaiveDate,
16    pub meal_type: MealType,
17    pub participants: Vec<PlanParticipant>,
18    #[serde(default)]
19    pub recipe_ids: Vec<i64>,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct WeeklyPlanDraft {
24    pub assignments: Vec<MealAssignment>,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct WeeklyPlan {
29    pub id: i64,
30    pub family_id: String,
31    pub week_start: NaiveDate,
32    pub assignments: Vec<MealAssignment>,
33    pub created_at: i64,
34}
35
36impl WeeklyPlanDraft {
37    pub(crate) fn validate(self, week_start: NaiveDate) -> Result<Self, String> {
38        if week_start.weekday() != Weekday::Mon {
39            return Err("week_start must be a Monday".into());
40        }
41        let week_end = week_start
42            .checked_add_days(Days::new(6))
43            .ok_or_else(|| "week_start is outside the supported date range".to_owned())?;
44        let mut ids = std::collections::HashSet::new();
45        for assignment in &self.assignments {
46            if assignment.id <= 0 || !ids.insert(assignment.id) {
47                return Err("assignment IDs must be positive and unique within a plan".into());
48            }
49            if assignment.date < week_start || assignment.date > week_end {
50                return Err("every assignment date must belong to the plan week".into());
51            }
52            if assignment.participants.is_empty() {
53                return Err("every assignment must include at least one participant".into());
54            }
55            let mut members = std::collections::HashSet::new();
56            for participant in &assignment.participants {
57                if participant.member_id <= 0 || participant.name.trim().is_empty() {
58                    return Err("assignment participants require a valid member and name".into());
59                }
60                if !members.insert(participant.member_id) {
61                    return Err("an assignment cannot contain a participant more than once".into());
62                }
63            }
64            if assignment.recipe_ids.iter().any(|id| *id <= 0) {
65                return Err("recipe_ids must contain only positive IDs".into());
66            }
67        }
68        Ok(self)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    #[test]
76    fn validates_week_boundary_and_monday_start() {
77        let monday = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
78        let assignment = MealAssignment {
79            id: 1,
80            date: monday,
81            meal_type: MealType::Lunch,
82            participants: vec![PlanParticipant {
83                member_id: 1,
84                name: "Alex".into(),
85            }],
86            recipe_ids: vec![],
87        };
88        assert!(
89            WeeklyPlanDraft {
90                assignments: vec![assignment.clone()]
91            }
92            .validate(monday)
93            .is_ok()
94        );
95        assert!(
96            WeeklyPlanDraft {
97                assignments: vec![]
98            }
99            .validate(monday.succ_opt().unwrap())
100            .is_err()
101        );
102        assert!(
103            WeeklyPlanDraft {
104                assignments: vec![assignment.clone(), assignment]
105            }
106            .validate(monday)
107            .is_err()
108        );
109    }
110}