Typed schemas for Bill of Materials (#11075) (#11076)

* claim: #11075

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bill of Materials: input and output schemas (#11075)

assembly.bom gets a typed contract and reply types in schema/bom.rs and
leaves unconverted.txt. Each key reads as the handler reads it, with its
message; the reply is built from Bom, BomRow and BomChild, in the old
field order, so the reply and the files it writes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
austin62jake
2026-11-02 18:38:30 +00:00
committed by GitHub
parent 9432cdfee8
commit 0f8b971ef0
5 changed files with 326 additions and 26 deletions
+54 -25
View File
@@ -19,8 +19,12 @@ use solidcraft_doc::metadata::{BOM_KEYS, BOM_TYPE, MAX_KEYS, Owner, check_text,
use super::CommandSpec;
use crate::params::{bad, str_};
use crate::schema::bom::{Bom, BomChild, BomParams, BomRow};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BOM_CONTRACT: TypedContract<BomParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("component.metadata", "Part Properties", read).icon("settings").noundo().doc_only().params(
"component: id or name (0 or \"root\": the design's own properties) → component, name, part_number, description, revision, \
@@ -33,8 +37,14 @@ pub static COMMANDS: &[CommandSpec] = &[
properties?: {name: text, …} (free properties; empty or null removes). All or nothing, one undo step → component, \
metadata, properties, changed: [keys]",
),
CommandSpec::new("assembly.bom", "Bill of Materials", bom).at("SOLID", "INSPECT").icon("bom").noundo().params(
"component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \
CommandSpec::new("assembly.bom", "Bill of Materials", crate::checked!("assembly.bom", bom))
.at("SOLID", "INSPECT")
.icon("bom")
.noundo()
.contract(&BOM_CONTRACT)
.output(output_schema_for::<Bom>)
.params(
"component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \
subassemblies) | top (the component's direct children, subassemblies as one row each); group_by?: [\"part_number\"] \
(default; components without a part number get a row per definition) | [\"definition\"]; group_children?: true (a component \
with a part number is one row, the parts placed inside it listed under it as children: [{item, part_number, description, \
@@ -43,7 +53,7 @@ pub static COMMANDS: &[CommandSpec] = &[
counts here), reference counts nowhere, purchased and inseparable are one row (in flat, an inseparable one's purchased \
parts are listed too, under it with group_children and a part number) → rows: [{item, part_number, description, revision, \
bom_type, count, definition, components, properties, children?}] sorted by part number, total_occurrences (children included)",
),
),
];
/// Longest free property name, in bytes.
@@ -434,36 +444,56 @@ fn bom(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let mut total: u64 = 0;
let rows: Vec<Value> = rows(s, &ix, &counts, o.group, &kits)
let rows: Vec<BomRow> = rows(s, &ix, &counts, o.group, &kits)
.into_iter()
.enumerate()
.map(|(i, r)| {
total += r.count;
let mut v = json!({"item": i + 1, "part_number": r.part_number, "description": r.description, "revision": r.revision,
"bom_type": r.bom_type.as_str(), "count": r.count, "definition": r.names.join("; "), "components": r.components,
"properties": r.properties});
if !r.kit.is_empty() {
let children: Vec<Value> = self::rows(s, &ix, &r.kit, Group::PartNumber, &BTreeMap::new())
let children = (!r.kit.is_empty()).then(|| {
self::rows(s, &ix, &r.kit, Group::PartNumber, &BTreeMap::new())
.into_iter()
.enumerate()
.map(|(j, c)| {
let count = c.count.saturating_mul(r.count);
total += count;
json!({"item": format!("{}.{}", i + 1, j + 1), "part_number": c.part_number, "description": c.description,
"revision": c.revision, "bom_type": c.bom_type.as_str(), "each": c.count, "count": count,
"definition": c.names.join("; ")})
BomChild {
item: format!("{}.{}", i + 1, j + 1),
part_number: c.part_number,
description: c.description,
revision: c.revision,
bom_type: c.bom_type.as_str().to_string(),
each: c.count,
count,
definition: c.names.join("; "),
}
})
.collect();
v["children"] = Value::Array(children);
.collect()
});
BomRow {
item: i + 1,
part_number: r.part_number,
description: r.description,
revision: r.revision,
bom_type: r.bom_type.as_str().to_string(),
count: r.count,
definition: r.names.join("; "),
components: r.components,
properties: r.properties,
children,
}
v
})
.collect();
let mut out = Map::new();
out.insert("component".into(), json!(root));
out.insert("levels".into(), json!(if o.levels == Levels::Top { "top" } else { "flat" }));
out.insert("group_by".into(), json!([if o.group == Group::Definition { "definition" } else { "part_number" }]));
out.insert("group_children".into(), json!(o.fold));
let mut out = Bom {
component: root,
levels: if o.levels == Levels::Top { "top" } else { "flat" }.to_string(),
group_by: vec![if o.group == Group::Definition { "definition" } else { "part_number" }.to_string()],
group_children: o.fold,
path: None,
format: None,
rows,
total_occurrences: total,
param_warnings: Vec::new(),
};
if let Some(path) = str_(p, "path") {
let format = match str_(p, "format").map(str::to_ascii_lowercase) {
Some(f) => f,
@@ -471,18 +501,17 @@ fn bom(s: &mut Session, p: &Value) -> Result<Value> {
None if path.to_ascii_lowercase().ends_with(".csv") => "csv".into(),
None => return Err(bad(cmd, "`path` must end in .csv or .json, or give `format`")),
};
let rows = out.rows.iter().map(|r| serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))).collect::<Result<Vec<Value>>>()?;
let text = match format.as_str() {
"csv" => csv(&rows),
"json" => serde_json::to_string_pretty(&json!({"rows": rows, "total_occurrences": total})).map_err(|e| bad(cmd, e.to_string()))?,
other => return Err(bad(cmd, format!("unknown format `{other}` (csv or json)"))),
};
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
out.insert("path".into(), json!(path));
out.insert("format".into(), json!(format));
out.path = Some(path.to_string());
out.format = Some(format);
}
out.insert("rows".into(), Value::Array(rows));
out.insert("total_occurrences".into(), json!(total));
Ok(Value::Object(out))
serde_json::to_value(out).map_err(|e| bad(cmd, e.to_string()))
}
#[cfg(test)]
+185
View File
@@ -0,0 +1,185 @@
//! Contract and result types for `assembly.bom` in `cmd/bom.rs` (#11075).
use std::borrow::Cow;
use std::collections::BTreeMap;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use super::check::whole;
/// The bill of materials below a component: its parts, counted through subassemblies, by part
/// number. Each component's bom type counts: a phantom has no row (what it holds counts where it
/// is placed), a reference counts nowhere, and a purchased or inseparable component is one row.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct BomParams {
/// The component, by id or name (default: the design).
#[serde(default, deserialize_with = "component")]
#[schemars(schema_with = "component_schema")]
pub component: Option<String>,
/// `flat` (the default): every part at any depth, counted through its subassemblies; `top`:
/// the component's direct children, subassemblies as one row each.
#[serde(default, deserialize_with = "levels")]
#[schemars(schema_with = "levels_schema")]
pub levels: Option<String>,
#[serde(default)]
pub group_by: Option<BomGroupBy>,
/// A component with a part number is one row, the parts placed inside it listed under it as
/// `children` rather than as rows of their own (default false).
#[serde(default, deserialize_with = "group_children")]
pub group_children: Option<bool>,
/// Also write the bill of materials to this `.csv` or `.json` file (children as items 1.1,
/// 1.2…).
#[serde(default)]
pub path: Option<String>,
/// With `path`: `csv` or `json`, in any case (default: from the path's extension).
#[serde(default)]
pub format: Option<String>,
}
/// A component's id or name, as the handler reads it, with its message; `null` is none.
fn component<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
match Value::deserialize(d)? {
Value::Null => Ok(None),
Value::Number(n) => Ok(Some(n.to_string())),
Value::String(s) => Ok(Some(s)),
_ => Err(D::Error::custom(whole("`component` must be a component id or name"))),
}
}
fn component_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": ["number", "string", "null"]})
}
/// `flat` or `top`, with the handler's message; `null` is `flat`.
fn levels<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
match Value::deserialize(d)? {
Value::Null => Ok(None),
Value::String(l) if l == "flat" || l == "top" => Ok(Some(l)),
_ => Err(D::Error::custom(whole("`levels` is flat or top"))),
}
}
fn levels_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"enum": ["flat", "top", null]})
}
/// `true` or `false`, with the handler's message; `null` is `false`.
fn group_children<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
match Value::deserialize(d)? {
Value::Null => Ok(None),
Value::Bool(b) => Ok(Some(b)),
_ => Err(D::Error::custom(whole("`group_children` is true or false"))),
}
}
/// What makes two components one row: `part_number` (the default; components without a part
/// number get a row per definition) or `definition`, as a word or a one-item list, with the
/// handler's messages.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BomGroupBy(pub String);
impl<'de> Deserialize<'de> for BomGroupBy {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let key = |g: String| match g.as_str() {
"part_number" | "definition" => Ok(BomGroupBy(g)),
o => Err(D::Error::custom(whole(format!("can't group by `{o}` (part_number or definition)")))),
};
let shape = || D::Error::custom(whole("`group_by` is [\"part_number\"] or [\"definition\"]"));
match Value::deserialize(d)? {
Value::String(g) => key(g),
Value::Array(a) => match <[Value; 1]>::try_from(a) {
Ok([Value::String(g)]) => key(g),
_ => Err(shape()),
},
_ => Err(shape()),
}
}
}
impl JsonSchema for BomGroupBy {
fn schema_name() -> Cow<'static, str> {
"BomGroupBy".into()
}
fn inline_schema() -> bool {
true
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
let key = serde_json::json!({"enum": ["part_number", "definition"]});
json_schema!({
"description": "What makes two components one row: part_number (the default; components without a part number get a row per definition) or definition, as a word or a one-item list.",
"anyOf": [key, {"type": "array", "items": key, "minItems": 1, "maxItems": 1}]
})
}
}
/// What `assembly.bom` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct Bom {
/// The component listed, by id (0: the design).
pub component: u64,
/// `flat` or `top`.
pub levels: String,
/// `["part_number"]` or `["definition"]`.
pub group_by: Vec<String>,
pub group_children: bool,
/// With `path`: the file written.
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
/// With `path`: `csv` or `json`.
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// The rows, by part number; rows without one after them, by name.
pub rows: Vec<BomRow>,
/// How many occurrences the rows count, children included.
pub total_occurrences: u64,
/// In the warn parameter-check mode: what the call's parameters got wrong.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub param_warnings: Vec<String>,
}
/// One row of a bill of materials.
#[derive(Debug, Serialize, JsonSchema)]
pub struct BomRow {
/// Its number, from 1.
pub item: usize,
pub part_number: String,
pub description: String,
pub revision: String,
/// `normal`, `purchased` or `inseparable`.
pub bom_type: String,
/// How many are placed.
pub count: u64,
/// The components' names, `; ` between them.
pub definition: String,
/// The components' ids.
pub components: Vec<u64>,
/// Their free properties, by name.
pub properties: BTreeMap<String, String>,
/// With `group_children`: the parts placed inside it.
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<BomChild>>,
}
/// A part placed inside a row's component, with `group_children`.
#[derive(Debug, Serialize, JsonSchema)]
pub struct BomChild {
/// Its number under its row, such as `2.1`.
pub item: String,
pub part_number: String,
pub description: String,
pub revision: String,
pub bom_type: String,
/// How many are in one of the row's component.
pub each: u64,
/// How many in all.
pub count: u64,
pub definition: String,
}
#[cfg(test)]
#[path = "bom_tests.rs"]
mod tests;
+86
View File
@@ -0,0 +1,86 @@
use serde_json::{Value, json};
use super::{Bom, BomParams};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
/// As in the command's own tests: a plate placed three times, and a hinge subassembly placed
/// twice that holds one pin. Here the hinge has a part number too, so it can keep its pin.
fn assembly(s: &mut Session) {
run(s, "component.create", json!({"name": "Plate"}));
run(s, "solid.box", json!({"length": 40, "width": 20, "height": 3}));
run(s, "component.activate", json!({"component": 0}));
run(s, "component.create", json!({"name": "Hinge", "activate": false}));
run(s, "component.create", json!({"name": "Pin", "parent": "Hinge"}));
run(s, "solid.cylinder", json!({"diameter": 4, "height": 30}));
run(s, "component.activate", json!({"component": 0}));
for x in [50, 100] {
run(s, "occurrence.copy", json!({"component": "Plate", "translate": [x, 0, 0]}));
}
run(s, "occurrence.copy", json!({"component": "Hinge", "translate": [0, 50, 0]}));
run(s, "component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "description": "Plate, 3 mm", "revision": "B"}));
run(s, "component.metadata.set", json!({"component": "Pin", "part_number": "PN-040", "properties": {"finish": "zinc"}}));
run(s, "component.metadata.set", json!({"component": "Hinge", "part_number": "HG-1"}));
}
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<BomParams>(), &["component", "format", "group_by", "group_children", "levels", "path"]);
}
#[test]
fn strict_keeps_todays_errors() {
let file = std::env::temp_dir().join(format!("solidcraft-bom-schema-{}.csv", std::process::id()));
let file = file.to_string_lossy();
assert_strict_keeps_todays_errors(&[
("assembly.bom", json!({"component": true})),
("assembly.bom", json!({"component": "Nope"})),
("assembly.bom", json!({"levels": "deep"})),
("assembly.bom", json!({"levels": 1})),
("assembly.bom", json!({"group_by": "size"})),
("assembly.bom", json!({"group_by": ["size"]})),
("assembly.bom", json!({"group_by": ["part_number", "definition"]})),
("assembly.bom", json!({"group_by": [5]})),
("assembly.bom", json!({"group_by": 5})),
("assembly.bom", json!({"group_children": "yes"})),
("assembly.bom", json!({"path": file.replace(".csv", ".txt")})),
("assembly.bom", json!({"path": file, "format": "xml"})),
]);
}
/// #11075: a bill of materials replies as its output schema says, in Warn without warnings for
/// good calls and with them for a misspelt key: flat and top, grouped by definition, with the
/// hinge keeping its pin as children, and written to a JSON and a CSV file.
#[test]
fn a_bill_of_materials_replies_with_its_schema() {
let schema = output_schema_for::<Bom>();
let matches = |r: &Value, warned: bool| {
let schema = schema.as_value();
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
};
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
assembly(&mut s);
let r = run(&mut s, "assembly.bom", json!({}));
matches(&r, false);
assert!(r.get("path").is_none() && r["rows"].as_array().is_some_and(|rows| rows.iter().all(|row| row.get("children").is_none())), "{r}");
matches(&run(&mut s, "assembly.bom", json!({"component": 0, "levels": "top", "group_by": "definition"})), false);
let r = run(&mut s, "assembly.bom", json!({"levels": "flat", "group_by": ["part_number"], "group_children": true}));
matches(&r, false);
let hinge = r["rows"].as_array().and_then(|rows| rows.iter().find(|row| row["part_number"] == "HG-1")).cloned().unwrap_or_default();
assert_eq!((hinge["children"][0]["part_number"].as_str(), hinge["children"][0]["item"].is_string()), (Some("PN-040"), true), "{r}");
let dir = std::env::temp_dir();
for (name, format) in [("json", Value::Null), ("csv", json!("CSV"))] {
let path = dir.join(format!("solidcraft-bom-schema-{}.{name}", std::process::id())).to_string_lossy().into_owned();
let r = run(&mut s, "assembly.bom", json!({"path": path, "format": format}));
matches(&r, false);
assert_eq!(r["format"], name, "{r}");
let _ = std::fs::remove_file(&path);
}
matches(&run(&mut s, "assembly.bom", json!({"level": "top"})), true);
}
+1
View File
@@ -54,6 +54,7 @@ mod coverage_tests;
mod tests;
// The contracts, by command file.
pub mod bom;
pub mod component;
pub mod construct;
pub mod edit;
-1
View File
@@ -5,7 +5,6 @@
appearance.assign
appearance.library
appearance.list
assembly.bom
body.rename
browser.collapse_all
browser.expand_all