main
Colby Knox 0.2.101: altium_assembly_check on engine 0.25.0 (eda-bridge-standard#30): two-pad parts by their 3D body, ball grids ap… ce3656d
//! Ready for JLCPCB assembly? The standard's shared engine answers it (vendor/adom-eda-checks `assembly`, ported from
//! this file and fixed in engine 0.25.0 for eda-bridge-standard#30): size, thickness and layers, one or two sides, the
//! smallest package by its body, the finest pin pitch with ball grids held to their own, fiducials, and which parts have
//! no LCSC number. This module reads Altium: the board model, the stack, each part's 3D body (bodyMm) and the BOM.
use serde_json::{json, Value};
use std::collections::BTreeMap;

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }

/// Each part's body size [long, short] mm in its own frame, from the bodies companion rows (bodies::rows): a turned
/// part's own rectangle (w, h), else its box on the board; a part with several bodies takes their union. Pure.
pub fn body_sizes(rows: &[Value]) -> BTreeMap<String, (f64, f64)> {
    let mut boxes: BTreeMap<String, (f64, f64, f64, f64)> = BTreeMap::new();
    let mut turned: BTreeMap<String, (f64, f64)> = BTreeMap::new();
    for b in rows {
        let Some(r) = b["ref"].as_str() else { continue };
        if let (Some(w), Some(h)) = (b["w"].as_f64(), b["h"].as_f64()) {
            let e = turned.entry(r.to_string()).or_insert((0.0, 0.0));
            *e = (e.0.max(w.max(h)), e.1.max(w.min(h)));
            continue;
        }
        let (x0, y0, x1, y1) = (f(&b["x0"]), f(&b["y0"]), f(&b["x1"]), f(&b["y1"]));
        let e = boxes.entry(r.to_string()).or_insert((x0, y0, x1, y1));
        *e = (e.0.min(x0), e.1.min(y0), e.2.max(x1), e.3.max(y1));
    }
    let mut out: BTreeMap<String, (f64, f64)> = boxes.into_iter().map(|(r, (x0, y0, x1, y1))| {
        let (w, h) = (x1 - x0, y1 - y0);
        (r, (r3(w.max(h)), r3(w.min(h))))
    }).filter(|(_, (l, s))| *l > 0.0 && *s > 0.0).collect();
    for (r, (l, s)) in turned { if l > 0.0 && s > 0.0 { out.insert(r, (r3(l), r3(s))); } }
    out
}

/// The board model with bodyMm on every component that has a 3D body. Pure.
pub fn with_bodies(st: &Value, sizes: &BTreeMap<String, (f64, f64)>) -> Value {
    let mut st = st.clone();
    if let Some(cs) = st["components"].as_array_mut() {
        for c in cs.iter_mut() {
            if let Some((l, s)) = c["ref"].as_str().and_then(|r| sizes.get(r)) { c["bodyMm"] = json!([l, s]); }
        }
    }
    st
}

/// The LCSC numbers on the BOM's purchased lines, once each. Pure.
pub fn lcsc_numbers(lines: &[Value]) -> Vec<String> {
    let mut v: Vec<String> = lines.iter().filter(|l| l["purchase"] != json!(false))
        .filter_map(|l| l["lcsc"].as_str().map(|s| s.trim().to_string())).filter(|s| !s.is_empty()).collect();
    v.sort();
    v.dedup();
    v
}

/// The engine names the standard's verbs; this bridge's panel verb has no underscore for prefix_verbs to catch.
fn altium_words(r: &mut Value) {
    match r {
        Value::String(s) => { if s.contains("(panelize") { *s = s.replace("(panelize", "(altium_panelize"); } }
        Value::Array(a) => a.iter_mut().for_each(altium_words),
        Value::Object(o) => o.values_mut().for_each(altium_words),
        _ => {}
    }
}

