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 board against both of JLCPCB's PCBA tiers as published
//! (jlcpcb.com/capabilities/pcb-assembly-capabilities, read 2026-10-26): size, thickness and layers, one or two sides,
//! the smallest package and the finest pin pitch, fiducials, and which parts have no LCSC number. It answers the tier
//! the board can be ordered in. From the Altium bridge's assembly.rs, with kicad-bridge 1.0.109 and 1.0.111's fixes (#30):
//! a two-pad part sized by its body, ball grids held to their own pitch, a FET's joined lands no pitch, and the
//! per-part PCBA Type named.
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 }

/// One SMD pin of a part: centre, a round land (a ball), its net, and its copper (sizeX, sizeY, rotation in degrees).
struct Pin { x: f64, y: f64, round: bool, net: String, sx: f64, sy: f64, rot: f64 }

/// Half the copper of a pin along direction `phi` (radians), its land taken as a rectangle.
fn half_along(p: &Pin, phi: f64) -> f64 {
    let a = p.rot.to_radians() - phi;
    (p.sx / 2.0 * a.cos()).abs() + (p.sy / 2.0 * a.sin()).abs()
}

/// A two-pad part's copper, end to end along its pins and across: [long, short] mm. None without pad sizes.
fn copper(ps: &[Pin]) -> Option<(f64, f64)> {
    if ps.len() != 2 || ps.iter().any(|p| p.sx <= 0.0 || p.sy <= 0.0) { return None; }
    let (dx, dy) = (ps[1].x - ps[0].x, ps[1].y - ps[0].y);
    let phi = dy.atan2(dx);
    let long = (dx * dx + dy * dy).sqrt() + half_along(&ps[0], phi) + half_along(&ps[1], phi);
    let short = ps.iter().map(|p| 2.0 * half_along(p, phi + std::f64::consts::FRAC_PI_2)).fold(0.0, f64::max);
    Some((long.max(short), long.min(short)))
}

