1use chrono::{Datelike, Days, NaiveDate, Weekday};
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub struct FamilyMember {
8 pub id: i64,
9 pub name: String,
10 pub active: bool,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum MealType {
17 Lunch,
18 Dinner,
19}
20impl MealType {
21 pub const ALL: [Self; 2] = [Self::Lunch, Self::Dinner];
22 pub(crate) fn as_str(self) -> &'static str {
23 match self {
24 Self::Lunch => "lunch",
25 Self::Dinner => "dinner",
26 }
27 }
28 pub(crate) fn parse(value: &str) -> Option<Self> {
29 match value {
30 "lunch" => Some(Self::Lunch),
31 "dinner" => Some(Self::Dinner),
32 _ => None,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum MealArrangement {
41 Home,
42 School,
43 Away,
44 NotParticipating,
45}
46impl MealArrangement {
47 pub(crate) fn as_str(self) -> &'static str {
48 match self {
49 Self::Home => "home",
50 Self::School => "school",
51 Self::Away => "away",
52 Self::NotParticipating => "not_participating",
53 }
54 }
55 pub(crate) fn parse(value: &str) -> Option<Self> {
56 match value {
57 "home" => Some(Self::Home),
58 "school" => Some(Self::School),
59 "away" => Some(Self::Away),
60 "not_participating" => Some(Self::NotParticipating),
61 _ => None,
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
68#[serde(rename_all = "snake_case")]
69#[repr(u8)]
70pub enum MealWeekday {
71 Monday,
72 Tuesday,
73 Wednesday,
74 Thursday,
75 Friday,
76 Saturday,
77 Sunday,
78}
79impl MealWeekday {
80 pub fn from_date(date: NaiveDate) -> Self {
81 match date.weekday() {
82 Weekday::Mon => Self::Monday,
83 Weekday::Tue => Self::Tuesday,
84 Weekday::Wed => Self::Wednesday,
85 Weekday::Thu => Self::Thursday,
86 Weekday::Fri => Self::Friday,
87 Weekday::Sat => Self::Saturday,
88 Weekday::Sun => Self::Sunday,
89 }
90 }
91 pub(crate) fn from_number(value: u8) -> Option<Self> {
92 match value {
93 0 => Some(Self::Monday),
94 1 => Some(Self::Tuesday),
95 2 => Some(Self::Wednesday),
96 3 => Some(Self::Thursday),
97 4 => Some(Self::Friday),
98 5 => Some(Self::Saturday),
99 6 => Some(Self::Sunday),
100 _ => None,
101 }
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
107pub struct RecurringParticipationRule {
108 pub id: i64,
109 pub member_id: i64,
110 pub weekday: MealWeekday,
111 pub meal_type: MealType,
112 pub arrangement: MealArrangement,
113 pub effective_from: Option<NaiveDate>,
114 pub effective_until: Option<NaiveDate>,
115}
116impl RecurringParticipationRule {
117 pub fn applies_on(&self, date: NaiveDate) -> bool {
118 self.weekday == MealWeekday::from_date(date)
119 && self.effective_from.is_none_or(|from| date >= from)
120 && self.effective_until.is_none_or(|until| date <= until)
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
126pub struct MealException {
127 pub id: i64,
128 pub member_id: i64,
129 pub date: NaiveDate,
130 pub meal_type: MealType,
131 pub arrangement: MealArrangement,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum ParticipationSource {
137 RecurringRule,
138 DateException,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum ParticipationStatus {
144 Unconfigured,
145 Configured {
146 arrangement: MealArrangement,
147 source: ParticipationSource,
148 },
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct MealParticipation {
154 pub date: NaiveDate,
155 pub meal_type: MealType,
156 pub member: FamilyMember,
157 pub status: ParticipationStatus,
158}
159
160pub struct ParticipationResolver;
162impl ParticipationResolver {
163 pub fn resolve_date(
164 date: NaiveDate,
165 members: &[FamilyMember],
166 rules: &[RecurringParticipationRule],
167 exceptions: &[MealException],
168 ) -> Vec<MealParticipation> {
169 resolve_date(date, members, rules, exceptions)
170 }
171 pub fn resolve_week(
172 start: NaiveDate,
173 members: &[FamilyMember],
174 rules: &[RecurringParticipationRule],
175 exceptions: &[MealException],
176 ) -> Vec<MealParticipation> {
177 resolve_week(start, members, rules, exceptions)
178 }
179}
180
181pub fn resolve_date(
184 date: NaiveDate,
185 members: &[FamilyMember],
186 rules: &[RecurringParticipationRule],
187 exceptions: &[MealException],
188) -> Vec<MealParticipation> {
189 let mut output = Vec::new();
190 for member in members.iter().filter(|member| member.active) {
191 for meal_type in MealType::ALL {
192 let exception = exceptions.iter().find(|item| {
193 item.member_id == member.id && item.date == date && item.meal_type == meal_type
194 });
195 let status = if let Some(item) = exception {
196 ParticipationStatus::Configured {
197 arrangement: item.arrangement,
198 source: ParticipationSource::DateException,
199 }
200 } else {
201 rules
202 .iter()
203 .filter(|rule| {
204 rule.member_id == member.id
205 && rule.meal_type == meal_type
206 && rule.applies_on(date)
207 })
208 .max_by_key(|rule| (rule.effective_from, rule.id))
209 .map_or(ParticipationStatus::Unconfigured, |rule| {
210 ParticipationStatus::Configured {
211 arrangement: rule.arrangement,
212 source: ParticipationSource::RecurringRule,
213 }
214 })
215 };
216 output.push(MealParticipation {
217 date,
218 meal_type,
219 member: member.clone(),
220 status,
221 });
222 }
223 }
224 output
225}
226
227pub fn resolve_week(
229 start: NaiveDate,
230 members: &[FamilyMember],
231 rules: &[RecurringParticipationRule],
232 exceptions: &[MealException],
233) -> Vec<MealParticipation> {
234 (0..7)
235 .filter_map(|offset| start.checked_add_days(Days::new(offset)))
236 .flat_map(|date| resolve_date(date, members, rules, exceptions))
237 .collect()
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243 fn date(s: &str) -> NaiveDate {
244 NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
245 }
246 fn member() -> FamilyMember {
247 FamilyMember {
248 id: 1,
249 name: "Alex".into(),
250 active: true,
251 }
252 }
253 fn rule(
254 id: i64,
255 arrangement: MealArrangement,
256 from: Option<&str>,
257 until: Option<&str>,
258 ) -> RecurringParticipationRule {
259 RecurringParticipationRule {
260 id,
261 member_id: 1,
262 weekday: MealWeekday::Monday,
263 meal_type: MealType::Lunch,
264 arrangement,
265 effective_from: from.map(date),
266 effective_until: until.map(date),
267 }
268 }
269 #[test]
270 fn only_lunch_and_dinner_are_supported() {
271 assert_eq!(MealType::ALL, [MealType::Lunch, MealType::Dinner]);
272 assert!(serde_json::from_str::<MealType>(r#""breakfast""#).is_err());
273 }
274
275 #[test]
276 fn exception_overrides_rule_and_can_mean_not_participating() {
277 let exception = MealException {
278 id: 1,
279 member_id: 1,
280 date: date("2026-11-16"),
281 meal_type: MealType::Lunch,
282 arrangement: MealArrangement::NotParticipating,
283 };
284 let result = resolve_date(
285 date("2026-11-16"),
286 &[member()],
287 &[rule(1, MealArrangement::School, None, None)],
288 &[exception],
289 );
290 assert_eq!(
291 result[0].status,
292 ParticipationStatus::Configured {
293 arrangement: MealArrangement::NotParticipating,
294 source: ParticipationSource::DateException
295 }
296 );
297 }
298 #[test]
299 fn latest_overlapping_rule_wins() {
300 let result = resolve_date(
301 date("2026-11-16"),
302 &[member()],
303 &[
304 rule(1, MealArrangement::Home, Some("2026-01-01"), None),
305 rule(2, MealArrangement::School, Some("2026-11-01"), None),
306 ],
307 &[],
308 );
309 assert_eq!(
310 result[0].status,
311 ParticipationStatus::Configured {
312 arrangement: MealArrangement::School,
313 source: ParticipationSource::RecurringRule
314 }
315 );
316 }
317 #[test]
318 fn effective_boundaries_and_weekdays_are_respected() {
319 let rules = [rule(
320 1,
321 MealArrangement::Away,
322 Some("2026-11-16"),
323 Some("2026-11-16"),
324 )];
325 assert!(matches!(
326 resolve_date(date("2026-11-16"), &[member()], &rules, &[])[0].status,
327 ParticipationStatus::Configured { .. }
328 ));
329 assert_eq!(
330 resolve_date(date("2026-11-17"), &[member()], &rules, &[])[0].status,
331 ParticipationStatus::Unconfigured
332 );
333 }
334 #[test]
335 fn missing_configuration_is_distinct_and_week_has_seven_days() {
336 assert!(
337 resolve_date(date("2026-11-16"), &[member()], &[], &[])
338 .iter()
339 .all(|item| item.status == ParticipationStatus::Unconfigured)
340 );
341 assert_eq!(
342 resolve_week(date("2026-11-16"), &[member()], &[], &[]).len(),
343 14
344 );
345 }
346}