main
Colby Knox 0.2.74 source (not yet released, needs signing): jlcpcb_order (one folder: Gerber zip, JLCPCB BOM and CPL, order form,… 83a5027
//! A JLCPCB order in one call: the fab check against JLCPCB's limits, the manufacturing outputs, the JLCPCB BOM and
//! pick-and-place, the assembly-tier check, and one folder to upload from (the Gerbers and drill zipped the way the
//! order page takes them, the BOM and CPL beside it) with every issue in one list.
use serde_json::{json, Value};
use std::io::Write;
use std::path::{Path, PathBuf};

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }

/// The values JLCPCB's order form asks for, from the fab check's measurements. Pure.
pub fn order_form(fab: &Value) -> Value {
    let m = &fab["measured"];
    let hole = [&m["viaDrill"]["mm"], &m["padHole"]["mm"]].iter().filter_map(|v| v.as_f64()).fold(None::<f64>, |a, b| Some(a.map_or(b, |x| x.min(b))));
    json!({"layers": m["copperLayers"], "dimensionsMm": m["boardSize"]["mm"], "outerCopperOz": fab["fab"]["copperOz"].as_f64().map(|o| (o * 2.0).round() / 2.0),
           "minTrackSpaceMm": [m["track"]["mm"], m["clearanceRule"]["mm"]], "minHoleMm": hole,
           "note": "Board thickness, surface finish, mask and silk colours are the order form's choices; thickness must match the stack-up (altium_layer_stack)."})
}

/// Every issue from the checks as one list of {from, what}. Pure.
pub fn issues(fab: &Value, asm: &Value, export: &Value) -> Vec<Value> {
    let mut out = Vec::new();
    for o in fab["outsideLimits"].as_array().cloned().unwrap_or_default() {
        out.push(json!({"from": "fab", "what": format!("{} {} mm, JLCPCB needs {}", o["limit"].as_str().unwrap_or(""), o["boardMm"], o["limitMm"]), "at": o["at"]}));
    }
    for c in fab["costlierOrBelowRecommended"].as_array().cloned().unwrap_or_default() {
        out.push(json!({"from": "fab (costs more)", "what": c["note"]}));
    }
    if asm["service"].is_null() {
        for t in ["economic", "standard"] {
            for r in asm[t]["rules"].as_array().cloned().unwrap_or_default().iter().filter(|r| r["ok"] == json!(false)) {
                out.push(json!({"from": format!("assembly ({t})"), "what": format!("{}: {}", r["rule"].as_str().unwrap_or(""), r["detail"].as_str().unwrap_or(""))}));
            }
        }
    }
    if export["fabChecks"]["outline"]["present"] == json!(false) { out.push(json!({"from": "gerbers", "what": "no board outline in the Gerbers"})); }
    if export["fabChecks"]["copperLayers"]["ok"] == json!(false) { out.push(json!({"from": "gerbers", "what": "fewer copper Gerbers than the board has layers"})); }
    out
}

/// A Gerber layer or the drill file: what JLCPCB's order page reads. Altium's reports (.REP, .RUL, .EXTREP), aperture
/// files and drill reports (.DRR, .LDP) stay out of the zip. Pure.
pub fn upload_file(rel: &str) -> bool {
    let l = rel.replace('\\', "/").to_ascii_lowercase();
    let ext = l.rsplit('.').next().unwrap_or("");
    if l.starts_with("nc drill/") { return ext == "txt"; }
    l.starts_with("gerber/") && ext.starts_with('g') && !matches!(ext, "gbr_lib")
}

/// Zip the files under `root` named in `rel` (flat, by file name) into `zip_path`.
fn zip_flat(root: &Path, rel: &[String], zip_path: &Path) -> Result<usize, String> {
    let file = std::fs::File::create(zip_path).map_err(|e| format!("{}: {e}", zip_path.display()))?;
    let mut z = zip::ZipWriter::new(file);
    let opts = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
    let mut n = 0;
    for r in rel {
        let p = root.join(r);
        let Ok(bytes) = std::fs::read(&p) else { continue };
        let name = p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
        z.start_file(name, opts).map_err(|e| e.to_string())?;
        z.write_all(&bytes).map_err(|e| e.to_string())?;
        n += 1;
    }
    z.finish().map_err(|e| e.to_string())?;
    Ok(n)
}