/// What the board offers the assembly line, from the board model. Pure.
pub fn facts(st: &Value) -> Value {
    let pads = st["pads"].as_array().cloned().unwrap_or_default();
    let comps = st["components"].as_array().cloned().unwrap_or_default();
    let comp = |r: &str| comps.iter().find(|c| c["ref"].as_str() == Some(r));
    let pattern = |r: &str| comp(r).map(|c| c["pattern"].as_str().unwrap_or("").to_ascii_uppercase()).unwrap_or_default();
    // a part's pins: an unnamed pad is copper drawn beside a pin (a power FET's land), never a pin of its own (#30)
    let mut by: BTreeMap<String, Vec<Pin>> = BTreeMap::new();
    for p in pads.iter().filter(|p| f(&p["drill"]) == 0.0 && p["name"].as_str() != Some("")) {
        if let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) {
            let (sx, sy) = (f(&p["sizeX"]), f(&p["sizeY"]));
            let round = p["shape"] == "circle" || (p["shape"] == "round" && sx > 0.0 && (sx - sy).abs() < 1e-6);
            by.entry(r.to_string()).or_default().push(Pin { x: f(&p["x"]), y: f(&p["y"]), round, net: p["net"].as_str().unwrap_or("").to_string(), sx, sy, rot: f(&p["rotation"]) });
        }
    }
    // a ball grid: named so (BGA, DSBGA, WLCSP, CSP), or four or more round lands in two or more rows and columns (#30)
    let is_bga = |r: &str, ps: &[Pin]| {
        let lines = |k: fn(&Pin) -> f64| { let mut v: Vec<i64> = ps.iter().map(|q| (k(q) * 100.0).round() as i64).collect(); v.sort(); v.dedup(); v.len() };
        ["BGA", "CSP"].iter().any(|x| pattern(r).contains(x)) || (ps.len() >= 4 && ps.iter().all(|q| q.round) && lines(|q| q.x) >= 2 && lines(|q| q.y) >= 2)
    };
    // the finest pitch: the closest pin centres within one part with 3 or more SMD pins, ball grids apart;
    // the smallest two-pad part: by its body (bodyMm, the bridge's package outline), else its copper, else its pad centres
    let mut pitch: Option<(f64, String)> = None;
    let mut bga: Option<(f64, String)> = None;
    let mut chip: Option<(f64, String, Option<(f64, f64, &str)>)> = None;
    for (r, ps) in &by {
        let mut d = f64::MAX;
        for i in 0..ps.len() {
            for j in i + 1..ps.len() {
                // pins with one centre are one land drawn in pieces (fusion-lane #24); pins on one net (a FET's source
                // pins drawn as overlapping lands) cannot bridge (#30): neither is a pitch
                let e = ((ps[i].x - ps[j].x).powi(2) + (ps[i].y - ps[j].y).powi(2)).sqrt();
                if e > 0.01 && (ps[i].net.is_empty() || ps[i].net != ps[j].net) { d = d.min(e); }
            }
        }
        if d == f64::MAX { continue; }
        if ps.len() >= 3 {
            let slot = if is_bga(r, ps) { &mut bga } else { &mut pitch };
            if slot.as_ref().map(|p| d < p.0).unwrap_or(true) { *slot = Some((d, r.clone())); }
        }
        if ps.len() == 2 {
            let body = comp(r).and_then(|c| Some((c["bodyMm"][0].as_f64()?, c["bodyMm"][1].as_f64()?))).filter(|b| b.0 > 0.0 && b.1 > 0.0);
            let sz = body.map(|(a, b)| (a.max(b), a.min(b), "body")).or_else(|| copper(ps).map(|(l, s)| (l, s, "copper")));
            // smaller: the shorter long side, else the closer pad centres
            let key = |c: &(f64, String, Option<(f64, f64, &str)>)| (c.2.map(|z| z.0).unwrap_or(f64::MAX), c.0);
            let cand = (d, r.clone(), sz);
            if chip.as_ref().map(|c| key(&cand) < key(c)).unwrap_or(true) { chip = Some(cand); }
        }
    }
    let named = |c: &Value, pat: &[&str]| { let p = c["pattern"].as_str().unwrap_or("").to_ascii_uppercase(); pat.iter().any(|x| p.contains(x)) };
    let tiny: Vec<Value> = comps.iter().filter(|c| named(c, &["0201", "01005", "0603M", "0402M"])).map(|c| json!({"ref": c["ref"], "footprint": c["pattern"]})).collect();
    let fid = |s: &str| s.to_ascii_uppercase().starts_with("FID");
    let fiducials = comps.iter().filter(|c| c["ref"].as_str().map(fid).unwrap_or(false) || named(c, &["FIDUCIAL"])).count()
        + pads.iter().filter(|p| p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true) && p["name"].as_str().map(fid).unwrap_or(false)).count();
    // a part is a component with pads: a logo or an icon has none and is never placed (fusion-lane #24)
    let placed = |c: &Value| pads.iter().any(|p| p["ref"] == c["ref"]);
    let bottom: Vec<Value> = comps.iter().filter(|c| c["side"] == "bottom" && placed(c)).map(|c| c["ref"].clone()).collect();
    let tht = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| !r.is_empty()).unwrap_or(false))
        .filter_map(|p| p["ref"].as_str().map(String::from)).collect::<std::collections::BTreeSet<_>>();
    json!({"parts": comps.iter().filter(|c| placed(c)).count(), "bottomSideParts": bottom, "finestPitch": pitch.map(|(d, r)| json!({"mm": r3(d), "ref": r})),
           "finestBgaPitch": bga.map(|(d, r)| json!({"mm": r3(d), "ref": r})),
           "smallestChip": chip.map(|(d, r, sz)| json!({"padCentresMm": r3(d), "ref": r, "sizeMm": sz.map(|z| json!([r3(z.0), r3(z.1)])), "sizeFrom": sz.map(|z| z.2)})),
           "tinyFootprints": tiny, "fiducials": fiducials, "throughHoleParts": tht.into_iter().collect::<Vec<_>>()})
}

