1use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25use serde_json::Value;
26
27pub 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
35pub const TEMPLATE_INPUTS_KEY: &str = "templateInputs";
37pub const PART_ATTRIBUTES_KEY: &str = "partAttributes";
39
40pub 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
53pub 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
63pub 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
72pub 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
94pub use brep_kernel::stable_json_hash;
103
104pub 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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct FamilySource {
121 pub family: String,
123 pub part_number: String,
124 pub values_hash: String,
125 pub history_hash: String,
126}
127
128pub 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#[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
195pub 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
203pub 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
217pub 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
244pub 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#[derive(Debug, Clone, Default, PartialEq)]
294pub struct CsvRows {
295 pub columns: Vec<String>,
297 pub has_revision: bool,
300 pub has_description: bool,
301 pub rows: Vec<FamilyRow>,
302}
303
304pub 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