Skip to main content

brep_plm/
seed.rs

1//! Family and template SEED documents, read and written the way the CAD app
2//! reads and writes them.
3//!
4//! The server never links the CAD app (it does link the kernel). This module
5//! reads and writes just the document fields families and templates use —
6//! `documentClass`, `familyTable`, `familySource`, `templateInputs` and
7//! `templateSource`. The pure functions over them it shares with the CAD app
8//! through the kernel (`brep_kernel::family`):
9//!
10//! * the expression rewrite a row or a template input applies
11//!   (`rewrite_expressions`), so a member the server assembles is the member
12//!   the CAD app would write;
13//! * the fingerprints (`history_hash`, `row_hash`; `template_hash` here), on
14//!   the kernel's `stable_json_hash` and pinned by golden values, so a stamp
15//!   the server writes and a stamp the CAD app writes compare equal.
16//!
17//! What this module can NOT do is evaluate an expression. The CAD app refuses
18//! a row whose values do not evaluate before writing it; the server writes it
19//! and marks it for a bake, and the headless CAD worker that takes the bake
20//! reports the problem.
21
22use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25use serde_json::Value;
26
27// The table, its rows, the key names, the expression rewrite, the identifier
28// rule and the fingerprints are the kernel's, the very code the CAD app runs
29// (I2, 2026-11-01): one copy instead of a port kept in step by tests.
30pub use brep_kernel::family::{
31    effective_row, history_hash, is_identifier, rewrite_expressions, row_hash, FamilyColumn, FamilyRow, FamilyTable,
32    DERIVED_FROM_KEY, DOCUMENT_CLASS_KEY, FAMILY_SOURCE_KEY, FAMILY_TABLE_KEY, TEMPLATE_SOURCE_KEY,
33};
34
35/// The document key a template's input marks are stored under.
36pub const TEMPLATE_INPUTS_KEY: &str = "templateInputs";
37/// The document key the part attributes (the BOM's source) live under.
38pub const PART_ATTRIBUTES_KEY: &str = "partAttributes";
39
40// ===========================================================================
41// The family table
42// ===========================================================================
43
44/// The table a document carries, or an empty one when it has none or the
45/// block does not parse — as the CAD app reads it.
46pub fn read_table(document: &Value) -> FamilyTable {
47    document
48        .get(FAMILY_TABLE_KEY)
49        .and_then(|block| serde_json::from_value(block.clone()).ok())
50        .unwrap_or_default()
51}
52
53/// Replace `document`'s table with `table`; every other field is kept.
54pub fn write_table(document: &mut Value, table: &FamilyTable) -> Result<(), String> {
55    let object = document
56        .as_object_mut()
57        .ok_or("the family document is not a JSON object")?;
58    let block = serde_json::to_value(table).map_err(|e| e.to_string())?;
59    object.insert(FAMILY_TABLE_KEY.into(), block);
60    Ok(())
61}
62
63/// The class a document says it is: `family`, `template`, or `None` for a
64/// normal part (which writes no field).
65pub fn document_class(document: &Value) -> Option<&str> {
66    match document.get(DOCUMENT_CLASS_KEY).and_then(Value::as_str) {
67        Some(class @ ("family" | "template")) => Some(class),
68        _ => None,
69    }
70}
71
72/// The `name = rhs` assignments of an expressions source, in order
73/// (`BREP_app/src/template.rs` `assignments`).
74pub fn assignments(expressions: &str) -> Vec<(String, String)> {
75    let mut cleaned = String::with_capacity(expressions.len());
76    for line in expressions.lines() {
77        cleaned.push_str(line.split("//").next().unwrap_or(""));
78        cleaned.push('\n');
79    }
80    cleaned
81        .split(';')
82        .filter_map(|statement| {
83            let (name, rhs) = statement.split_once('=')?;
84            let (name, rhs) = (name.trim(), rhs.trim());
85            (is_identifier(name) && !rhs.is_empty()).then(|| (name.to_string(), rhs.to_string()))
86        })
87        .collect()
88}
89
90fn expressions_of(document: &Value) -> &str {
91    document.get("expressions").and_then(Value::as_str).unwrap_or_default()
92}
93
94// ===========================================================================
95// Fingerprints
96// ===========================================================================
97
98/// The kernel's `stable_json_hash` itself (a sorted-key walk, string leaves
99/// verbatim, through std's `DefaultHasher`), so a stamp the server writes and
100/// a stamp the CAD app writes compare equal. The golden values in the tests
101/// below were computed by the kernel and fail loudly if it ever changes.
102pub use brep_kernel::stable_json_hash;
103
104/// A content hash of a template document less its view state.
105pub fn template_hash(template: &Value) -> String {
106    let mut content = template.clone();
107    if let Some(object) = content.as_object_mut() {
108        object.remove("workbench");
109    }
110    format!("{:016x}", stable_json_hash(&content))
111}
112
113// ===========================================================================
114// Building a member and a copy
115// ===========================================================================
116
117/// The CAD app's `familySource` stamp.
118#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct FamilySource {
121    /// The family's file name (`bolt.fbrep`).
122    pub family: String,
123    pub part_number: String,
124    pub values_hash: String,
125    pub history_hash: String,
126}
127
128/// The member document for `row` (already an [`effective_row`]), exactly as
129/// the CAD app's `member_document` builds it: the family's model with the
130/// row's values in its expressions, the table, the class and any template
131/// marks dropped, the part number and description in the part attributes, and
132/// the `familySource` stamp naming `family_file`.
133pub fn member_document(family: &Value, family_file: &str, row: &FamilyRow) -> Value {
134    let expressions = expressions_of(family);
135    let mut member = family.clone();
136    if let Some(object) = member.as_object_mut() {
137        object.remove(FAMILY_TABLE_KEY);
138        object.remove(DOCUMENT_CLASS_KEY);
139        object.remove(TEMPLATE_INPUTS_KEY);
140        object.remove(TEMPLATE_SOURCE_KEY);
141        object.remove(DERIVED_FROM_KEY);
142        object.insert(
143            "expressions".into(),
144            Value::String(rewrite_expressions(expressions, &row.values)),
145        );
146        let attributes = object
147            .entry(PART_ATTRIBUTES_KEY)
148            .or_insert_with(|| serde_json::json!({}));
149        if !attributes.is_object() {
150            *attributes = serde_json::json!({});
151        }
152        attributes["Part_Number"] = Value::String(row.part_number.trim().into());
153        if !row.description.trim().is_empty() {
154            attributes["Description"] = Value::String(row.description.trim().into());
155        }
156        let stamp = FamilySource {
157            family: family_file.to_string(),
158            part_number: row.part_number.trim().to_string(),
159            values_hash: row_hash(row),
160            history_hash: history_hash(family),
161        };
162        object.insert(
163            FAMILY_SOURCE_KEY.into(),
164            serde_json::to_value(stamp).unwrap_or(Value::Null),
165        );
166    }
167    member
168}
169
170/// One marked template input (`BREP_app/src/template.rs` `TemplateInput`).
171#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
172#[serde(rename_all = "camelCase")]
173pub struct TemplateInput {
174    pub name: String,
175    #[serde(default)]
176    pub label: String,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub min: Option<f64>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub max: Option<f64>,
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    pub choices: Vec<String>,
183}
184
185impl TemplateInput {
186    pub fn shown(&self) -> &str {
187        if self.label.trim().is_empty() {
188            &self.name
189        } else {
190            &self.label
191        }
192    }
193}
194
195/// The inputs a template marks (empty when none or unreadable).
196pub fn inputs_of(document: &Value) -> Vec<TemplateInput> {
197    document
198        .get(TEMPLATE_INPUTS_KEY)
199        .and_then(|block| serde_json::from_value(block.clone()).ok())
200        .unwrap_or_default()
201}
202
203/// The template's own value for `input`, what a form starts from.
204pub fn default_value(template: &Value, input: &TemplateInput) -> String {
205    let own = assignments(expressions_of(template))
206        .into_iter()
207        .find(|(name, _)| *name == input.name)
208        .map(|(_, rhs)| rhs);
209    if let Some(first) = input.choices.first() {
210        return own
211            .filter(|rhs| input.choices.iter().any(|choice| choice.trim() == rhs))
212            .unwrap_or_else(|| first.clone());
213    }
214    own.unwrap_or_default()
215}
216
217/// Why `text` is not an acceptable value for `input`, as far as the server
218/// can tell without an evaluator: it must be non-empty, one of the choices
219/// when there are choices, and — when it is a plain number — inside the
220/// limits. An expression (`width / 2`) passes here; the bake evaluates it.
221pub fn value_problem(input: &TemplateInput, text: &str) -> Option<String> {
222    let text = text.trim();
223    let shown = input.shown();
224    if text.is_empty() {
225        return Some(format!("{shown}: enter a value"));
226    }
227    if !input.choices.is_empty() && !input.choices.iter().any(|choice| choice.trim() == text) {
228        return Some(format!("{shown}: choose one of {}", input.choices.join(", ")));
229    }
230    if let Ok(value) = text.parse::<f64>() {
231        if !value.is_finite() {
232            return Some(format!("{shown}: {text} is not a finite number"));
233        }
234        if let Some(min) = input.min.filter(|min| value < *min) {
235            return Some(format!("{shown}: {value} is below the minimum {min}"));
236        }
237        if let Some(max) = input.max.filter(|max| value > *max) {
238            return Some(format!("{shown}: {value} is above the maximum {max}"));
239        }
240    }
241    None
242}
243
244/// The specialised copy of `template` (file `template_file`), as the CAD
245/// app's `spin_out` builds it: a normal part that keeps its expressions with
246/// `values` in place of the template's, drops the input marks, the class and
247/// any family blocks, and records its template in `templateSource`.
248///
249/// An input left out takes the template's own value. A value for a name that
250/// is not an input is refused, as is any value [`value_problem`] refuses.
251/// Returns the copy and the values it was made with.
252pub fn spin_out(
253    template: &Value,
254    template_file: &str,
255    values: &BTreeMap<String, String>,
256) -> Result<(Value, BTreeMap<String, String>), String> {
257    let inputs = inputs_of(template);
258    if let Some(stray) = values.keys().find(|name| !inputs.iter().any(|i| &i.name == *name)) {
259        return Err(format!("'{stray}' is not an input of this template"));
260    }
261    let mut used = BTreeMap::new();
262    for input in &inputs {
263        let given = values.get(&input.name).map(|v| v.trim()).unwrap_or("");
264        let text = if given.is_empty() { default_value(template, input) } else { given.to_string() };
265        if let Some(problem) = value_problem(input, &text) {
266            return Err(problem);
267        }
268        used.insert(input.name.clone(), text.trim().to_string());
269    }
270    let mut copy = template.clone();
271    let object = copy.as_object_mut().ok_or("the template is not a JSON object")?;
272    object.insert(
273        "expressions".into(),
274        Value::String(rewrite_expressions(expressions_of(template), &used)),
275    );
276    object.remove(TEMPLATE_INPUTS_KEY);
277    object.remove(DOCUMENT_CLASS_KEY);
278    object.remove(FAMILY_TABLE_KEY);
279    object.remove(FAMILY_SOURCE_KEY);
280    object.remove(DERIVED_FROM_KEY);
281    object.insert(
282        TEMPLATE_SOURCE_KEY.into(),
283        serde_json::json!({ "template": template_file, "contentHash": template_hash(template) }),
284    );
285    Ok((copy, used))
286}
287
288// ===========================================================================
289// CSV rows for a family table
290// ===========================================================================
291
292/// Rows read from a CSV (or tab-separated) paste, for a family table.
293#[derive(Debug, Clone, Default, PartialEq)]
294pub struct CsvRows {
295    /// The expression columns the header names, in order.
296    pub columns: Vec<String>,
297    /// Whether the header had a revision / description column. A column the
298    /// CSV lacks leaves that field of an existing row alone.
299    pub has_revision: bool,
300    pub has_description: bool,
301    pub rows: Vec<FamilyRow>,
302}
303
304/// Parse a family table CSV. The header names the columns: `part number`
305/// (also `part_number`, `partnumber`, `number`) is required; `revision` (or
306/// `rev`) and `description` are optional; every other header is an
307/// expression name. Tab-separated text — a paste from a spreadsheet — is read
308/// the same way. Quoted fields may hold the separator, quotes (`""`) and line
309/// breaks. Blank lines are skipped. The reader is the kernel's
310/// `text::delimited`, strict: an unclosed quote, or text after a closing
311/// quote, is refused naming its line.
312pub fn parse_csv(text: &str) -> Result<CsvRows, String> {
313    use brep_kernel::text::delimited;
314    let text = delimited::strip_bom(text);
315    let records = delimited::parse(text, delimited::sniff_separator(text), delimited::Strictness::Strict)?;
316    let mut records = records
317        .into_iter()
318        .filter(|record| !record.is_blank())
319        .map(|record| (record.line, record.fields));
320    let Some((_, header)) = records.next() else {
321        return Err("the CSV is empty — its first line names the columns".into());
322    };
323
324    enum Col {
325        Number,
326        Revision,
327        Description,
328        Value(String),
329    }
330    let mut columns = Vec::new();
331    let mut out = CsvRows::default();
332    for raw in &header {
333        let name = raw.trim();
334        let key = name.to_ascii_lowercase().replace(['_', ' '], "");
335        let col = match key.as_str() {
336            "partnumber" | "number" => Col::Number,
337            "revision" | "rev" => Col::Revision,
338            "description" => Col::Description,
339            _ if is_identifier(name) => Col::Value(name.to_string()),
340            _ => return Err(format!("column '{name}' is not an expression name (letters, digits, _ and $, not starting with a digit)")),
341        };
342        let duplicate = match &col {
343            Col::Number => columns.iter().any(|c| matches!(c, Col::Number)),
344            Col::Revision => out.has_revision,
345            Col::Description => out.has_description,
346            Col::Value(n) => out.columns.contains(n),
347        };
348        if duplicate {
349            return Err(format!("column '{name}' appears twice"));
350        }
351        match &col {
352            Col::Revision => out.has_revision = true,
353            Col::Description => out.has_description = true,
354            Col::Value(n) => out.columns.push(n.clone()),
355            Col::Number => {}
356        }
357        columns.push(col);
358    }
359    if !columns.iter().any(|c| matches!(c, Col::Number)) {
360        return Err("the CSV needs a 'part number' column".into());
361    }
362    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
363    for (line, fields) in records {
364        if fields.len() > columns.len() && fields[columns.len()..].iter().any(|f| !f.trim().is_empty()) {
365            return Err(format!("line {line} has more fields than the header has columns"));
366        }
367        let mut row = FamilyRow::default();
368        for (col, field) in columns.iter().zip(fields.iter().chain(std::iter::repeat(&String::new()))) {
369            let field = field.trim();
370            match col {
371                Col::Number => row.part_number = field.to_string(),
372                Col::Revision => row.revision = field.to_string(),
373                Col::Description => row.description = field.to_string(),
374                Col::Value(name) => {
375                    if !field.is_empty() {
376                        row.values.insert(name.clone(), field.to_string());
377                    }
378                }
379            }
380        }
381        if row.part_number.is_empty() {
382            return Err(format!("line {line} has no part number"));
383        }
384        let key = row.part_number.to_lowercase();
385        if let Some(first) = seen.get(&key) {
386            return Err(format!("line {line} repeats part number {} from line {first}", row.part_number));
387        }
388        seen.insert(key, line);
389        out.rows.push(row);
390    }
391    Ok(out)
392}
393