fn rule(name: &str, ok: Option<bool>, detail: String) -> Value { json!({"rule": name, "ok": ok, "detail": detail}) }

/// The board against one tier ("economic" or "standard"). `size` is [w, h] mm (the board, or the panel it ships in),
/// `lcsc_missing` the purchased lines with no LCSC number (None: not checked). `fa.lcscNumbers`, when the bridge passed
/// them, are listed for the per-part PCBA Type look-up. Pure.
pub fn tier(name: &str, fa: &Value, size: (f64, f64), thick: Option<f64>, layers: Option<i64>, lcsc_missing: Option<usize>, panel: bool) -> Value {
    let eco = name == "economic";
    let mut rs = Vec::new();
    let (w, h) = (size.0.min(size.1), size.0.max(size.1));
    let (lo, hi): ((f64, f64), (f64, f64)) = match (eco, panel) { (true, false) => ((10.0, 10.0), (470.0, 500.0)), (true, true) => ((10.0, 10.0), (250.0, 250.0)), (false, false) => ((70.0, 70.0), (460.0, 500.0)), (false, true) => ((70.0, 70.0), (250.0, 250.0)) };
    let ok = w >= lo.0 && h >= lo.1 && w <= hi.0.min(hi.1) && h <= hi.0.max(hi.1);
    rs.push(rule(&format!("{} {} x {} to {} x {} mm", if panel { "panel" } else { "board" }, lo.0, lo.1, hi.0, hi.1), Some(ok), format!("{} x {} mm{}", r3(size.0), r3(size.1), if !ok && !eco && !panel { ": a panel (panelize) can bring it to 70 x 70" } else { "" })));
    if eco {
        // a stack-up adds up to a little over or under JLCPCB's 1.6 mm option (KiCad's default 4 layers: 1.6166 mm), #30
        rs.push(match thick { Some(t) => rule("board 0.8 to 1.6 mm thick", Some((0.8 - 0.05..=1.6 + 0.05).contains(&t)),
            format!("{} mm{}", r3(t), if (t - 1.6).abs() > 1e-6 && (t - 1.6).abs() <= 0.05 { " (JLCPCB's 1.6 mm option, within 0.05 mm)" } else { "" })),
            None => rule("board 0.8 to 1.6 mm thick", None, "thickness not read: pass the stack".into()) });
        rs.push(match layers { Some(n) => rule("2, 4 or 6 layers", Some([2, 4, 6].contains(&n)), format!("{n} layers")), None => rule("2, 4 or 6 layers", None, "layers not read: pass the stack".into()) });
        let bot = fa["bottomSideParts"].as_array().map(|a| a.len()).unwrap_or(0);
        rs.push(rule("parts on one side only", Some(bot == 0), if bot == 0 { "all on top".into() } else { format!("{bot} part(s) on the bottom: {}", fa["bottomSideParts"]) }));
    }
    let (chip_min, pitch_min, bga_min) = if eco { (0.8, 0.4, 0.5) } else { (0.3, 0.35, 0.3) };
    let tiny = fa["tinyFootprints"].as_array().map(|a| a.len()).unwrap_or(0);
    let sc = &fa["smallestChip"];
    let centres = sc["padCentresMm"].as_f64();
    let sz = sc["sizeMm"][0].as_f64().zip(sc["sizeMm"][1].as_f64());
    let from = sc["sizeFrom"].as_str().unwrap_or("");
    // the package by its body: 0402 is 1.0 x 0.5 mm, 01005 0.4 x 0.2, a tenth under allowed; with no body, its copper:
    // 0402 lands are about 1.5 mm end to end, 0201 about 1.1, 01005 about 0.65, so between is an estimate (#30)
    let (body, pkg) = if eco { ((1.0, 0.5), "0402 is 1.0 x 0.5 mm") } else { ((0.4, 0.2), "01005 is 0.4 x 0.2 mm") };
    let size_ok = match sz {
        Some((l, s)) if from == "body" => Some(l >= 0.9 * body.0 && s >= 0.9 * body.1),
        Some((l, _)) if eco => if l >= 1.3 { Some(true) } else if l < 0.95 { Some(false) } else { None },
        Some((l, _)) => if l >= 0.55 { Some(true) } else { None },
        None => centres.map(|c| c >= chip_min),
    };
    let chip_ok = if eco && tiny > 0 { Some(false) } else { size_ok.or(if sc.is_null() { Some(true) } else { None }) };
    let how = match sz {
        Some((l, s)) if from == "body" => format!("body {} x {} mm", r3(l), r3(s)),
        Some((l, s)) => format!("{} x {} mm of copper, no body size: an estimate, check the part's body ({pkg})", r3(l), r3(s)),
        None => "sized by its pad centres only".to_string(),
    };
    rs.push(rule(if eco { "smallest package 0402" } else { "smallest package 01005" }, chip_ok,
        if sc.is_null() { "no two-pad SMD part".into() } else {
            format!("smallest two-pad part {}: {how} (pad centres {} mm){}", sc["ref"].as_str().unwrap_or("-"), centres.map(r3).unwrap_or(0.0),
                if tiny > 0 { format!("; footprints named under 0402: {}", fa["tinyFootprints"]) } else { String::new() })
        }));
    let pitch = fa["finestPitch"]["mm"].as_f64();
    let bga = fa["finestBgaPitch"]["mm"].as_f64();
    let pitch_ok = pitch.map(|p| p + 1e-6 >= pitch_min).unwrap_or(true) && bga.map(|p| p + 1e-6 >= bga_min).unwrap_or(true);
    let mut detail = format!("finest {} mm on {}", pitch.map(r3).unwrap_or(0.0), fa["finestPitch"]["ref"].as_str().unwrap_or("-"));
    if let Some(b) = bga {
        detail += &format!("; ball grid {} mm on {}{}", r3(b), fa["finestBgaPitch"]["ref"].as_str().unwrap_or("-"), if b + 1e-6 < bga_min { format!(" (needs {bga_min} mm)") } else { String::new() });
    }
    rs.push(rule(&format!("IC pin pitch {pitch_min} mm or more (BGA {bga_min} mm)"), Some(pitch_ok), detail));
    if eco {
        // JLCPCB rates each part too: "PCBA Type: Standard Only" parts cannot go Economic, and no board file says which (#30)
        let nums: Vec<&str> = fa["lcscNumbers"].as_array().into_iter().flatten().filter_map(|v| v.as_str()).collect();
        rs.push(rule("every part offered in Economic (JLCPCB's PCBA Type)", None, format!("not checked: JLCPCB marks some parts Standard Only (fine-pitch BGAs, some LEDs and connectors); read PCBA Type on each part's page, jlcpcb.com/partdetail/<number>{}",
            if nums.is_empty() { String::new() } else { format!(": {}", nums.join(", ")) })));
    }
    if !eco {
        let n = fa["fiducials"].as_u64().unwrap_or(0);
        rs.push(rule("fiducials and edge rails", Some(n >= 2 || panel), if panel { "on the panel rails (panelize adds three)".into() } else { format!("{n} fiducial(s) on the board: add 3 (board_features fiducials) or ship it in a panel with rails") }));
    }
    rs.push(match lcsc_missing { Some(0) => rule("every purchased part has an LCSC number", Some(true), "all lines".into()),
        Some(n) => rule("every purchased part has an LCSC number", Some(false), format!("{n} line(s) without one: find them (adom-parts-search, adom-jlcpcb) or consign them")),
        None => rule("every purchased part has an LCSC number", None, "not checked: pass lcscMissing from the bridge's bom".into()) });
    let ok = rs.iter().all(|r| r["ok"] != json!(false));
    json!({"tier": name, "ok": ok, "rules": rs})
}

