1use crate::{MealPlannerError, MealPlannerStore, Recipe, RecipeDraft};
3use rusqlite::{OptionalExtension, params};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6impl MealPlannerStore {
7 pub fn create_recipe(
8 &self,
9 owner_id: &str,
10 draft: RecipeDraft,
11 ) -> Result<Recipe, MealPlannerError> {
12 let draft = draft.validate().map_err(MealPlannerError::InvalidInput)?;
13 let payload = serde_json::to_string(&draft)?;
14 let now = timestamp();
15 let mut connection = self
16 .connection
17 .lock()
18 .map_err(|_| MealPlannerError::LockPoisoned)?;
19 let transaction = connection.transaction()?;
20 transaction.execute(
21 "INSERT INTO recipes(title,payload,owner_id,family_id,created_at,updated_at) VALUES (?1,?2,?3,?4,?5,?5)",
22 params![draft.title, payload, owner_id, draft.family_id, now],
23 )?;
24 let id = transaction.last_insert_rowid();
25 transaction.commit()?;
26 Ok(Recipe {
27 id,
28 owner_id: owner_id.to_owned(),
29 draft,
30 created_at: now,
31 updated_at: now,
32 })
33 }
34
35 pub fn update_recipe(
36 &self,
37 id: i64,
38 owner_id: &str,
39 draft: RecipeDraft,
40 ) -> Result<Recipe, MealPlannerError> {
41 let draft = draft.validate().map_err(MealPlannerError::InvalidInput)?;
42 let payload = serde_json::to_string(&draft)?;
43 let now = timestamp();
44 let connection = self
45 .connection
46 .lock()
47 .map_err(|_| MealPlannerError::LockPoisoned)?;
48 if connection.execute(
49 "UPDATE recipes SET title=?1,payload=?2,family_id=?3,updated_at=?4 WHERE id=?5 AND owner_id=?6",
50 params![draft.title, payload, draft.family_id, now, id, owner_id],
51 )? == 0
52 {
53 return Err(MealPlannerError::NotFound);
54 }
55 load_recipe(&connection, id)?.ok_or(MealPlannerError::NotFound)
56 }
57
58 pub fn get_recipe(
59 &self,
60 id: i64,
61 owner_id: &str,
62 families: &[String],
63 ) -> Result<Recipe, MealPlannerError> {
64 let connection = self
65 .connection
66 .lock()
67 .map_err(|_| MealPlannerError::LockPoisoned)?;
68 let recipe = load_recipe(&connection, id)?.ok_or(MealPlannerError::NotFound)?;
69 let visible = match recipe.draft.family_id.as_deref() {
70 None => recipe.owner_id == owner_id,
71 Some(family) => families.iter().any(|available| available == family),
72 };
73 if !visible {
74 return Err(MealPlannerError::NotFound);
75 }
76 Ok(recipe)
77 }
78
79 pub fn list_recipes(
80 &self,
81 owner_id: &str,
82 families: &[String],
83 query: Option<&str>,
84 ) -> Result<Vec<Recipe>, MealPlannerError> {
85 let connection = self
86 .connection
87 .lock()
88 .map_err(|_| MealPlannerError::LockPoisoned)?;
89 let mut statement = connection.prepare(
90 "SELECT id,payload,owner_id,family_id,created_at,updated_at FROM recipes ORDER BY lower(title),id",
91 )?;
92 let rows = statement
93 .query_map([], row_recipe)?
94 .collect::<Result<Vec<_>, _>>()?;
95 let needle = query
96 .map(str::trim)
97 .filter(|value| !value.is_empty())
98 .map(str::to_lowercase);
99
100 Ok(rows
101 .into_iter()
102 .filter(|recipe| {
103 (match recipe.draft.family_id.as_deref() {
104 None => recipe.owner_id == owner_id,
105 Some(family) => families.iter().any(|available| available == family),
106 }) && needle.as_ref().is_none_or(|needle| {
107 let draft = &recipe.draft;
108 draft.title.to_lowercase().contains(needle)
109 || draft
110 .description
111 .as_deref()
112 .is_some_and(|value| value.to_lowercase().contains(needle))
113 || draft
114 .ingredients
115 .iter()
116 .any(|ingredient| ingredient.name.to_lowercase().contains(needle))
117 || draft
118 .tags
119 .iter()
120 .chain(&draft.categories)
121 .any(|value| value.to_lowercase().contains(needle))
122 })
123 })
124 .collect())
125 }
126
127 pub fn update_recipe_for_family(
128 &self,
129 id: i64,
130 owner_id: &str,
131 family_id: &str,
132 draft: RecipeDraft,
133 ) -> Result<Recipe, MealPlannerError> {
134 self.get_recipe(id, owner_id, &[family_id.to_owned()])?;
135 self.update_recipe(id, owner_id, draft)
136 }
137
138 pub fn delete_recipe_for_family(
139 &self,
140 id: i64,
141 owner_id: &str,
142 family_id: &str,
143 ) -> Result<(), MealPlannerError> {
144 self.get_recipe(id, owner_id, &[family_id.to_owned()])?;
145 self.delete_recipe(id, owner_id)
146 }
147
148 pub fn delete_recipe(&self, id: i64, owner_id: &str) -> Result<(), MealPlannerError> {
149 let connection = self
150 .connection
151 .lock()
152 .map_err(|_| MealPlannerError::LockPoisoned)?;
153 if connection.execute(
154 "DELETE FROM recipes WHERE id=?1 AND owner_id=?2",
155 params![id, owner_id],
156 )? == 0
157 {
158 return Err(MealPlannerError::NotFound);
159 }
160 Ok(())
161 }
162}
163
164fn row_recipe(row: &rusqlite::Row<'_>) -> rusqlite::Result<Recipe> {
165 let payload: String = row.get(1)?;
166 let draft = serde_json::from_str(&payload).map_err(|error| {
167 rusqlite::Error::FromSqlConversionFailure(1, rusqlite::types::Type::Text, Box::new(error))
168 })?;
169 Ok(Recipe {
170 id: row.get(0)?,
171 draft,
172 owner_id: row.get(2)?,
173 created_at: row.get(4)?,
174 updated_at: row.get(5)?,
175 })
176}
177
178pub(super) fn load_recipe(
179 connection: &rusqlite::Connection,
180 id: i64,
181) -> Result<Option<Recipe>, MealPlannerError> {
182 Ok(connection
183 .query_row(
184 "SELECT id,payload,owner_id,family_id,created_at,updated_at FROM recipes WHERE id=?1",
185 [id],
186 row_recipe,
187 )
188 .optional()?)
189}
190
191fn timestamp() -> i64 {
192 SystemTime::now()
193 .duration_since(UNIX_EPOCH)
194 .unwrap_or_default()
195 .as_secs() as i64
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201 use crate::RecipeIngredient;
202
203 fn store() -> MealPlannerStore {
204 MealPlannerStore::open_in_memory().unwrap()
205 }
206
207 fn draft(title: &str, ingredient: &str, family_id: Option<&str>) -> RecipeDraft {
208 RecipeDraft {
209 family_id: family_id.map(str::to_owned),
210 title: title.into(),
211 description: None,
212 servings: 2,
213 ingredients: vec![RecipeIngredient {
214 name: ingredient.into(),
215 amount: None,
216 unit: None,
217 preparation_note: None,
218 }],
219 steps: vec!["Cook".into()],
220 categories: vec![],
221 tags: vec![],
222 source: None,
223 notes: None,
224 dietary_information: vec![],
225 allergens: None,
226 }
227 }
228
229 #[test]
230 fn access_is_owner_or_matching_family() {
231 let store = store();
232 let private = store
233 .create_recipe("a", draft("Private", "x", None))
234 .unwrap();
235 let shared = store
236 .create_recipe("a", draft("Shared", "y", Some("f1")))
237 .unwrap();
238 store
239 .create_recipe("b", draft("Other", "z", Some("f2")))
240 .unwrap();
241
242 assert_eq!(
243 store.list_recipes("a", &["f1".into()], None).unwrap().len(),
244 2
245 );
246 assert!(store.get_recipe(private.id, "b", &[]).is_err());
247 assert!(store.get_recipe(shared.id, "b", &["f1".into()]).is_ok());
248 }
249
250 #[test]
251 fn only_owner_can_mutate() {
252 let store = store();
253 let recipe = store
254 .create_recipe("a", draft("Soup", "x", Some("f1")))
255 .unwrap();
256
257 assert!(
258 store
259 .update_recipe(recipe.id, "b", draft("No", "x", None))
260 .is_err()
261 );
262 assert_eq!(
263 store
264 .update_recipe(recipe.id, "a", draft("Soup", "x", None))
265 .unwrap()
266 .draft
267 .family_id,
268 None
269 );
270 assert!(store.delete_recipe(recipe.id, "b").is_err());
271 store.delete_recipe(recipe.id, "a").unwrap();
272 }
273}