1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
|
#![expect(clippy::unused_async)]
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
app::App,
storage::sql::{
mk_id,
product::{Product, ProductId},
product_amount::ProductAmount,
recipe_parent::RecipeParentId,
unit::UnitAmount,
},
};
macro_rules! for_in {
($value:expr, |$name:ident| $closoure:expr) => {{
let fun = async |$name| $closoure;
let mut output = Vec::with_capacity($value.len());
for $name in $value {
output.push(fun($name).await?);
}
output
}};
}
/// An recipe.
///
/// These are transparently expressed in cooklang.
#[derive(ToSchema, Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Recipe {
/// The unique id of this recipe.
pub(crate) id: RecipeId,
/// The name of the recipe.
///
/// This should be globally unique, to make searching easier for the user.
pub(crate) name: String,
/// The parent this recipe has.
///
/// This is effectively it's anchor in the recipe DAG.
/// None means, that it has no parents and as such is in the toplevel.
#[schema(nullable = false)]
pub(crate) parent: Option<RecipeParentId>,
/// The actual content of this recipe.
pub(crate) content: CooklangRecipe,
}
mk_id!(RecipeId and RecipeIdStub);
/// A complete recipe
///
/// The recipes do not have a name. You give it externally or maybe use
/// some metadata key.
///
/// The recipe returned from parsing is a [`ScalableRecipe`].
///
/// The difference between [`ScalableRecipe`] and [`ScaledRecipe`] is in the
/// values of the quantities of ingredients, cookware and timers. The parser
/// returns [`ScalableValue`]s and after scaling, these are converted to regular
/// [`Value`]s.
#[derive(ToSchema, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct CooklangRecipe {
/// Metadata as read from preamble
pub(crate) metadata: Metadata,
/// Each of the sections
///
/// If no sections declared, a section without name
/// is the default.
pub(crate) sections: Vec<Section>,
/// All the ingredients
pub(crate) ingredients: Vec<Ingredient>,
/// All the cookware
pub(crate) cookware: Vec<Cookware>,
/// All the timers
pub(crate) timers: Vec<Timer>,
}
/// A section holding steps
#[derive(Debug, ToSchema, Default, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct Section {
/// Name of the section
#[schema(nullable = false)]
pub(crate) name: Option<String>,
/// Content inside
pub(crate) content: Vec<Content>,
}
/// Each type of content inside a section
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub(crate) enum Content {
/// A step
Step(Step),
/// A paragraph of just text, no instructions
Text(String),
}
/// A step holding step [`Item`]s
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct Step {
/// [`Item`]s inside
pub(crate) items: Vec<Item>,
/// Step number
///
/// The step numbers start at 1 in each section and increase with non
/// text step.
pub(crate) number: u32,
}
/// A step item
///
/// Except for [`Item::Text`], the value is the index where the item is located
/// in it's corresponding [`Vec`] in the [`Recipe`].
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
#[serde(tag = "type", rename_all = "camelCase")]
pub(crate) enum Item {
/// Just plain text
Text {
value: String,
},
Ingredient {
index: usize,
},
Cookware {
index: usize,
},
Timer {
index: usize,
},
InlineQuantity {
index: usize,
},
}
/// A recipe ingredient
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) enum Ingredient {
/// This ingredient is a registered product.
RegisteredProduct {
id: ProductId,
/// Alias
#[schema(nullable = false)]
alias: Option<String>,
/// Quantity
#[schema(nullable = false)]
quantity: Option<ProductAmount>,
},
/// This ingredient is a not yet registered product.
NotRegisteredProduct {
name: String,
/// Quantity
#[schema(nullable = false)]
quantity: Option<UnitAmount>,
},
/// This ingredient is a reference to another recipe.
RecipeReference { id: RecipeId },
}
/// A recipe cookware item
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct Cookware {
/// Name
pub(crate) name: String,
/// Alias
#[schema(nullable = false)]
pub(crate) alias: Option<String>,
/// Amount needed
///
/// Note that this is a value, not a quantity, so it doesn't have units.
#[schema(nullable = false)]
pub(crate) quantity: Option<usize>,
/// Note
#[schema(nullable = false)]
pub(crate) note: Option<String>,
}
/// A recipe timer
///
/// If created from parsing, at least one of the fields is guaranteed to be
/// [`Some`].
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct Timer {
/// Name
#[schema(nullable = false)]
pub(crate) name: Option<String>,
/// Time quantity
pub(crate) quantity: UnitAmount,
}
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct Metadata {
#[schema(nullable = false)]
title: Option<String>,
#[schema(nullable = false)]
description: Option<String>,
#[schema(nullable = false)]
tags: Option<Vec<String>>,
#[schema(nullable = false)]
author: Option<NameAndUrl>,
#[schema(nullable = false)]
source: Option<NameAndUrl>,
// time: Option<serde_yaml::Value>,
// prep_time: Option<serde_yaml::Value>,
// cook_time: Option<serde_yaml::Value>,
// servings: Option<serde_yaml::Value>,
// difficulty: Option<serde_yaml::Value>,
// cuisine: Option<serde_yaml::Value>,
// diet: Option<serde_yaml::Value>,
// images: Option<serde_yaml::Value>,
// locale: Option<serde_yaml::Value>,
// other: serde_yaml::Mapping,
}
pub(crate) mod conversion {
use crate::storage::sql::get::product::from_id;
#[derive(thiserror::Error, Debug)]
pub(crate) enum Error {
#[error("Failed to get a product by id: `{0}`")]
ProductAccess(#[from] from_id::Error),
}
}
#[derive(Debug, ToSchema, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) struct NameAndUrl {
#[schema(nullable = false)]
name: Option<String>,
#[schema(nullable = false)]
url: Option<String>,
}
impl NameAndUrl {
async fn from(value: cooklang::metadata::NameAndUrl) -> Result<Self, conversion::Error> {
Ok(Self {
name: value.name().map(|v| v.to_owned()),
url: value.url().map(|v| v.to_owned()),
})
}
}
impl CooklangRecipe {
pub(crate) async fn from(
app: &App,
value: cooklang::Recipe,
) -> Result<Self, conversion::Error> {
Ok(Self {
metadata: Metadata::from(value.metadata).await?,
sections: for_in!(value.sections, |s| Section::from(s).await),
ingredients: for_in!(value.ingredients, |i| Ingredient::from(app, i).await),
cookware: for_in!(value.cookware, |c| Cookware::from(c).await),
timers: for_in!(value.timers, |t| Timer::from(t).await),
})
}
}
impl Metadata {
async fn from(value: cooklang::Metadata) -> Result<Self, conversion::Error> {
let author = if let Some(author) = value.author() {
Some(NameAndUrl::from(author).await?)
} else {
None
};
let source = if let Some(source) = value.source() {
Some(NameAndUrl::from(source).await?)
} else {
None
};
Ok(Self {
title: value.title().map(str::to_owned),
description: value.description().map(str::to_owned),
tags: value
.tags()
.map(|vec| vec.into_iter().map(|c| c.to_string()).collect()),
author,
source,
// time: value.time(&Converter::bundled()).map(|t| t.total()),
// prep_time: todo!(),
// cook_time: todo!(),
// servings: todo!(),
// difficulty: todo!(),
// cuisine: todo!(),
// diet: todo!(),
// images: todo!(),
// locale: todo!(),
// other: value.map_filtered().,
})
}
}
impl Section {
async fn from(value: cooklang::Section) -> Result<Self, conversion::Error> {
Ok(Self {
name: value.name,
content: for_in!(value.content, |c| Content::from(c).await),
})
}
}
impl Content {
async fn from(value: cooklang::Content) -> Result<Self, conversion::Error> {
match value {
cooklang::Content::Step(step) => Ok(Self::Step(Step::from(step).await?)),
cooklang::Content::Text(text) => Ok(Self::Text(text)),
}
}
}
impl Step {
async fn from(value: cooklang::Step) -> Result<Self, conversion::Error> {
Ok(Self {
items: for_in!(value.items, |item| Item::from(item).await),
number: value.number,
})
}
}
impl Item {
async fn from(value: cooklang::Item) -> Result<Self, conversion::Error> {
match value {
cooklang::Item::Text { value } => Ok(Self::Text { value }),
cooklang::Item::Ingredient { index } => Ok(Self::Ingredient { index }),
cooklang::Item::Cookware { index } => Ok(Self::Cookware { index }),
cooklang::Item::Timer { index } => Ok(Self::Timer { index }),
cooklang::Item::InlineQuantity { index } => Ok(Self::InlineQuantity { index }),
}
}
}
impl Ingredient {
async fn from(app: &App, value: cooklang::Ingredient) -> Result<Self, conversion::Error> {
if value.name.starts_with('/') {
Ok(Self::RecipeReference { id: todo!() })
} else if let Some(product) = Product::from_name(&app, value.name.as_str()).await? {
Ok(Self::RegisteredProduct {
id: product.id,
alias: value.alias,
quantity: None,
})
} else {
Ok(Self::NotRegisteredProduct {
name: value.name,
quantity: None,
})
}
}
}
impl Cookware {
async fn from(value: cooklang::Cookware) -> Result<Self, conversion::Error> {
Ok(Self {
name: value.name,
alias: value.alias,
quantity: value.quantity.map(|q| match q.value() {
cooklang::Value::Number(number) => number.value() as usize,
cooklang::Value::Range { start, end } => todo!(),
cooklang::Value::Text(_) => todo!(),
}),
note: value.note,
})
}
}
impl Timer {
async fn from(value: cooklang::Timer) -> Result<Self, conversion::Error> {
Ok(Self {
name: value.name,
quantity: todo!(),
})
}
}
|