Skip to main content

brep_plm/api/
setup.rs

1//! Optional starter content. All writes use the normal PLM part/document APIs.
2use super::{blocking, require_admin, Shared};
3use crate::{
4    db::PartSpec,
5    model::{DocumentClass, Origin, User},
6    Error,
7};
8use axum::{extract::State, http::HeaderMap, Json};
9use serde::Deserialize;
10use serde_json::{json, Value};
11mod kicad;
12
13pub async fn kicad_part_type(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
14    require_admin(&db, &headers)?;
15    let part_type = db.mutate(|state| {
16        if let Some(existing) = state.part_type("kicad") {
17            if !matches!(existing.mode, crate::model::NumberMode::Counter) { return Err(Error::bad_request("The KiCad part type must use counter numbering.")); }
18            return Ok(existing.clone());
19        }
20        let part_type = crate::model::PartType { id: "kicad".into(), name: "KiCad electrical parts".into(), prefix: "ELEC".into(), digits: 11, next: 1, created_at: crate::db::now(), mode: crate::model::NumberMode::Counter };
21        state.part_types.push(part_type.clone());
22        Ok(part_type)
23    })?;
24    Ok(Json(serde_json::to_value(part_type).map_err(Error::internal)?))
25}
26
27pub async fn kicad_libraries(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
28    require_admin(&db, &headers)?;
29    Ok(Json(blocking(move || kicad::libraries(&db)).await?))
30}
31
32#[derive(Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct TaxonomyRequest { pub category: String }
35
36pub async fn kicad_taxonomy(State(db): State<Shared>, headers: HeaderMap, Json(request): Json<TaxonomyRequest>) -> Result<Json<Value>, Error> {
37    require_admin(&db, &headers)?;
38    Ok(Json(blocking(move || kicad::repair_taxonomy(&db, &request.category)).await?))
39}
40
41#[derive(Clone, Deserialize)]
42#[serde(deny_unknown_fields)]
43pub struct ImportRequest {
44    pub part_type: String,
45    pub category: String,
46    pub pack: String,
47    #[serde(default)]
48    pub library: String,
49}
50
51pub async fn import(
52    State(db): State<Shared>,
53    headers: HeaderMap,
54    Json(request): Json<ImportRequest>,
55) -> Result<Json<Value>, Error> {
56    let user = require_admin(&db, &headers)?;
57    Ok(Json(blocking(move || {
58        db.read(|s| {
59            let kind = s.part_type(&request.part_type).ok_or_else(|| Error::bad_request("choose a part type"))?;
60            if !matches!(kind.mode, crate::model::NumberMode::Counter) {
61                return Err(Error::bad_request("starter imports require a counter part type"));
62            }
63            if !request.category.is_empty() && crate::catalog::find(&s.categories, &request.category).is_none() {
64                return Err(Error::bad_request("choose an existing category"));
65            }
66            Ok(())
67        })?;
68        if request.pack != "kicad" {
69            // Validate the selection before provisioning anything.
70            starter_entries(&request.pack)?;
71            db.mutate(|state| {
72                if let Some(kind) = state.part_type("starter-member") {
73                    if kind.mode != crate::model::NumberMode::Free {
74                        return Err(Error::conflict("starter-member must use free text numbering"));
75                    }
76                } else {
77                    state.part_types.push(crate::model::PartType {
78                        id: "starter-member".into(), name: "Starter family member".into(),
79                        prefix: "".into(), digits: 9, next: 1, created_at: crate::db::now(),
80                        mode: crate::model::NumberMode::Free,
81                    });
82                }
83                Ok(())
84            })?;
85        }
86        if request.pack == "kicad" {
87            return kicad::import(&db, &user, &request);
88        }
89        let entries = starter_entries(&request.pack)?;
90        let warnings: Vec<String> = Vec::new();
91        let mut created = 0;
92        let mut skipped = 0;
93        let mut failed = Vec::new();
94        for (reference, name, document) in entries {
95            match install(&db, &user, &request, &reference, &name, document) {
96                Ok(true) => created += 1,
97                Ok(false) => skipped += 1,
98                Err(error) => failed.push(json!({"name":name,"error":error.to_string()})),
99            }
100        }
101        Ok(json!({"created":created,"skipped":skipped,"failed":failed,"warnings":warnings}))
102    }).await?))
103}
104
105// A retry resumes a document-less first revision after a failed write. Existing
106// completed parts are never replaced, including parts the user has edited.
107fn install(
108    db: &crate::db::Db,
109    user: &User,
110    request: &ImportRequest,
111    reference: &str,
112    name: &str,
113    mut document: Value,
114) -> Result<bool, Error> {
115    let existing = db.read(|s| {
116        s.parts
117            .iter()
118            .find(|p| p.part_type == request.part_type && p.external_ref == reference)
119            .cloned()
120    });
121    let part = if let Some(part) = existing {
122        if part.latest().is_some_and(|r| !r.content_hash.is_empty()) {
123            return Ok(false);
124        }
125        part
126    } else {
127        db.create_part_with(user, &PartSpec {
128            part_type: request.part_type.clone(), name: name.into(), category: request.category.clone(),
129            description: if request.pack == "kicad" { "KiCad symbol library import".into() } else { "Parametric starter geometry in mm; simplified fasteners without threads. Verify dimensions against your supplier before release.".into() },
130            document_class: if request.pack == "kicad" { DocumentClass::Normal } else { DocumentClass::Family },
131            external_ref: reference.into(), origin: Origin::Imported, ..PartSpec::default()
132        })?
133    };
134    if request.pack != "kicad" {
135        db.update_part(&part.id, &json!({"member_part_type":"starter-member"}))?;
136    }
137    let revision = part
138        .latest()
139        .ok_or_else(|| Error::conflict("import part has no revision"))?;
140    document["partAttributes"] = json!({"Part_Number":part.number,"Description":part.description});
141    // Members use the dedicated free text type. The unique family number
142    // prefixes their table numbers, avoiding collisions across packs.
143    if let Some(rows) = document["familyTable"]["rows"].as_array_mut() {
144        for (i, row) in rows.iter_mut().enumerate() {
145            row["partNumber"] = json!(format!("{}-{:02}", part.number, i + 1));
146        }
147    }
148    db.checkout(user, &part.id, &revision.id, "setup-wizard")?;
149    let body = serde_json::to_string(&document).map_err(Error::internal)?;
150    let written = db.write_import_document(
151        user,
152        &part.id,
153        &revision.id,
154        &revision.content_hash,
155        &body,
156        &json!({"uses":[]}),
157    );
158    let checked_in = db.checkin(user, &part.id, &revision.id, false);
159    written?;
160    checked_in?;
161    Ok(true)
162}
163
164fn primitive(
165    kind: &str,
166    id: &str,
167    dimensions: Value,
168    position: Value,
169    operation: &str,
170    targets: &[&str],
171) -> Value {
172    let mut params = dimensions;
173    params["id"] = json!(id);
174    params["transform"] = json!({"position":position,"rotationEuler":[0,0,0],"scale":[1,1,1]});
175    params["boolean"] = json!({"targets":targets,"operation":operation});
176    json!({"type":kind,"inputParams":params,"persistentData":{}})
177}
178fn cube(
179    id: &str,
180    x: Value,
181    y: Value,
182    z: Value,
183    position: Value,
184    operation: &str,
185    targets: &[&str],
186) -> Value {
187    primitive(
188        "P.CU",
189        id,
190        json!({"sizeX":x,"sizeY":y,"sizeZ":z}),
191        position,
192        operation,
193        targets,
194    )
195}
196fn cylinder(
197    id: &str,
198    radius: Value,
199    height: Value,
200    position: Value,
201    operation: &str,
202    targets: &[&str],
203) -> Value {
204    primitive(
205        "P.CY",
206        id,
207        json!({"radius":radius,"height":height}),
208        position,
209        operation,
210        targets,
211    )
212}
213fn family(expressions: &str, columns: &[&str], rows: Vec<Value>, features: Vec<Value>) -> Value {
214    json!({"documentClass":"family","expressions":expressions,"configurator":{},"features":features,
215        "familyTable":{"columns":columns.iter().map(|name|json!({"name":name,"label":name})).collect::<Vec<_>>(),"rows":rows}})
216}
217fn row(description: &str, values: Value) -> Value {
218    json!({"partNumber":"","revision":"A","description":description,"values":values})
219}
220
221fn starter_entries(pack: &str) -> Result<Vec<(String, String, Value)>, Error> {
222    let mut entries = Vec::new();
223    let mut add = |id: &str, name: &str, doc: Value| {
224        entries.push((format!("brep-starter:v1:{id}"), name.into(), doc))
225    };
226    match pack {
227        "fasteners" => {
228            add("socket-screws", "Metric socket head screws", family("diameter = 6; length = 20; headDiameter = 10; headHeight = 6;", &["diameter","length","headDiameter","headHeight"],
229                [(3,10,5.5,3),(4,16,7.0,4),(5,20,8.5,5),(6,20,10.0,6),(8,30,13.0,8)].into_iter().map(|(d,l,h,t)|row(&format!("M{d} x {l} socket head screw"),json!({"diameter":d.to_string(),"length":l.to_string(),"headDiameter":h.to_string(),"headHeight":t.to_string()}))).collect(),
230                vec![cylinder("Shank",json!("diameter / 2"),json!("length"),json!([0,0,0]),"NONE",&[]),cylinder("Head",json!("headDiameter / 2"),json!("headHeight"),json!([0,"length",0]),"UNION",&["Shank"])]));
231            add("washers", "Metric plain washers", family("bore = 6.4; outer = 12; thickness = 1.6;", &["bore","outer","thickness"],
232                [(3.2,7.0,0.5),(4.3,9.0,0.8),(5.3,10.0,1.0),(6.4,12.0,1.6),(8.4,16.0,1.6)].into_iter().map(|(b,o,t)|row(&format!("Washer {b} mm bore"),json!({"bore":b.to_string(),"outer":o.to_string(),"thickness":t.to_string()}))).collect(),
233                vec![cylinder("Washer",json!("outer / 2"),json!("thickness"),json!([0,0,0]),"NONE",&[]),cylinder("Bore",json!("bore / 2"),json!("thickness + 2"),json!([0,-1,0]),"SUBTRACT",&["Washer"])]));
234        }
235        "bar-stock" => {
236            add("rectangular-bar", "Rectangular bar stock", family("width = 20; height = 10; length = 100;", &["width","height","length"],
237                [(10,5),(20,10),(25,25),(50,10)].into_iter().map(|(w,h)|row(&format!("{w} x {h} mm bar"),json!({"width":w.to_string(),"height":h.to_string(),"length":"100"}))).collect(),vec![cube("Bar",json!("width"),json!("height"),json!("length"),json!([0,0,0]),"NONE",&[])]));
238            add(
239                "round-bar",
240                "Round bar stock",
241                family(
242                    "diameter = 20; length = 100;",
243                    &["diameter", "length"],
244                    [6, 10, 12, 20, 25, 50]
245                        .into_iter()
246                        .map(|d| {
247                            row(
248                                &format!("Round bar diameter {d} mm"),
249                                json!({"diameter":d.to_string(),"length":"100"}),
250                            )
251                        })
252                        .collect(),
253                    vec![cylinder(
254                        "Bar",
255                        json!("diameter / 2"),
256                        json!("length"),
257                        json!([0, 0, 0]),
258                        "NONE",
259                        &[],
260                    )],
261                ),
262            );
263        }
264        "i-beams" => add(
265            "i-beam",
266            "I beam cross sections",
267            family(
268                "width = 100; height = 100; web = 6; flange = 8; length = 100;",
269                &["width", "height", "web", "flange", "length"],
270                vec![
271                    row(
272                        "IPE 100 nominal section, sharp corners",
273                        json!({"width":"55","height":"100","web":"4.1","flange":"5.7","length":"100"}),
274                    ),
275                    row(
276                        "IPE 200 nominal section, sharp corners",
277                        json!({"width":"100","height":"200","web":"5.6","flange":"8.5","length":"100"}),
278                    ),
279                ],
280                vec![
281                    cube(
282                        "Web",
283                        json!("web"),
284                        json!("height - 2 * flange"),
285                        json!("length"),
286                        json!(["(width - web) / 2", "flange", 0]),
287                        "NONE",
288                        &[],
289                    ),
290                    cube(
291                        "Top",
292                        json!("width"),
293                        json!("flange"),
294                        json!("length"),
295                        json!([0, "height - flange", 0]),
296                        "UNION",
297                        &["Web"],
298                    ),
299                    cube(
300                        "Bottom",
301                        json!("width"),
302                        json!("flange"),
303                        json!("length"),
304                        json!([0, 0, 0]),
305                        "UNION",
306                        &["Top"],
307                    ),
308                ],
309            ),
310        ),
311        "aluminum" => {
312            add(
313                "aluminum-tube",
314                "Aluminum square tube cross sections",
315                family(
316                    "size = 20; wall = 2; length = 100;",
317                    &["size", "wall", "length"],
318                    [20, 25, 30, 40, 50]
319                        .into_iter()
320                        .map(|size| {
321                            row(
322                                &format!("{size} x {size} x 2 mm square tube"),
323                                json!({"size":size.to_string(),"wall":"2","length":"100"}),
324                            )
325                        })
326                        .collect(),
327                    vec![
328                        cube(
329                            "Tube",
330                            json!("size"),
331                            json!("size"),
332                            json!("length"),
333                            json!([0, 0, 0]),
334                            "NONE",
335                            &[],
336                        ),
337                        cube(
338                            "Void",
339                            json!("size - 2 * wall"),
340                            json!("size - 2 * wall"),
341                            json!("length + 2"),
342                            json!(["wall", "wall", -1]),
343                            "SUBTRACT",
344                            &["Tube"],
345                        ),
346                    ],
347                ),
348            );
349            let mut profile = vec![cube(
350                "Profile",
351                json!("size"),
352                json!("size"),
353                json!("length"),
354                json!([0, 0, 0]),
355                "NONE",
356                &[],
357            )];
358            for (id, x, y, w, h, target) in [
359                (
360                    "SlotBottom",
361                    "(size - slot) / 2",
362                    "-1",
363                    "slot",
364                    "size / 4 + 1",
365                    "Profile",
366                ),
367                (
368                    "SlotTop",
369                    "(size - slot) / 2",
370                    "3 * size / 4",
371                    "slot",
372                    "size / 4 + 1",
373                    "SlotBottom",
374                ),
375                (
376                    "SlotLeft",
377                    "-1",
378                    "(size - slot) / 2",
379                    "size / 4 + 1",
380                    "slot",
381                    "SlotTop",
382                ),
383                (
384                    "SlotRight",
385                    "3 * size / 4",
386                    "(size - slot) / 2",
387                    "size / 4 + 1",
388                    "slot",
389                    "SlotLeft",
390                ),
391            ] {
392                profile.push(cube(
393                    id,
394                    json!(w),
395                    json!(h),
396                    json!("length + 2"),
397                    json!([x, y, -1]),
398                    "SUBTRACT",
399                    &[target],
400                ));
401            }
402            // Undercuts give each slot a T cross section.
403            for (id, x, y, w, h, target) in [
404                (
405                    "TBottom",
406                    "(size - cavity) / 2",
407                    "size / 8",
408                    "cavity",
409                    "size / 8",
410                    "SlotRight",
411                ),
412                (
413                    "TTop",
414                    "(size - cavity) / 2",
415                    "3 * size / 4",
416                    "cavity",
417                    "size / 8",
418                    "TBottom",
419                ),
420                (
421                    "TLeft",
422                    "size / 8",
423                    "(size - cavity) / 2",
424                    "size / 8",
425                    "cavity",
426                    "TTop",
427                ),
428                (
429                    "TRight",
430                    "3 * size / 4",
431                    "(size - cavity) / 2",
432                    "size / 8",
433                    "cavity",
434                    "TLeft",
435                ),
436            ] {
437                profile.push(cube(
438                    id,
439                    json!(w),
440                    json!(h),
441                    json!("length + 2"),
442                    json!([x, y, -1]),
443                    "SUBTRACT",
444                    &[target],
445                ));
446            }
447            add("aluminum-t-slot", "Aluminum T slot cross sections", family("size = 20; slot = 6; cavity = 10; length = 100;", &["size","slot","cavity","length"],
448                [(20,6,10),(30,8,14),(40,8,16)].into_iter().map(|(size,slot,cavity)|row(&format!("{size} x {size} mm generic T slot"),json!({"size":size.to_string(),"slot":slot.to_string(),"cavity":cavity.to_string(),"length":"100"}))).collect(), profile));
449            add("aluminum-angle", "Aluminum angle cross sections", family("width = 25; height = 25; wall = 3; length = 100;", &["width","height","wall","length"], [20,25,30,40,50].into_iter().map(|size|row(&format!("{size} x {size} x 3 mm angle"),json!({"width":size.to_string(),"height":size.to_string(),"wall":"3","length":"100"}))).collect(),
450                vec![cube("Angle",json!("width"),json!("height"),json!("length"),json!([0,0,0]),"NONE",&[]),cube("Void",json!("width"),json!("height"),json!("length + 2"),json!(["wall","wall",-1]),"SUBTRACT",&["Angle"])]));
451        }
452        _ => return Err(Error::bad_request("unknown starter pack")),
453    }
454    Ok(entries)
455}