Skip to main content

brep_instructions/
fields.rs

1//! Step fields: what the person doing the work records at a step.
2//!
3//! An author adds any number of fields to a step ([`crate::model::Step::fields`]):
4//! a box to tick, a choice among options, a line or a box of text, a
5//! measurement with its limits, a serial number. The players show them as
6//! inputs and the printed pages as a paper form (a choice prints every option
7//! as its own box to mark). The values are a build's record, never the
8//! document's: the players keep them, and a jobs floor stores them with the
9//! step's sign-off.
10//!
11//! A value is plain JSON, the same in the page, the app and a server:
12//!
13//! | kind | value |
14//! |---|---|
15//! | `check` | `true` / `false` |
16//! | `choice` | the option's text; with `multiple`, an array of them; with `other`, any text |
17//! | `text`, `serial` | text |
18//! | `number` | a number (or text that reads as one) |
19//!
20//! [`evaluate`] reads one value against its field and [`blocking`] says why a
21//! step cannot be completed yet, so every player and every server apply the
22//! same rule.
23
24use serde::{Deserialize, Serialize};
25use serde_json::Value;
26
27/// The most lines a text field's box holds.
28pub const MAX_TEXT_LINES: u32 = 20;
29/// The most options a choice offers.
30pub const MAX_OPTIONS: usize = 50;
31/// The most decimals a measurement shows.
32pub const MAX_DECIMALS: u8 = 6;
33/// The longest text a value holds, in characters.
34pub 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/// One field of a step.
53#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct StepField {
57    /// `MF12`: unique in the document, never reused.
58    #[serde(default)]
59    pub id: String,
60    /// What the field asks for (`Bearing seated`, `Shaft diameter`).
61    #[serde(default)]
62    pub label: String,
63    /// The step is not complete until the field is filled (a `check`: ticked).
64    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
65    pub required: bool,
66    /// A line of help shown with the field.
67    #[serde(default, skip_serializing_if = "String::is_empty")]
68    pub hint: String,
69    #[serde(flatten)]
70    pub kind: FieldKind,
71}
72
73/// What a field records.
74#[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    /// One box to tick.
79    Check,
80    /// One of `options` (a dropdown; on paper, a box per option).
81    #[serde(rename_all = "camelCase")]
82    Choice {
83        options: Vec<String>,
84        /// Any number of the options may be picked.
85        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
86        multiple: bool,
87        /// A free-text "Other" value is allowed beside the options.
88        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
89        other: bool,
90    },
91    /// Written text: one line, or a box of `lines` lines.
92    #[serde(rename_all = "camelCase")]
93    Text {
94        #[serde(default = "one", skip_serializing_if = "is_one")]
95        lines: u32,
96    },
97    /// A measurement, with its unit and limits.
98    #[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        /// Decimals shown for the nominal and the limits.
109        #[serde(default, skip_serializing_if = "Option::is_none")]
110        decimals: Option<u8>,
111        /// A value outside the limits blocks the step's completion; when
112        /// false it is flagged and accepted.
113        #[serde(default = "yes", skip_serializing_if = "is_true")]
114        required_in_limits: bool,
115    },
116    /// A serial number not tied to a part (the build's own, a gauge's).
117    Serial,
118}
119
120impl FieldKind {
121    /// Every kind's key and label, in the order a dropdown lists them.
122    pub const CHOICES: [(&'static str, &'static str); 5] =
123        [("check", "Checkbox"), ("choice", "Choice"), ("text", "Text"), ("number", "Measurement"), ("serial", "Serial number")];
124
125    /// The kind's key, as written in the document.
126    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    /// A new field of the kind named `key`, as the editor adds it.
137    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
149/// The keys a field's JSON may carry beside `id`.
150const 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"];
153/// The keys that belong to one kind: dropped when a patch changes the kind.
154const KIND_KEYS: [&str; 9] = ["options", "multiple", "other", "lines", "unit", "nominal", "min", "max", "decimals"];
155
156impl StepField {
157    /// A new field of kind `key` (see [`FieldKind::new`]) labelled `label`.
158    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    /// Read a field from JSON (`{label, kind, …}`), refusing a key no field
163    /// has. A `choice` given without options, like any kind given bare, takes
164    /// the kind's defaults.
165    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    /// The field with `patch`'s keys set (`null` clears an optional one).
181    /// Changing `kind` drops what belonged to the old kind and takes the new
182    /// kind's defaults; the id never changes.
183    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    /// The structural rules of one field.
215    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    /// The options a choice offers, as shown: blank ones left out and a
250    /// repeated one listed once. Empty for every other kind.
251    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    /// A measurement's unit; empty for every other kind.
264    pub fn unit(&self) -> &str {
265        match &self.kind {
266            FieldKind::Number { unit, .. } => unit.trim(),
267            _ => "",
268        }
269    }
270
271    /// A measurement's nominal and limits as the page and the paper print
272    /// them: `10.00 mm, 9.95–10.05`, `min 2.0 N·m`, `max 5`; empty when the
273    /// field has none (or is no measurement). Only characters every output
274    /// can draw (the PDF's base font has no ≥ or ≤).
275    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
310/// `value` with `decimals` decimals, or as short as it reads when none is set.
311pub 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/// One value read against its field.
319#[derive(Debug, Clone, PartialEq)]
320pub struct Evaluated {
321    /// The value as it is stored: trimmed text, a number for a measurement,
322    /// an array for a multiple choice. `None`: nothing was entered (an
323    /// unticked box included).
324    pub value: Option<Value>,
325    /// A measurement with a limit: whether the value is inside. `None` for
326    /// every other field, a measurement without limits, and an empty one.
327    pub in_limits: Option<bool>,
328}
329
330impl Evaluated {
331    /// The value as one line of text, for a list or a CSV cell.
332    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
356/// Read `value` (absent: nothing entered) against `field`. An `Err` is a
357/// value the field cannot hold (text for a tick, an option the choice does
358/// not offer, something that is no number): a server refuses it.
359pub 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                // The options and, with `other`, one free text: no more.
385                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
430/// Why `field` keeps its step from being completed with this value, if it
431/// does: a required field left empty, or a measurement outside limits that
432/// must be inside.
433pub 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
450/// Everything that keeps a step with `fields` from being completed, given
451/// the values entered (looked up by field id): one reason per field, in
452/// order. A value its field cannot hold is a reason too.
453pub 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