/// altium_jlcpcb_order {projectPath, pcbPath, outputDir?, variant?}
pub fn jlcpcb_order(args: &Value) -> Value {
    use crate::support::s;
    if let Some(g) = crate::support::need_licensed() { return g; }
    let (Some(prj), Some(pcb)) = (s(args, "projectPath"), s(args, "pcbPath")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) and pcbPath (.PcbDoc) are required"});
    };
    let stem = Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());
    let pack: PathBuf = s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(&prj).parent().unwrap_or(Path::new(".")).join(format!("JLCPCB order {stem}")));
    let _ = std::fs::remove_dir_all(&pack);
    if let Err(e) = std::fs::create_dir_all(&pack) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", pack.display())}); }
    let fab = crate::fab::fab_check(&json!({"filePath": pcb, "fab": "jlcpcb"}));
    if fab.get("success").and_then(|b| b.as_bool()) != Some(true) { return fab; }
    let export = crate::manufacturing::export_manufacturing(&json!({"projectPath": prj, "pcbPath": pcb, "timeout": 400}));
    if export.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "export_failed", "error": "the manufacturing outputs failed", "export": export}); }
    let out_dir = PathBuf::from(export["outputDir"].as_str().unwrap_or(""));
    let files: Vec<String> = export["files"].as_array().cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(String::from)).collect();
    let fabfiles: Vec<String> = files.iter().filter(|r| upload_file(r)).cloned().collect();
    let zip_path = pack.join(format!("{stem}-gerbers.zip"));
    let zipped = match zip_flat(&out_dir, &fabfiles, &zip_path) { Ok(n) => n, Err(e) => return json!({"success": false, "errorCode": "zip_failed", "error": e}) };
    let mut bom_args = json!({"projectPath": prj, "outputDir": pack.to_string_lossy(), "write": true});
    if let Some(v) = s(args, "variant") { bom_args["variant"] = json!(v); }
    let bom = crate::bom::bom(&bom_args);
    let asm = crate::assembly::assembly_check(&json!({"filePath": pcb, "projectPath": prj}));
    let form = order_form(&fab);
    let list = issues(&fab, &asm, &export);
    let summary = json!({"board": pcb, "project": prj, "orderForm": form, "fabFits": fab["fits"], "assemblyService": asm["service"], "issues": list,
                         "files": {"gerbers": zip_path.to_string_lossy(), "bom": pack.join("bom-jlcpcb.csv").to_string_lossy(), "cpl": pack.join("cpl-jlcpcb.csv").to_string_lossy()}});
    let _ = std::fs::write(pack.join("order.json"), serde_json::to_string_pretty(&summary).unwrap_or_default());
    let ready = fab["fits"] == json!(true) && !asm["service"].is_null() && list.is_empty();
    json!({"success": true, "ready": ready, "folder": pack.to_string_lossy(), "gerberZip": {"path": zip_path.to_string_lossy(), "files": zipped},
        "bomFiles": bom.get("files").cloned().unwrap_or(Value::Null), "orderForm": form, "fabFits": fab["fits"], "assemblyService": asm["service"],
        "issues": list, "checks": {"fab": {"outsideLimits": fab["outsideLimits"], "source": fab["fab"]["source"]}, "assembly": {"economic": asm["economic"]["ok"], "standard": asm["standard"]["ok"]}},
        "_hint": if ready { "Upload the Gerber zip on JLCPCB's order page, set the order form from orderForm, then add assembly with bom-jlcpcb.csv and cpl-jlcpcb.csv and check every part's rotation in their preview." }
                 else { "issues lists what stands between this board and a JLCPCB order (fab limits, the assembly tier, the Gerbers); the folder is written anyway. Fix them and run it again." }})
}

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

    #[test]
    fn issues_gather_every_check() {
        let fab = json!({"outsideLimits": [{"limit": "minTrack", "boardMm": 0.08, "limitMm": 0.1, "at": [1, 2]}], "costlierOrBelowRecommended": [{"note": "via holes under 0.3 mm"}],
                         "measured": {"copperLayers": 2, "boardSize": {"mm": [40.0, 20.0]}, "track": {"mm": 0.2}, "clearanceRule": {"mm": 0.15}, "viaDrill": {"mm": 0.3}, "padHole": {"mm": 0.8}}, "fab": {"copperOz": 1.0}});
        let asm = json!({"service": null, "economic": {"rules": [{"rule": "parts on one side only", "ok": false, "detail": "1 on the bottom"}]}, "standard": {"rules": [{"rule": "fiducials", "ok": false, "detail": "0"}]}});
        let ex = json!({"fabChecks": {"outline": {"present": true}, "copperLayers": {"ok": true}}});
        let l = issues(&fab, &asm, &ex);
        assert_eq!(l.len(), 4);
        assert!(l[0]["what"].as_str().unwrap().starts_with("minTrack 0.08"));
        let form = order_form(&fab);
        assert_eq!(form["minHoleMm"], 0.3);
        assert_eq!(form["dimensionsMm"], json!([40.0, 20.0]));
        let _ = f(&json!(1));
    }
    #[test]
    fn only_gerbers_and_the_drill_file_go_in_the_zip() {
        for (f, want) in [("Gerber\\lane.GTL", true), ("Gerber\\lane.GM1", true), ("Gerber\\lane.GKO", true), ("NC Drill\\lane.TXT", true),
                          ("Gerber\\lane.REP", false), ("Gerber\\lane.RUL", false), ("Gerber\\lane.EXTREP", false), ("Gerber\\lane.apr", false),
                          ("Gerber\\lane-macro.APR_LIB", false), ("NC Drill\\lane.DRR", false), ("NC Drill\\lane.LDP", false), ("Pick Place\\x.csv", false)] {
            assert_eq!(upload_file(f), want, "{f}");
        }
    }
}