/// assembly_check: input {board, stack?, args: {panelMm?: [w, h], lcscMissing?: count or the BOM lines without one, lcscNumbers?: the BOM's LCSC numbers}}.
pub fn assembly_check(input: &Value) -> Value {
    let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };
    let args = &input["args"];
    let Some((x0, y0, x1, y1)) = crate::geom::outline_bbox(&st) else { return crate::input::refuse("no_outline", "the board has no outline") };
    let panel = args["panelMm"].as_array().filter(|a| a.len() == 2).map(|a| (f(&a[0]), f(&a[1])));
    let size = panel.unwrap_or((x1 - x0, y1 - y0));
    let stack = crate::input::stack(input);
    let thick = stack.as_ref().and_then(|s| s["totalUm"].as_f64()).map(|u| u / 1000.0);
    let layers = stack.as_ref().and_then(|s| s["copperLayers"].as_i64());
    let (lcsc_missing, lcsc_lines) = match &args["lcscMissing"] {
        Value::Array(a) => (Some(a.len()), Value::Array(a.clone())),
        v if v.as_u64().is_some() => (v.as_u64().map(|n| n as usize), Value::Null),
        _ => (None, Value::Null),
    };
    let mut fa = facts(&st);
    if let Some(a) = args["lcscNumbers"].as_array() { fa["lcscNumbers"] = Value::Array(a.iter().filter(|v| v.is_string()).cloned().collect()); }
    let eco = tier("economic", &fa, size, thick, layers, lcsc_missing, panel.is_some());
    let std_ = tier("standard", &fa, size, thick, layers, lcsc_missing, panel.is_some());
    let service = if eco["ok"] == json!(true) { json!("economic") } else if std_["ok"] == json!(true) { json!("standard") } else { Value::Null };
    json!({"success": true, "fab": {"name": "JLCPCB", "source": "https://jlcpcb.com/capabilities/pcb-assembly-capabilities", "read": "2026-10-26"},
        "service": service, "economic": eco, "standard": std_, "board": fa, "linesWithoutLcsc": lcsc_lines,
        "_hint": "service is the cheapest JLCPCB assembly tier every rule allows (null: fix what the rules mark false). A rule marked null was not decided: Economic also needs every part offered in Economic, which JLCPCB states per part (PCBA Type), and a two-pad part without bodyMm is sized from its copper. Rotation: JLCPCB's part orientation can differ from the tool's for some packages; check every part in JLCPCB's placement preview after uploading the BOM and pick-and-place."})
}

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

    fn board() -> Value {
        json!({"components": [{"ref": "U1", "side": "top", "pattern": "QFN-20"}, {"ref": "C1", "side": "top", "pattern": "C0402"}, {"ref": "R9", "side": "bottom", "pattern": "R0603"}],
               "pads": [{"ref": "U1", "name": "1", "x": 0.0, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "2", "x": 0.5, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "3", "x": 1.0, "y": 0.0, "drill": 0.0},
                        {"ref": "C1", "name": "1", "x": 5.0, "y": 0.0, "drill": 0.0}, {"ref": "C1", "name": "2", "x": 6.0, "y": 0.0, "drill": 0.0},
                        {"ref": "R9", "name": "1", "x": 9.0, "y": 0.0, "drill": 0.0}, {"ref": "R9", "name": "2", "x": 10.5, "y": 0.0, "drill": 0.0}],
               "outline": [[0, 0], [40, 0], [40, 20], [0, 20]]})
    }

    #[test]
    fn facts_find_pitch_the_smallest_chip_and_the_bottom_side() {
        let fa = facts(&board());
        assert_eq!(fa["finestPitch"], json!({"mm": 0.5, "ref": "U1"}));
        assert_eq!(fa["smallestChip"], json!({"padCentresMm": 1.0, "ref": "C1", "sizeMm": null, "sizeFrom": null}));
        assert_eq!(fa["bottomSideParts"], json!(["R9"]));
        // fusion-lane #24: pads sharing one centre are one land, and a pad-less icon on the bottom is no part
        let mut b = board();
        b["components"].as_array_mut().unwrap().push(json!({"ref": "Q1", "side": "top", "pattern": "PowerPAK"}));
        b["components"].as_array_mut().unwrap().push(json!({"ref": "LOGO1", "side": "bottom", "pattern": "ICON"}));
        for k in 5..=8 { b["pads"].as_array_mut().unwrap().push(json!({"ref": "Q1", "name": k.to_string(), "x": 20.0, "y": 0.0, "drill": 0.0})); }
        b["pads"].as_array_mut().unwrap().push(json!({"ref": "Q1", "name": "1", "x": 20.0, "y": 1.27, "drill": 0.0}));
        let fa = facts(&b);
        assert_eq!(fa["finestPitch"], json!({"mm": 0.5, "ref": "U1"}));
        assert_eq!((fa["bottomSideParts"].clone(), fa["parts"].clone()), (json!(["R9"]), json!(4)));
    }

    #[test]
    fn a_small_two_sided_board_needs_standard_in_a_panel() {
        let fa = facts(&board());
        let eco = tier("economic", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);
        assert_eq!(eco["ok"], json!(false)); // R9 on the bottom
        let std_ = tier("standard", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);
        assert_eq!(std_["ok"], json!(false)); // under 70 x 70 and no fiducials
        let std_panel = tier("standard", &fa, (90.0, 80.0), Some(1.6), Some(2), Some(0), true);
        assert_eq!(std_panel["ok"], json!(true));
        assert_eq!(tier("economic", &fa, (40.0, 20.0), Some(0.4), Some(2), None, false)["rules"][1]["ok"], json!(false));
    }

    #[test]
    fn the_verb_reads_the_stack_and_the_bridges_lcsc_lines() {
        let r = assembly_check(&json!({"board": board(), "stack": {"totalUm": 1600, "copperLayers": 2}, "args": {"panelMm": [90, 80], "lcscMissing": [{"comment": "10k", "designators": "R9"}]}}));
        assert_eq!(r["service"], Value::Null, "{r}");
        assert_eq!(r["linesWithoutLcsc"][0]["designators"], "R9");
        let lcsc = r["standard"]["rules"].as_array().unwrap().last().unwrap().clone();
        assert_eq!(lcsc["ok"], json!(false));
        assert_eq!(assembly_check(&json!({"board": board(), "stack": {"totalUm": 1600, "copperLayers": 2}, "args": {"panelMm": [90, 80], "lcscMissing": 0}}))["service"], "standard");
        assert_eq!(assembly_check(&json!({"board": {"pads": []}, "args": {}}))["errorCode"], "no_outline");
    }

    fn pad(r: &str, n: &str, x: f64, y: f64, sx: f64, sy: f64, shape: &str, net: &str) -> Value {
        json!({"ref": r, "name": n, "x": x, "y": y, "sizeX": sx, "sizeY": sy, "rotation": 0.0, "shape": shape, "net": net, "drill": 0.0})
    }
    fn eco_rule(r: &Value, name: &str) -> Value { r["economic"]["rules"].as_array().unwrap().iter().find(|x| x["rule"].as_str().unwrap().starts_with(name)).cloned().unwrap() }
    fn run(comps: Value, pads: Value, args: Value) -> Value {
        assembly_check(&json!({"board": {"components": comps, "pads": pads, "outline": [[0, 0], [40, 0], [40, 40], [0, 40]]}, "stack": {"totalUm": 1600, "copperLayers": 2}, "args": args}))
    }

    #[test]
    fn a_two_pad_part_is_sized_by_its_body_not_its_pad_centres() {
        // #30: TI X1SON-2 (1.0 x 0.6 mm, pad centres 0.7 mm, LCSC C48260) is Economic at JLCPCB
        let pads = json!([pad("D1", "1", 0.0, 0.0, 0.4, 0.5, "rect", "A"), pad("D1", "2", 0.7, 0.0, 0.4, 0.5, "rect", "K")]);
        let with_body = run(json!([{"ref": "D1", "side": "top", "pattern": "X1SON-2", "bodyMm": [0.6, 1.0]}]), pads.clone(), json!({}));
        assert_eq!(with_body["board"]["smallestChip"]["sizeMm"], json!([1.0, 0.6]), "{with_body}");
        assert_eq!(eco_rule(&with_body, "smallest package")["ok"], json!(true));
        // no body: its copper, 1.1 mm end to end, sits between 0201 and 0402, so the rule says it is an estimate
        let copper = run(json!([{"ref": "D1", "side": "top", "pattern": "X1SON-2"}]), pads, json!({}));
        assert_eq!(copper["board"]["smallestChip"]["sizeFrom"], "copper");
        assert_eq!(copper["board"]["smallestChip"]["sizeMm"], json!([1.1, 0.5]));
        let r = eco_rule(&copper, "smallest package");
        assert_eq!(r["ok"], Value::Null, "{r}");
        assert!(r["detail"].as_str().unwrap().contains("an estimate"));
        // a real 0201 (0.6 x 0.3 mm body) still fails Economic
        let o201 = run(json!([{"ref": "C1", "side": "top", "pattern": "C_0201", "bodyMm": [0.6, 0.3]}]),
            json!([pad("C1", "1", 0.0, 0.0, 0.3, 0.3, "rect", "A"), pad("C1", "2", 0.5, 0.0, 0.3, 0.3, "rect", "B")]), json!({}));
        assert_eq!(eco_rule(&o201, "smallest package")["ok"], json!(false));
        // a rotated 0402's copper reads the same as an upright one
        let rot = run(json!([{"ref": "R1", "side": "top", "pattern": "R_0402"}]),
            json!([{"ref": "R1", "name": "1", "x": 0.0, "y": 0.0, "sizeX": 0.6, "sizeY": 0.5, "rotation": 90.0, "shape": "rect", "drill": 0.0},
                   {"ref": "R1", "name": "2", "x": 0.0, "y": 0.96, "sizeX": 0.6, "sizeY": 0.5, "rotation": 90.0, "shape": "rect", "drill": 0.0}]), json!({}));
        assert_eq!(rot["board"]["smallestChip"]["sizeMm"], json!([1.56, 0.5]), "{rot}");
        assert_eq!(eco_rule(&rot, "smallest package")["ok"], json!(true));
    }

    #[test]
    fn a_ball_grid_is_held_to_its_own_pitch() {
        // #30: a 0.4 mm DSBGA-4 (TPS22916BYFPR, C2150095) is Standard Only
        let balls = |r: &str| json!([pad(r, "A1", 0.0, 0.0, 0.25, 0.25, "circle", "1"), pad(r, "A2", 0.4, 0.0, 0.25, 0.25, "circle", "2"),
                                     pad(r, "B1", 0.0, 0.4, 0.25, 0.25, "circle", "3"), pad(r, "B2", 0.4, 0.4, 0.25, 0.25, "circle", "4")]);
        let r = run(json!([{"ref": "U2", "side": "top", "pattern": "DSBGA-4"}]), balls("U2"), json!({}));
        assert_eq!(r["board"]["finestBgaPitch"], json!({"mm": 0.4, "ref": "U2"}), "{r}");
        assert_eq!(r["board"]["finestPitch"], Value::Null);
        let p = eco_rule(&r, "IC pin pitch");
        assert_eq!((p["ok"].clone(), p["detail"].as_str().unwrap().contains("needs 0.5 mm")), (json!(false), true), "{p}");
        assert_eq!(r["economic"]["ok"], json!(false));
        // found by its round lands in rows and columns when the footprint's name says nothing
        let unnamed = run(json!([{"ref": "U2", "side": "top", "pattern": "U2_PKG"}]), balls("U2"), json!({}));
        assert_eq!(unnamed["board"]["finestBgaPitch"]["mm"], json!(0.4));
        // a 0.4 mm QFN is not a ball grid and stays at the 0.4 mm IC limit
        let qfn = run(json!([{"ref": "U3", "side": "top", "pattern": "QFN-16"}]),
            json!([pad("U3", "1", 0.0, 0.0, 0.2, 0.6, "roundrect", "1"), pad("U3", "2", 0.4, 0.0, 0.2, 0.6, "roundrect", "2"), pad("U3", "3", 0.8, 0.0, 0.2, 0.6, "roundrect", "3")]), json!({}));
        assert_eq!((qfn["board"]["finestBgaPitch"].clone(), eco_rule(&qfn, "IC pin pitch")["ok"].clone()), (Value::Null, json!(true)));
    }

    #[test]
    fn a_fets_joined_lands_are_no_pitch() {
        // #30: TDSON-8, source pins 1 and 2 as overlapping lands on one net, plus unnamed copper beside them
        let pads = json!([pad("Q1", "1", 0.0, 0.0, 0.6, 0.7, "rect", "SRC"), pad("Q1", "2", 0.12, 0.0, 0.6, 0.7, "rect", "SRC"),
                          pad("Q1", "", 0.3, 0.2, 0.5, 0.5, "rect", "SRC"), pad("Q1", "3", 1.27, 0.0, 0.6, 0.7, "rect", "SRC2"),
                          pad("Q1", "4", 2.54, 0.0, 0.6, 0.7, "rect", "G"), pad("Q1", "5", 1.27, 3.0, 3.8, 3.0, "rect", "DRN")]);
        let r = run(json!([{"ref": "Q1", "side": "top", "pattern": "TDSON-8"}]), pads, json!({}));
        assert_eq!(r["board"]["finestPitch"], json!({"mm": 1.15, "ref": "Q1"}), "{r}");
        assert_eq!(eco_rule(&r, "IC pin pitch")["ok"], json!(true));
        // pins on different nets that close are still a pitch, and so are pins with no nets assigned yet
        let tight = run(json!([{"ref": "Q1", "side": "top", "pattern": "X"}]),
            json!([pad("Q1", "1", 0.0, 0.0, 0.2, 0.2, "rect", "A"), pad("Q1", "2", 0.12, 0.0, 0.2, 0.2, "rect", "B"), pad("Q1", "3", 1.0, 0.0, 0.2, 0.2, "rect", "C")]), json!({}));
        assert_eq!(tight["board"]["finestPitch"]["mm"], json!(0.12));
        let unrouted = run(json!([{"ref": "Q1", "side": "top", "pattern": "X"}]),
            json!([pad("Q1", "1", 0.0, 0.0, 0.2, 0.2, "rect", ""), pad("Q1", "2", 0.12, 0.0, 0.2, 0.2, "rect", ""), pad("Q1", "3", 1.0, 0.0, 0.2, 0.2, "rect", "")]), json!({}));
        assert_eq!(unrouted["board"]["finestPitch"]["mm"], json!(0.12));
    }

    #[test]
    fn a_stack_a_little_over_1_6_mm_passes_and_part_ratings_are_named() {
        // #30: KiCad's default 4-layer stack adds up to 1.6166 mm
        let r = assembly_check(&json!({"board": board(), "stack": {"totalUm": 1616.6, "copperLayers": 4}, "args": {"lcscNumbers": ["C48260", "C2150095"]}}));
        let th = eco_rule(&r, "board 0.8 to 1.6");
        assert_eq!(th["ok"], json!(true), "{th}");
        assert!(th["detail"].as_str().unwrap().contains("within 0.05 mm"));
        assert_eq!(eco_rule(&r, "board 0.8 to 1.6")["ok"], json!(true));
        let too = assembly_check(&json!({"board": board(), "stack": {"totalUm": 1700, "copperLayers": 4}, "args": {}}));
        assert_eq!(eco_rule(&too, "board 0.8 to 1.6")["ok"], json!(false));
        let pt = eco_rule(&r, "every part offered in Economic");
        assert_eq!(pt["ok"], Value::Null);
        assert!(pt["detail"].as_str().unwrap().ends_with(": C48260, C2150095"), "{pt}");
        assert!(r["standard"]["rules"].as_array().unwrap().iter().all(|x| !x["rule"].as_str().unwrap().starts_with("every part offered")));
    }
}