/// altium_assembly_check {filePath?, projectPath?, panelMm?}
pub fn assembly_check(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let mut eargs = json!({});
    if let Some(p) = args.get("panelMm").filter(|v| v.is_array()) { eargs["panelMm"] = p.clone(); }
    let mut bom_error = Value::Null;
    if let Some(prj) = crate::support::s(args, "projectPath") {
        let b = crate::bom::bom(&json!({"projectPath": prj, "write": false}));
        if b.get("success").and_then(|v| v.as_bool()) == Some(true) {
            eargs["lcscMissing"] = b["checks"]["jlcpcb"]["linesWithoutLcsc"].clone();
            if !eargs["lcscMissing"].is_array() { eargs["lcscMissing"] = json!([]); }
            eargs["lcscNumbers"] = json!(lcsc_numbers(&b["lines"].as_array().cloned().unwrap_or_default()));
        } else { bom_error = b.get("error").cloned().unwrap_or(json!("the BOM could not be read")); }
    }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    // each part's body sizes the two-pad parts (#30); with no bodies read, the engine sizes them by their copper
    let bodies = crate::agent::call("bodies", &[], None, std::time::Duration::from_secs(120));
    let sizes = bodies.get("data").filter(|d| d["ok"] == json!(true))
        .map(|d| body_sizes(&crate::bodies::rows(&d["bodies"].as_array().cloned().unwrap_or_default()))).unwrap_or_default();
    let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    let mut r = crate::checks::engine("assembly_check", &json!({"board": with_bodies(&st, &sizes), "stack": stack, "args": eargs}));
    altium_words(&mut r);
    if r["success"] == json!(true) {
        if !bom_error.is_null() { r["linesWithoutLcsc"] = json!({"bomError": bom_error}); }
        if let Some(h) = r["_hint"].as_str() {
            r["_hint"] = json!(format!("{h} Pass projectPath to check LCSC numbers and list them for the PCBA Type look-up; bodyMm comes from each part's 3D body (altium_add_body for a part without one). altium_bom writes the JLCPCB BOM, altium_export_manufacturing the pick-and-place."));
        }
    }
    r
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn body_sizes_take_the_union_and_a_turned_parts_own_rectangle() {
        let rows = vec![
            json!({"ref": "D1", "x0": 0.0, "y0": 0.0, "x1": 0.6, "y1": 1.0}),
            json!({"ref": "U1", "x0": 0.0, "y0": 0.0, "x1": 3.0, "y1": 3.0}), json!({"ref": "U1", "x0": 2.0, "y0": 0.0, "x1": 5.0, "y1": 1.0}),
            json!({"ref": "C2", "x0": 0.0, "y0": 0.0, "x1": 2.0, "y1": 2.0, "w": 1.0, "h": 0.5, "rotation": 45.0}),
        ];
        let s = body_sizes(&rows);
        assert_eq!(s["D1"], (1.0, 0.6));
        assert_eq!(s["U1"], (5.0, 3.0));
        assert_eq!(s["C2"], (1.0, 0.5));
    }

    #[test]
    fn an_x1son_with_its_body_passes_economic() {
        // a 1.0 x 0.6 mm X1SON-2: pad centres 0.65 mm apart failed Economic as smaller than 0402 before engine 0.25.0
        let st = json!({"outline": [[0.0, 0.0], [30.0, 0.0], [30.0, 30.0], [0.0, 30.0]],
            "components": [{"ref": "D1", "side": "top", "pattern": "X1SON-2"}],
            "pads": [{"ref": "D1", "name": "1", "x": 10.0, "y": 10.0, "sizeX": 0.3, "sizeY": 0.5, "rotation": 0.0, "drill": 0.0, "net": "A", "shape": "rect"},
                     {"ref": "D1", "name": "2", "x": 10.65, "y": 10.0, "sizeX": 0.3, "sizeY": 0.5, "rotation": 0.0, "drill": 0.0, "net": "K", "shape": "rect"}]});
        let sizes: BTreeMap<String, (f64, f64)> = [("D1".to_string(), (1.0, 0.6))].into_iter().collect();
        let r = adom_eda_checks::run("assembly_check", &json!({"board": with_bodies(&st, &sizes), "stack": {"totalUm": 1600.0, "copperLayers": 2}, "args": {"lcscMissing": 0}}));
        let rule = r["economic"]["rules"].as_array().unwrap().iter().find(|x| x["rule"] == "smallest package 0402").cloned().unwrap();
        assert_eq!(rule["ok"], json!(true), "{r}");
        assert_eq!(r["board"]["smallestChip"]["sizeFrom"], "body");
    }

    #[test]
    fn lcsc_numbers_are_the_purchased_lines_once_each() {
        let lines = vec![json!({"lcsc": "C2", "purchase": true}), json!({"lcsc": "C1"}), json!({"lcsc": "C2"}), json!({"lcsc": "C9", "purchase": false}), json!({"lcsc": ""})];
        assert_eq!(lcsc_numbers(&lines), vec!["C1", "C2"]);
    }
}