1use serde::{Deserialize, Serialize};
25use serde_json::Value;
26
27pub const MAX_TEXT_LINES: u32 = 20;
29pub const MAX_OPTIONS: usize = 50;
31pub const MAX_DECIMALS: u8 = 6;
33pub const MAX_VALUE_CHARS: usize = 4000;
35
36fn one() -> u32 {
37 1
38}
39
40fn yes() -> bool {
41 true
42}
43
44fn is_true(value: &bool) -> bool {
45 *value
46}
47
48fn is_one(value: &u32) -> bool {
49 *value == 1
50}
51
52#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct StepField {
57 #[serde(default)]
59 pub id: String,
60 #[serde(default)]
62 pub label: String,
63 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
65 pub required: bool,
66 #[serde(default, skip_serializing_if = "String::is_empty")]
68 pub hint: String,
69 #[serde(flatten)]
70 pub kind: FieldKind,
71}
72
73#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "camelCase")]
77pub enum FieldKind {
78 Check,
80 #[serde(rename_all = "camelCase")]
82 Choice {
83 options: Vec<String>,
84 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
86 multiple: bool,
87 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
89 other: bool,
90 },
91 #[serde(rename_all = "camelCase")]
93 Text {
94 #[serde(default = "one", skip_serializing_if = "is_one")]
95 lines: u32,
96 },
97 #[serde(rename_all = "camelCase")]
99 Number {
100 #[serde(default, skip_serializing_if = "String::is_empty")]
101 unit: String,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 nominal: Option<f64>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 min: Option<f64>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 max: Option<f64>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 decimals: Option<u8>,
111 #[serde(default = "yes", skip_serializing_if = "is_true")]
114 required_in_limits: bool,
115 },
116 Serial,
118}
119
120impl FieldKind {
121 pub const CHOICES: [(&'static str, &'static str); 5] =
123 [("check", "Checkbox"), ("choice", "Choice"), ("text", "Text"), ("number", "Measurement"), ("serial", "Serial number")];
124
125 pub fn key(&self) -> &'static str {
127 match self {
128 FieldKind::Check => "check",
129 FieldKind::Choice { .. } => "choice",
130 FieldKind::Text { .. } => "text",
131 FieldKind::Number { .. } => "number",
132 FieldKind::Serial => "serial",
133 }
134 }
135
136 pub fn new(key: &str) -> Option<Self> {
138 Some(match key {
139 "check" => FieldKind::Check,
140 "choice" => FieldKind::Choice { options: vec!["Option 1".into(), "Option 2".into()], multiple: false, other: false },
141 "text" => FieldKind::Text { lines: 1 },
142 "number" => FieldKind::Number { unit: String::new(), nominal: None, min: None, max: None, decimals: None, required_in_limits: true },
143 "serial" => FieldKind::Serial,
144 _ => return None,
145 })
146 }
147}
148
149const FIELD_KEYS: [&str; 12] =
151 ["label", "required", "hint", "kind", "options", "multiple", "other", "lines", "unit", "nominal", "min", "max"];
152const MORE_FIELD_KEYS: [&str; 2] = ["decimals", "requiredInLimits"];
153const KIND_KEYS: [&str; 9] = ["options", "multiple", "other", "lines", "unit", "nominal", "min", "max", "decimals"];
155
156impl StepField {
157 pub fn new(id: String, key: &str, label: &str) -> Option<Self> {
159 Some(Self { id, label: label.to_string(), required: false, hint: String::new(), kind: FieldKind::new(key)? })
160 }
161
162 pub fn from_json(value: &Value) -> Result<Self, String> {
166 let object = value.as_object().ok_or("a field is a JSON object")?;
167 check_keys(object.keys().map(String::as_str), true)?;
168 let key = object.get("kind").and_then(Value::as_str).ok_or("a field names its kind: check, choice, text, number or serial")?;
169 let defaults = FieldKind::new(key).ok_or_else(|| format!("field kind '{key}': check, choice, text, number or serial"))?;
170 let mut merged = serde_json::to_value(StepField { id: String::new(), label: String::new(), required: false, hint: String::new(), kind: defaults })
171 .map_err(|e| e.to_string())?;
172 for (k, v) in object {
173 merged[k.as_str()] = v.clone();
174 }
175 let field: StepField = serde_json::from_value(merged).map_err(|e| format!("field: {e}"))?;
176 field.validate()?;
177 Ok(field)
178 }
179
180 pub fn patched(&self, patch: &Value) -> Result<Self, String> {
184 let object = patch.as_object().ok_or("a field update is a JSON object")?;
185 check_keys(object.keys().map(String::as_str), false)?;
186 let mut value = serde_json::to_value(self).map_err(|e| e.to_string())?;
187 if let Some(kind) = object.get("kind") {
188 let key = kind.as_str().ok_or("field kind: check, choice, text, number or serial")?;
189 if key != self.kind.key() {
190 let defaults = FieldKind::new(key).ok_or_else(|| format!("field kind '{key}': check, choice, text, number or serial"))?;
191 let map = value.as_object_mut().expect("a field serializes as an object");
192 for k in KIND_KEYS.iter().chain(&["requiredInLimits"]) {
193 map.remove(*k);
194 }
195 let fresh = serde_json::to_value(&defaults).map_err(|e| e.to_string())?;
196 for (k, v) in fresh.as_object().expect("a kind serializes as an object") {
197 map.insert(k.clone(), v.clone());
198 }
199 }
200 }
201 let map = value.as_object_mut().expect("a field serializes as an object");
202 for (k, v) in object {
203 if v.is_null() {
204 map.remove(k);
205 } else {
206 map.insert(k.clone(), v.clone());
207 }
208 }
209 let field: StepField = serde_json::from_value(value).map_err(|e| format!("field: {e}"))?;
210 field.validate()?;
211 Ok(field)
212 }
213
214 pub fn validate(&self) -> Result<(), String> {
216 let name = if self.label.is_empty() { self.id.as_str() } else { self.label.as_str() };
217 match &self.kind {
218 FieldKind::Check | FieldKind::Serial => {}
219 FieldKind::Choice { options, .. } => {
220 if options.is_empty() {
221 return Err(format!("field '{name}': a choice needs at least one option"));
222 }
223 if options.len() > MAX_OPTIONS {
224 return Err(format!("field '{name}': a choice has at most {MAX_OPTIONS} options"));
225 }
226 }
227 FieldKind::Text { lines } => {
228 if !(1..=MAX_TEXT_LINES).contains(lines) {
229 return Err(format!("field '{name}': 1 to {MAX_TEXT_LINES} lines"));
230 }
231 }
232 FieldKind::Number { nominal, min, max, decimals, .. } => {
233 if [nominal, min, max].iter().any(|v| v.is_some_and(|v| !v.is_finite())) {
234 return Err(format!("field '{name}': the nominal and the limits are finite numbers"));
235 }
236 if let (Some(min), Some(max)) = (min, max) {
237 if min > max {
238 return Err(format!("field '{name}': the minimum ({min}) is above the maximum ({max})"));
239 }
240 }
241 if decimals.is_some_and(|d| d > MAX_DECIMALS) {
242 return Err(format!("field '{name}': at most {MAX_DECIMALS} decimals"));
243 }
244 }
245 }
246 Ok(())
247 }
248
249 pub fn options(&self) -> Vec<&str> {
252 let FieldKind::Choice { options, .. } = &self.kind else { return Vec::new() };
253 let mut out: Vec<&str> = Vec::new();
254 for option in options {
255 let option = option.trim();
256 if !option.is_empty() && !out.contains(&option) {
257 out.push(option);
258 }
259 }
260 out
261 }
262
263 pub fn unit(&self) -> &str {
265 match &self.kind {
266 FieldKind::Number { unit, .. } => unit.trim(),
267 _ => "",
268 }
269 }
270
271 pub fn limits_text(&self) -> String {
276 let FieldKind::Number { unit, nominal, min, max, decimals, .. } = &self.kind else { return String::new() };
277 let show = |v: f64| format_number(v, *decimals);
278 let unit = unit.trim();
279 let with_unit = |text: String| if unit.is_empty() { text } else { format!("{text} {unit}") };
280 let range = match (min, max) {
281 (Some(min), Some(max)) => Some(format!("{}\u{2013}{}", show(*min), show(*max))),
282 (Some(min), None) => Some(format!("min {}", show(*min))),
283 (None, Some(max)) => Some(format!("max {}", show(*max))),
284 (None, None) => None,
285 };
286 match (nominal, range) {
287 (Some(nominal), Some(range)) => format!("{}, {range}", with_unit(show(*nominal))),
288 (Some(nominal), None) => with_unit(show(*nominal)),
289 (None, Some(range)) => with_unit(range),
290 (None, None) => String::new(),
291 }
292 }
293}
294
295fn check_keys<'a>(keys: impl Iterator<Item = &'a str>, id_allowed: bool) -> Result<(), String> {
296 for key in keys {
297 if key == "id" {
298 if id_allowed {
299 continue;
300 }
301 return Err("a field's id never changes".into());
302 }
303 if !FIELD_KEYS.contains(&key) && !MORE_FIELD_KEYS.contains(&key) {
304 return Err(format!("a field has no key '{key}'"));
305 }
306 }
307 Ok(())
308}
309
310pub fn format_number(value: f64, decimals: Option<u8>) -> String {
312 match decimals {
313 Some(d) => format!("{value:.*}", usize::from(d.min(MAX_DECIMALS))),
314 None => format!("{value}"),
315 }
316}
317
318#[derive(Debug, Clone, PartialEq)]
320pub struct Evaluated {
321 pub value: Option<Value>,
325 pub in_limits: Option<bool>,
328}
329
330impl Evaluated {
331 pub fn text(&self) -> String {
333 match &self.value {
334 None => String::new(),
335 Some(Value::Bool(true)) => "yes".into(),
336 Some(Value::Bool(false)) => "no".into(),
337 Some(Value::String(text)) => text.clone(),
338 Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; "),
339 Some(other) => other.to_string(),
340 }
341 }
342}
343
344fn text_of(field: &StepField, value: &Value) -> Result<Option<String>, String> {
345 let text = value.as_str().ok_or_else(|| format!("field '{}' takes text", name_of(field)))?.trim().to_string();
346 if text.chars().count() > MAX_VALUE_CHARS {
347 return Err(format!("field '{}': at most {MAX_VALUE_CHARS} characters", name_of(field)));
348 }
349 Ok((!text.is_empty()).then_some(text))
350}
351
352fn name_of(field: &StepField) -> &str {
353 if field.label.trim().is_empty() { &field.id } else { field.label.trim() }
354}
355
356pub fn evaluate(field: &StepField, value: Option<&Value>) -> Result<Evaluated, String> {
360 let empty = Evaluated { value: None, in_limits: None };
361 let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(empty) };
362 let name = name_of(field);
363 match &field.kind {
364 FieldKind::Check => match value {
365 Value::Bool(true) => Ok(Evaluated { value: Some(Value::Bool(true)), in_limits: None }),
366 Value::Bool(false) => Ok(empty),
367 _ => Err(format!("field '{name}' is a tick: true or false")),
368 },
369 FieldKind::Text { .. } | FieldKind::Serial => Ok(Evaluated { value: text_of(field, value)?.map(Value::String), in_limits: None }),
370 FieldKind::Choice { multiple, other, .. } => {
371 let options = field.options();
372 let offered = |text: &str| -> Result<(), String> {
373 if *other || options.contains(&text) {
374 Ok(())
375 } else {
376 Err(format!("field '{name}' offers no option '{text}'"))
377 }
378 };
379 if *multiple {
380 let items: Vec<&Value> = match value {
381 Value::Array(items) => items.iter().collect(),
382 one => vec![one],
383 };
384 if items.len() > options.len() + usize::from(*other) + MAX_OPTIONS {
386 return Err(format!("field '{name}' takes at most {} values", options.len() + usize::from(*other)));
387 }
388 let mut picked: Vec<String> = Vec::new();
389 for item in items {
390 if let Some(text) = text_of(field, item)? {
391 offered(&text)?;
392 if !picked.contains(&text) {
393 picked.push(text);
394 }
395 }
396 }
397 if picked.iter().filter(|text| !options.iter().any(|option| *option == text.as_str())).count() > 1 {
398 return Err(format!("field '{name}' takes one Other value"));
399 }
400 if picked.is_empty() {
401 return Ok(empty);
402 }
403 Ok(Evaluated { value: Some(Value::Array(picked.into_iter().map(Value::String).collect())), in_limits: None })
404 } else {
405 match text_of(field, value)? {
406 None => Ok(empty),
407 Some(text) => {
408 offered(&text)?;
409 Ok(Evaluated { value: Some(Value::String(text)), in_limits: None })
410 }
411 }
412 }
413 }
414 FieldKind::Number { min, max, .. } => {
415 let number = match value {
416 Value::Number(n) => n.as_f64(),
417 Value::String(text) if text.trim().is_empty() => return Ok(empty),
418 Value::String(text) => text.trim().parse::<f64>().ok(),
419 _ => None,
420 }
421 .filter(|n| n.is_finite())
422 .ok_or_else(|| format!("field '{name}' takes a number"))?;
423 let in_limits = (min.is_some() || max.is_some()).then(|| min.is_none_or(|m| number >= m) && max.is_none_or(|m| number <= m));
424 let stored = serde_json::Number::from_f64(number).map(Value::Number).ok_or_else(|| format!("field '{name}' takes a number"))?;
425 Ok(Evaluated { value: Some(stored), in_limits })
426 }
427 }
428}
429
430pub fn blocking(field: &StepField, evaluated: &Evaluated) -> Option<String> {
434 let name = name_of(field);
435 if evaluated.value.is_none() {
436 return field.required.then(|| match field.kind {
437 FieldKind::Check => format!("tick '{name}'"),
438 FieldKind::Choice { .. } => format!("choose '{name}'"),
439 _ => format!("enter '{name}'"),
440 });
441 }
442 if let FieldKind::Number { required_in_limits: true, .. } = field.kind {
443 if evaluated.in_limits == Some(false) {
444 return Some(format!("'{name}' is out of limits ({})", field.limits_text()));
445 }
446 }
447 None
448}
449
450pub fn missing<'a>(fields: &[StepField], value_of: impl Fn(&str) -> Option<&'a Value>) -> Vec<String> {
454 fields
455 .iter()
456 .filter_map(|field| match evaluate(field, value_of(&field.id)) {
457 Ok(evaluated) => blocking(field, &evaluated),
458 Err(error) => Some(error),
459 })
460 .collect()
461}
462