1use crate::{MealAssignment, Recipe};
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct ShoppingList {
7 pub id: i64,
8 pub family_id: String,
9 pub start_date: chrono::NaiveDate,
10 pub end_date: chrono::NaiveDate,
11 pub items: Vec<ShoppingListItem>,
12 pub created_at: i64,
13 pub updated_at: i64,
14}
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub struct ShoppingListItem {
17 pub id: i64,
18 pub name: String,
19 pub quantity: Option<f64>,
20 pub unit: Option<String>,
21 pub purchased: bool,
22 pub source_assignment_ids: Vec<i64>,
23 pub source_recipe_ids: Vec<i64>,
24 pub manually_added: bool,
25 pub manually_removed: bool,
26 pub quantity_overridden: bool,
27 pub stale: bool,
28}
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct NewShoppingListItem {
31 pub name: String,
32 pub quantity: Option<f64>,
33 pub unit: Option<String>,
34}
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct ShoppingListItemUpdate {
37 pub name: String,
38 pub quantity: Option<f64>,
39 pub unit: Option<String>,
40 pub purchased: bool,
41}
42#[derive(Debug, Clone)]
43pub(super) struct GeneratedItem {
44 pub(super) name: String,
45 pub(super) quantity: Option<f64>,
46 pub(super) unit: Option<String>,
47 pub(super) source_assignment_ids: Vec<i64>,
48 pub(super) source_recipe_ids: Vec<i64>,
49}
50
51pub(super) fn generate_items(
52 assignments: &[MealAssignment],
53 mut recipe_for: impl FnMut(i64) -> Option<Recipe>,
54) -> Result<Vec<GeneratedItem>, String> {
55 let mut items: Vec<GeneratedItem> = Vec::new();
56 for assignment in assignments {
57 for recipe_id in &assignment.recipe_ids {
58 let recipe = recipe_for(*recipe_id)
59 .ok_or_else(|| format!("recipe {recipe_id} referenced by plan was not found"))?;
60 let factor = assignment.participants.len() as f64 / recipe.draft.servings as f64;
61 for ingredient in recipe.draft.ingredients {
62 let (unit, multiplier) = normalize_unit(ingredient.unit.as_deref());
63 let quantity = ingredient.amount.map(|a| a * factor * multiplier);
64 let key = (normalize_name(&ingredient.name), unit.clone());
65 let existing = items
66 .iter_mut()
67 .find(|i| (normalize_name(&i.name), i.unit.clone()) == key);
68 if let Some(existing) = existing {
69 existing.quantity = match (existing.quantity, quantity) {
70 (Some(a), Some(b)) => Some(a + b),
71 _ => None,
72 };
73 push_unique(&mut existing.source_assignment_ids, assignment.id);
74 push_unique(&mut existing.source_recipe_ids, *recipe_id);
75 } else {
76 items.push(GeneratedItem {
77 name: ingredient.name,
78 quantity,
79 unit,
80 source_assignment_ids: vec![assignment.id],
81 source_recipe_ids: vec![*recipe_id],
82 });
83 }
84 }
85 }
86 }
87 Ok(items)
88}
89fn normalize_name(v: &str) -> String {
90 v.split_whitespace()
91 .collect::<Vec<_>>()
92 .join(" ")
93 .to_lowercase()
94}
95fn normalize_unit(v: Option<&str>) -> (Option<String>, f64) {
96 let Some(v) = v.map(str::trim).filter(|v| !v.is_empty()) else {
97 return (None, 1.0);
98 };
99 match v.to_ascii_lowercase().as_str() {
100 "g" | "gram" | "grams" => (Some("g".into()), 1.0),
101 "kg" | "kilogram" | "kilograms" => (Some("g".into()), 1000.0),
102 "ml" | "milliliter" | "milliliters" | "millilitre" | "millilitres" => {
103 (Some("ml".into()), 1.0)
104 }
105 "l" | "liter" | "liters" | "litre" | "litres" => (Some("ml".into()), 1000.0),
106 "pc" | "pcs" | "piece" | "pieces" | "unit" | "units" => (Some("piece".into()), 1.0),
107 other => (Some(other.to_owned()), 1.0),
108 }
109}
110fn push_unique(v: &mut Vec<i64>, id: i64) {
111 if !v.contains(&id) {
112 v.push(id)
113 }
114}
115impl ShoppingList {
116 pub(super) fn reconcile(
117 existing: Option<Self>,
118 family_id: String,
119 start_date: chrono::NaiveDate,
120 end_date: chrono::NaiveDate,
121 generated: Vec<GeneratedItem>,
122 now: i64,
123 ) -> Self {
124 let (id, created_at, mut old) = existing
125 .map(|l| (l.id, l.created_at, l.items))
126 .unwrap_or((0, now, Vec::new()));
127 let mut next = old.iter().map(|i| i.id).max().unwrap_or(0) + 1;
128 let mut items = Vec::new();
129 for g in generated {
130 let found = old.iter().position(|i| {
131 !i.manually_added
132 && normalize_name(&i.name) == normalize_name(&g.name)
133 && (i.manually_removed
134 || i.quantity_overridden
135 || normalize_unit(i.unit.as_deref()).0
136 == normalize_unit(g.unit.as_deref()).0)
137 });
138 if let Some(index) = found {
139 let mut old_item = old.remove(index);
140 old_item.source_assignment_ids = g.source_assignment_ids;
141 old_item.source_recipe_ids = g.source_recipe_ids;
142 old_item.stale = false;
143 if !old_item.quantity_overridden {
144 old_item.quantity = g.quantity;
145 old_item.unit = g.unit;
146 }
147 items.push(old_item);
148 } else {
149 items.push(ShoppingListItem {
150 id: next,
151 name: g.name,
152 quantity: g.quantity,
153 unit: g.unit,
154 purchased: false,
155 source_assignment_ids: g.source_assignment_ids,
156 source_recipe_ids: g.source_recipe_ids,
157 manually_added: false,
158 manually_removed: false,
159 quantity_overridden: false,
160 stale: false,
161 });
162 next += 1;
163 }
164 }
165 for mut item in old {
166 if item.manually_added
167 || item.manually_removed
168 || item.purchased
169 || item.quantity_overridden
170 {
171 if !item.manually_added {
172 item.stale = true;
173 item.source_assignment_ids.clear();
174 item.source_recipe_ids.clear();
175 }
176 items.push(item)
177 }
178 }
179 items.sort_by(|a, b| {
180 a.manually_added
181 .cmp(&b.manually_added)
182 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
183 .then_with(|| a.id.cmp(&b.id))
184 });
185 Self {
186 id,
187 family_id,
188 start_date,
189 end_date,
190 items,
191 created_at,
192 updated_at: now,
193 }
194 }
195}
196impl NewShoppingListItem {
197 pub(crate) fn validate(self) -> Result<Self, String> {
198 if self.name.trim().is_empty() {
199 return Err("shopping-list item name must not be empty".into());
200 }
201 if self.quantity.is_some_and(|v| !v.is_finite() || v <= 0.0) {
202 return Err("shopping-list quantity must be a positive finite number".into());
203 }
204 if self.unit.as_ref().is_some_and(|u| u.trim().is_empty()) {
205 return Err("shopping-list unit must not be empty".into());
206 }
207 Ok(Self {
208 name: self.name.trim().into(),
209 quantity: self.quantity,
210 unit: self.unit.map(|u| u.trim().into()),
211 })
212 }
213}
214impl ShoppingListItemUpdate {
215 pub(crate) fn validate(self) -> Result<Self, String> {
216 if self.name.trim().is_empty() {
217 return Err("shopping-list item name must not be empty".into());
218 }
219 if self.quantity.is_some_and(|v| !v.is_finite() || v <= 0.0) {
220 return Err("shopping-list quantity must be a positive finite number".into());
221 }
222 if self.unit.as_ref().is_some_and(|u| u.trim().is_empty()) {
223 return Err("shopping-list unit must not be empty".into());
224 }
225 Ok(Self {
226 name: self.name.trim().into(),
227 quantity: self.quantity,
228 unit: self.unit.map(|u| u.trim().into()),
229 purchased: self.purchased,
230 })
231 }
232}