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