1use crate::{
3 auth, catalog,
4 db::{find_revision_mut, Db, State},
5 model::{AttributeDef, BakeStatus, Revision, User},
6 Error,
7};
8use serde::{Deserialize, Serialize};
9use serde_json::{json, Value};
10use std::collections::{BTreeMap, BTreeSet};
11
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct Configuration {
14 #[serde(default)]
15 pub part_fields: BTreeMap<String, Vec<AttributeDef>>,
16 #[serde(default)]
17 pub occurrence_fields: Vec<AttributeDef>,
18 #[serde(default)]
19 pub layouts: Vec<Layout>,
20 #[serde(default)]
21 pub selections: BTreeMap<String, String>,
22}
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct Layout {
25 pub id: String,
26 pub name: String,
27 pub owner: Option<String>,
29 pub columns: Vec<String>,
30}
31#[derive(Debug, Clone, Default, Serialize, Deserialize)]
32pub struct Occurrence {
33 pub id: String,
34 pub part: String,
35 pub revision: String,
36 #[serde(default)]
37 pub attributes: BTreeMap<String, Value>,
38}
39#[derive(Debug, Clone, Serialize)]
41pub struct EditTarget {
42 pub resource: String,
43 pub key: String,
44}
45#[derive(Debug, Clone, Serialize)]
46pub struct Field {
47 pub id: String,
48 pub scope: String,
49 pub part_type: Option<String>,
50 pub key: String,
51 pub name: String,
52 pub editable: bool,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub edit: Option<EditTarget>,
55 #[serde(flatten)]
56 pub kind: crate::model::AttributeKind,
57 pub cad_field: String,
58}
59
60pub fn fields(state: &State) -> Vec<Field> {
61 use crate::model::AttributeKind;
62 let mut out = Vec::new();
63 for (key, name, cad) in [
64 ("number", "Part number", "Part_Number"),
65 ("name", "Name", "Description"),
66 ("revision_label", "Revision", "Revision"),
67 ("state", "State", "Lifecycle_State"),
68 ("quantity", "Quantity", "Quantity"),
69 ("total", "Total quantity", "Total"),
70 ("part_type", "Part type", "Part_Type"),
71 ("unit", "Unit", "Unit"),
72 (
73 "mpn",
74 "Manufacturer part number",
75 "Manufacturer_Part_Number",
76 ),
77 ("manufacturer", "Manufacturer", "Manufacturer"),
78 ("supplier", "Supplier", "Supplier"),
79 ("spn", "Supplier part number", "Supplier_Part_Number"),
80 ("unit_price", "Unit price", "Unit_Price"),
81 ("extended", "Extended price", "Extended_Price"),
82 ] {
83 out.push(Field {
84 id: format!("builtin.{key}"),
85 scope: "builtin".into(),
86 part_type: None,
87 key: key.into(),
88 name: name.into(),
89 editable: key == "name",
90 edit: (key == "name").then(|| EditTarget {
91 resource: "part".into(),
92 key: key.into(),
93 }),
94 kind: AttributeKind::Text,
95 cad_field: cad.into(),
96 });
97 }
98 for (key, name, cad) in [
99 ("find_number", "Callout / find number", "Find_Number"),
100 ("reference", "Reference designator", "Reference_Designator"),
101 ("notes", "Installation notes", "Notes"),
102 ] {
103 out.push(Field {
104 id: format!("builtin.{key}"),
105 scope: "occurrence".into(),
106 part_type: None,
107 key: key.into(),
108 name: name.into(),
109 editable: true,
110 edit: Some(EditTarget {
111 resource: "occurrence".into(),
112 key: cad.into(),
113 }),
114 kind: AttributeKind::Text,
115 cad_field: cad.into(),
116 });
117 }
118 for kind in &state.part_types {
119 for def in state
120 .bom_configuration
121 .part_fields
122 .get(&kind.id)
123 .into_iter()
124 .flatten()
125 {
126 out.push(Field {
127 id: format!("part.{}.{}", kind.id, def.key),
128 scope: "part".into(),
129 part_type: Some(kind.id.clone()),
130 key: def.key.clone(),
131 name: format!("{} ({})", def.name, kind.name),
132 editable: true,
133 edit: Some(EditTarget {
134 resource: "revision".into(),
135 key: def.key.clone(),
136 }),
137 kind: def.kind.clone(),
138 cad_field: def.key.clone(),
139 });
140 }
141 }
142 for def in &state.bom_configuration.occurrence_fields {
143 out.push(Field {
144 id: format!("occurrence.{}", def.key),
145 scope: "occurrence".into(),
146 part_type: None,
147 key: def.key.clone(),
148 name: def.name.clone(),
149 editable: true,
150 edit: Some(EditTarget {
151 resource: "occurrence".into(),
152 key: def.key.clone(),
153 }),
154 kind: def.kind.clone(),
155 cad_field: def.key.clone(),
156 });
157 }
158 out
159}
160
161pub fn checked_values(
162 defs: &[AttributeDef],
163 existing: &mut BTreeMap<String, Value>,
164 changes: &Value,
165) -> Result<(), Error> {
166 let changes = changes
167 .as_object()
168 .ok_or_else(|| Error::bad_request("attributes must be an object"))?;
169 for (key, value) in changes {
170 let def = defs
171 .iter()
172 .find(|def| def.key == *key)
173 .ok_or_else(|| Error::bad_request(format!("Unknown attribute '{key}'")))?;
174 match catalog::check_value(def, value).map_err(Error::bad_request)? {
175 Some(value) => {
176 existing.insert(key.clone(), value);
177 }
178 None => {
179 existing.remove(key);
180 }
181 }
182 }
183 Ok(())
184}
185
186fn can_edit(revision: &Revision, user: &User) -> Result<(), Error> {
187 if !revision.lifecycle.is_editable() {
188 return Err(Error::conflict(
189 "Start a new revision to edit these attributes",
190 ));
191 }
192 if revision
193 .lock
194 .as_ref()
195 .is_some_and(|lock| lock.user_id != user.id)
196 {
197 return Err(Error::conflict(
198 "This revision is checked out by another user",
199 ));
200 }
201 Ok(())
202}
203
204pub fn overlay(revision: &Revision, defs: &[AttributeDef], document: &mut Value) {
207 if !defs.is_empty() {
208 if !document["partAttributes"].is_object() {
209 document["partAttributes"] = json!({});
210 }
211 for def in defs {
212 let aliases: Vec<String> = document["partAttributes"]
213 .as_object()
214 .unwrap()
215 .keys()
216 .filter(|key| key.to_ascii_lowercase() == def.key && *key != &def.key)
217 .cloned()
218 .collect();
219 for alias in aliases {
220 if let Some(value) = revision.attributes.get(&def.key) {
221 document["partAttributes"][&alias] = value.clone();
222 } else {
223 document["partAttributes"]
224 .as_object_mut()
225 .unwrap()
226 .remove(&alias);
227 }
228 }
229 if let Some(value) = revision.attributes.get(&def.key) {
230 document["partAttributes"][&def.key] = value.clone();
231 } else {
232 document["partAttributes"]
233 .as_object_mut()
234 .unwrap()
235 .remove(&def.key);
236 }
237 }
238 }
239 if let Some(features) = document["features"].as_array_mut() {
240 for feature in features {
241 let id = feature["inputParams"]["id"].as_str().unwrap_or_default();
242 if let Some(occurrence) = revision.occurrences.iter().find(|o| o.id == id) {
243 if !occurrence.attributes.is_empty() || feature["inputParams"].get("bom").is_some()
244 {
245 feature["inputParams"]["bom"] = json!(occurrence.attributes);
246 }
247 }
248 }
249 }
250}
251
252impl Db {
253 pub fn set_type_fields(&self, id: &str, defs: Vec<AttributeDef>) -> Result<(), Error> {
254 let defs = catalog::check_definitions(defs)?;
255 self.mutate(|state| {
256 if !state.part_types.iter().any(|kind| kind.id == id) {
257 return Err(Error::not_found("part type"));
258 }
259 let old = state
260 .bom_configuration
261 .part_fields
262 .insert(id.into(), defs.clone())
263 .unwrap_or_default();
264 let ids: Vec<String> = state
265 .parts
266 .iter()
267 .filter(|p| p.part_type == id)
268 .map(|p| p.id.clone())
269 .collect();
270 for id in ids {
271 let part = state.part(&id).unwrap().clone();
272 for revision in &part.revisions {
273 let document = self
274 .read_document(&revision.document_key(&id))?
275 .and_then(|body| serde_json::from_str::<Value>(&body).ok())
276 .unwrap_or_default();
277 let stored = find_revision_mut(state, &id, &revision.id)?.1;
278 for def in &defs {
279 if old.iter().any(|old| old.key == def.key)
280 || stored.attributes.contains_key(&def.key)
281 {
282 continue;
283 }
284 let value = document["partAttributes"]
285 .as_object()
286 .and_then(|attrs| {
287 attrs
288 .iter()
289 .find(|(key, _)| key.to_ascii_lowercase() == def.key)
290 .map(|(_, value)| value)
291 })
292 .or_else(|| part.attributes.get(&def.key));
293 if let Some(value) = value {
294 if let Ok(Some(value)) = catalog::check_value(def, value) {
295 stored.attributes.insert(def.key.clone(), value);
296 }
297 }
298 }
299 stored.attributes_initialized = true;
300 }
301 state.touch_part(&id);
302 }
303 Ok(())
304 })
305 }
306 pub fn set_occurrence_fields(&self, defs: Vec<AttributeDef>) -> Result<(), Error> {
307 let defs = catalog::check_definitions(defs)?;
308 self.mutate(|state| {
309 let old =
310 std::mem::replace(&mut state.bom_configuration.occurrence_fields, defs.clone());
311 let mut touched = Vec::new();
312 for part in state.parts.iter_mut() {
313 let mut changed = false;
314 for revision in &mut part.revisions {
315 for occurrence in &mut revision.occurrences {
316 for def in &defs {
317 if old.iter().any(|old| old.key == def.key)
318 || occurrence.attributes.contains_key(&def.key)
319 {
320 continue;
321 }
322 let value = occurrence
323 .attributes
324 .iter()
325 .find(|(key, _)| key.to_ascii_lowercase() == def.key)
326 .map(|(_, value)| value.clone());
327 if let Some(value) = value {
328 if let Ok(Some(value)) = catalog::check_value(def, &value) {
329 occurrence.attributes.insert(def.key.clone(), value);
330 changed = true;
331 }
332 }
333 }
334 }
335 }
336 if changed {
337 touched.push(part.id.clone());
338 }
339 }
340 for id in touched {
341 state.touch_part(&id);
342 }
343 Ok(())
344 })
345 }
346 pub fn save_layout(
347 &self,
348 user: &User,
349 id: &str,
350 name: &str,
351 columns: Vec<String>,
352 shared: bool,
353 ) -> Result<Layout, Error> {
354 if shared && !user.is_admin() {
355 return Err(Error::forbidden(
356 "Only administrators manage shared BOM configurations",
357 ));
358 }
359 if name.trim().is_empty() {
360 return Err(Error::bad_request("Give the configuration a name"));
361 }
362 self.mutate(|state| {
363 let known: BTreeSet<String> = fields(state).into_iter().map(|f| f.id).collect();
364 let mut seen = BTreeSet::new();
365 if columns
366 .iter()
367 .any(|id| !known.contains(id) || !seen.insert(id.clone()))
368 {
369 return Err(Error::bad_request("Select available fields once each"));
370 }
371 let existing = state
372 .bom_configuration
373 .layouts
374 .iter()
375 .position(|l| l.id == id);
376 if let Some(at) = existing {
377 let l = &state.bom_configuration.layouts[at];
378 if l.owner.as_deref().is_some_and(|owner| owner != user.id)
379 || (l.owner.is_none() && !user.is_admin())
380 {
381 return Err(Error::forbidden(
382 "This configuration belongs to another user",
383 ));
384 }
385 }
386 let layout = Layout {
387 id: existing
388 .map(|_| id.to_string())
389 .unwrap_or_else(auth::new_id),
390 name: name.trim().into(),
391 owner: if shared { None } else { Some(user.id.clone()) },
392 columns,
393 };
394 if let Some(at) = existing {
395 state.bom_configuration.layouts[at] = layout.clone();
396 } else {
397 state.bom_configuration.layouts.push(layout.clone());
398 }
399 Ok(layout)
400 })
401 }
402 pub fn patch_revision_attributes(
403 &self,
404 user: &User,
405 part: &str,
406 rev: &str,
407 changes: &Value,
408 ) -> Result<(), Error> {
409 if !user.can_author() {
410 return Err(Error::forbidden(
411 "Editing attributes requires author permission",
412 ));
413 }
414 self.mutate(|state| {
415 let p = state
416 .part_by_id_or_number(part)
417 .ok_or_else(|| Error::not_found("part"))?;
418 let id = p.id.clone();
419 let defs = state
420 .bom_configuration
421 .part_fields
422 .get(&p.part_type)
423 .cloned()
424 .unwrap_or_default();
425 let revision =
426 crate::bom::find_revision(p, rev).ok_or_else(|| Error::not_found("revision"))?;
427 can_edit(revision, user)?;
428 let rid = revision.id.clone();
429 let revision = find_revision_mut(state, &id, &rid)?.1;
430 checked_values(&defs, &mut revision.attributes, changes)?;
431 revision.attributes_initialized = true;
432 self.sync_attribute_document(state, &id, &rid, user)?;
433 Ok(())
434 })
435 }
436 pub fn patch_occurrences(
437 &self,
438 user: &User,
439 part: &str,
440 rev: &str,
441 ids: &[String],
442 changes: &Value,
443 ) -> Result<(), Error> {
444 if !user.can_author() {
445 return Err(Error::forbidden(
446 "Editing attributes requires author permission",
447 ));
448 }
449 self.mutate(|state| {
450 let p = state
451 .part_by_id_or_number(part)
452 .ok_or_else(|| Error::not_found("part"))?;
453 let id = p.id.clone();
454 let revision =
455 crate::bom::find_revision(p, rev).ok_or_else(|| Error::not_found("revision"))?;
456 can_edit(revision, user)?;
457 let rid = revision.id.clone();
458 let mut defs = state.bom_configuration.occurrence_fields.clone();
459 for key in ["Find_Number", "Reference_Designator", "Notes"] {
460 defs.push(AttributeDef {
461 key: key.into(),
462 name: key.into(),
463 kind: crate::model::AttributeKind::Text,
464 required: false,
465 });
466 }
467 let revision = find_revision_mut(state, &id, &rid)?.1;
468 for oid in ids {
469 let occurrence = revision
470 .occurrences
471 .iter_mut()
472 .find(|o| o.id == *oid)
473 .ok_or_else(|| Error::not_found(format!("occurrence {oid}")))?;
474 checked_values(&defs, &mut occurrence.attributes, changes)?;
475 if let Some(changes) = changes.as_object() {
476 for key in changes.keys() {
477 let aliases: Vec<String> = occurrence
478 .attributes
479 .keys()
480 .filter(|alias| *alias != key && alias.eq_ignore_ascii_case(key))
481 .cloned()
482 .collect();
483 for alias in aliases {
484 if let Some(value) = occurrence.attributes.get(key).cloned() {
485 occurrence.attributes.insert(alias, value);
486 } else {
487 occurrence.attributes.remove(&alias);
488 }
489 }
490 }
491 }
492 }
493 self.sync_attribute_document(state, &id, &rid, user)?;
494 Ok(())
495 })
496 }
497 fn sync_attribute_document(
499 &self,
500 state: &mut State,
501 part: &str,
502 rev: &str,
503 user: &User,
504 ) -> Result<(), Error> {
505 let kind = state.part(part).unwrap().part_type.clone();
506 let defs = state
507 .bom_configuration
508 .part_fields
509 .get(&kind)
510 .cloned()
511 .unwrap_or_default();
512 let key = crate::identity::document_key(part, rev);
513 let path = self.document_path(&key)?;
514 let body = match std::fs::read_to_string(&path) {
515 Ok(body) => Some(body),
516 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
517 Err(e) => return Err(Error::internal(e)),
518 };
519 let revision = find_revision_mut(state, part, rev)?.1;
520 if let Some(body) = body {
521 let mut document: Value = serde_json::from_str(&body).map_err(Error::internal)?;
522 overlay(revision, &defs, &mut document);
523 let body = serde_json::to_string(&document).map_err(Error::internal)?;
524 crate::db::write_atomic(&path, &body).map_err(Error::internal)?;
525 revision.content_hash = auth::content_hash(&body);
526 revision.size = body.len() as u64;
527 if let Some(thumbnail) = revision.thumbnail.as_mut() {
528 thumbnail.content_hash = revision.content_hash.clone();
529 }
530 }
531 if let Some(bake) = revision
532 .bake
533 .as_mut()
534 .filter(|b| b.status != BakeStatus::Done)
535 {
536 bake.status = BakeStatus::Done;
537 bake.error = "superseded by saved attributes".into();
538 }
539 synchronize_uses(revision);
540 revision.modified_at = crate::db::now();
541 crate::review::document_changed(state, part, rev);
542 state.touch(key);
543 let _ = user;
544 Ok(())
545 }
546}
547
548pub fn capture_occurrences(
551 state: &State,
552 part: &str,
553 rev: &str,
554 body: &Value,
555) -> Result<Option<Vec<Occurrence>>, Error> {
556 let Some(raw) = body.get("occurrences") else {
557 return Ok(None);
558 };
559 let mut sent: Vec<Occurrence> = serde_json::from_value(raw.clone())
560 .map_err(|_| Error::bad_request("Invalid occurrences"))?;
561 let existing = state
562 .part(part)
563 .and_then(|p| p.revision(rev))
564 .ok_or_else(|| Error::not_found("revision"))?;
565 let mut seen = BTreeSet::new();
566 for occurrence in &mut sent {
567 if occurrence.id.is_empty() || !seen.insert(occurrence.id.clone()) {
568 return Err(Error::bad_request("Occurrences need unique stable ids"));
569 }
570 let child = state
571 .part_by_id_or_number(&occurrence.part)
572 .ok_or_else(|| Error::not_found("occurrence part"))?;
573 occurrence.part = child.id.clone();
574 occurrence.revision = crate::bom::find_revision(child, &occurrence.revision)
575 .ok_or_else(|| Error::not_found("occurrence revision"))?
576 .id
577 .clone();
578 if let Some(old) = existing.occurrences.iter().find(|o| o.id == occurrence.id) {
579 occurrence.attributes = old.attributes.clone();
580 }
581 for def in &state.bom_configuration.occurrence_fields {
583 if let Some(value) = occurrence.attributes.get(&def.key).cloned() {
584 match catalog::check_value(def, &value).map_err(Error::bad_request)? {
585 Some(value) => {
586 occurrence.attributes.insert(def.key.clone(), value);
587 }
588 None => {
589 occurrence.attributes.remove(&def.key);
590 }
591 }
592 }
593 }
594 }
595 Ok(Some(sent))
596}
597
598pub fn expand_bom(state: &State, bom: &mut crate::bom::Bom, flat: bool) {
601 let Some(part) = state.part(&bom.part_id) else {
602 return;
603 };
604 let Some(revision) = part.revision(&bom.revision_id) else {
605 return;
606 };
607 let mut lines = crate::bom::occurrence_lines(state, part, revision);
608 if flat {
609 let mut packed: Vec<crate::bom::BomLine> = Vec::new();
610 for mut row in lines {
611 if let Some(existing) = packed.iter_mut().find(|e| {
612 e.part_id == row.part_id
613 && e.revision_id == row.revision_id
614 && e.unit == row.unit
615 && e.owner_part == row.owner_part
616 && e.owner_revision == row.owner_revision
617 && e.occurrence_attributes == row.occurrence_attributes
618 }) {
619 existing.total += row.total;
620 existing.quantity = existing.total;
621 for id in row.occurrence_ids {
622 if !existing.occurrence_ids.contains(&id) {
623 existing.occurrence_ids.push(id);
624 }
625 }
626 } else {
627 row.level = 0;
628 row.position.clear();
629 row.quantity = row.total;
630 packed.push(row);
631 }
632 }
633 lines = packed;
634 }
635 for row in &mut lines {
636 crate::bom::reprice(state, row);
637 }
638 bom.flat = flat;
639 bom.lines = lines;
640 let mut totals: BTreeMap<String, (f64, usize)> = BTreeMap::new();
641 bom.unpriced = 0;
642 for line in &bom.lines {
643 if line.assembly {
644 continue;
645 }
646 if let Some(cost) = line.extended.filter(|_| line.costed) {
647 let t = totals.entry(line.currency.clone()).or_default();
648 t.0 += cost;
649 t.1 += 1;
650 } else {
651 bom.unpriced += 1;
652 }
653 }
654 bom.totals = totals
655 .into_iter()
656 .map(|(currency, (total, lines))| crate::bom::CurrencyTotal {
657 currency,
658 total,
659 lines,
660 })
661 .collect();
662 if !flat && bom.levels > 0 {
663 bom.lines.retain(|line| line.level <= bom.levels);
664 }
665}
666
667pub fn document_occurrences(document: &Value) -> Option<Vec<Occurrence>> {
668 let features = document.get("features")?.as_array()?;
669 let library = document.get("partsLibrary").and_then(Value::as_object);
670 let occurrences = features
671 .iter()
672 .filter(|feature| {
673 matches!(
674 feature["type"].as_str(),
675 Some("ACOMP") | Some("ASSEMBLY COMPONENT")
676 )
677 })
678 .filter_map(|feature| {
679 let params = &feature["inputParams"];
680 let id = params["id"].as_str()?.to_string();
681 let entry = library?.get(params["partName"].as_str()?)?;
682 let source = entry["sourceKey"]
683 .as_str()?
684 .strip_prefix("/models/")
685 .unwrap_or(entry["sourceKey"].as_str()?);
686 let source = [".nbrep", ".abrep", ".fbrep", ".tbrep", ".json"]
687 .iter()
688 .find_map(|suffix| source.strip_suffix(suffix))
689 .unwrap_or(source);
690 let (part, revision) = crate::identity::split_key(source)?;
691 let attributes = serde_json::from_value(
692 params
693 .get("bom")
694 .filter(|v| v.is_object())
695 .cloned()
696 .unwrap_or_else(|| json!({})),
697 )
698 .ok()?;
699 Some(Occurrence {
700 id,
701 part,
702 revision,
703 attributes,
704 })
705 })
706 .collect();
707 Some(occurrences)
708}
709
710pub fn synchronize_uses(revision: &mut Revision) {
711 for line in &mut revision.uses {
712 let occurrences: Vec<&Occurrence> = revision
713 .occurrences
714 .iter()
715 .filter(|o| {
716 o.part == line.part && (line.revision.is_empty() || o.revision == line.revision)
717 })
718 .collect();
719 if occurrences.is_empty() {
720 continue;
721 }
722 line.reference = occurrences
723 .iter()
724 .map(|o| {
725 o.attributes
726 .get("Reference_Designator")
727 .and_then(Value::as_str)
728 .filter(|s| !s.is_empty())
729 .unwrap_or(&o.id)
730 })
731 .collect::<Vec<_>>()
732 .join(", ");
733 let common = |key: &str| {
734 let first = occurrences[0]
735 .attributes
736 .get(key)
737 .and_then(Value::as_str)
738 .unwrap_or("");
739 if occurrences
740 .iter()
741 .all(|o| o.attributes.get(key).and_then(Value::as_str).unwrap_or("") == first)
742 {
743 first.to_string()
744 } else {
745 String::new()
746 }
747 };
748 line.find_number = common("Find_Number");
749 line.notes = common("Notes");
750 }
751}
752pub fn release_problems(
753 state: &State,
754 part: &crate::model::Part,
755 revision: &Revision,
756) -> Vec<String> {
757 let mut problems = Vec::new();
758 let mut check = |defs: &[AttributeDef], values: &BTreeMap<String, Value>, owner: &str| {
759 for def in defs {
760 match values.get(&def.key).map(|v| catalog::check_value(def, v)) {
761 Some(Ok(Some(_))) => {}
762 Some(Err(error)) => problems.push(format!("{owner}: {error}")),
763 _ if def.required => problems.push(format!("{owner}: {} is required", def.name)),
764 _ => {}
765 }
766 }
767 };
768 if let Some(defs) = state.bom_configuration.part_fields.get(&part.part_type) {
769 check(defs, &revision.attributes, "Revision attributes");
770 }
771 for occurrence in &revision.occurrences {
772 check(
773 &state.bom_configuration.occurrence_fields,
774 &occurrence.attributes,
775 &occurrence.id,
776 );
777 }
778 problems
779}
780
781pub fn layout_csv(bom: &crate::bom::Bom, layout: &Layout, fields: &[Field]) -> String {
782 fn cell(value: &str) -> String {
783 if value.contains([',', '"', '\n', '\r']) {
784 format!("\"{}\"", value.replace('"', "\"\""))
785 } else {
786 value.into()
787 }
788 }
789 let columns: Vec<&Field> = layout
790 .columns
791 .iter()
792 .filter_map(|id| fields.iter().find(|f| f.id == *id))
793 .collect();
794 let mut csv = columns
795 .iter()
796 .map(|f| cell(&f.name))
797 .collect::<Vec<_>>()
798 .join(",");
799 csv.push('\n');
800 for line in &bom.lines {
801 let builtins = serde_json::to_value(line).unwrap_or_default();
802 let cells = columns
803 .iter()
804 .map(|field| {
805 let value = if field.scope == "part" {
806 if field.part_type.as_deref() == Some(&line.part_type) {
807 line.part_values.get(&field.key)
808 } else {
809 None
810 }
811 } else if field.scope == "occurrence" && !field.id.starts_with("builtin.") {
812 line.occurrence_attributes.get(&field.key)
813 } else {
814 builtins.get(&field.key)
815 };
816 cell(&match value {
817 None | Some(Value::Null) => String::new(),
818 Some(Value::String(s)) => s.clone(),
819 Some(v) => v.to_string(),
820 })
821 })
822 .collect::<Vec<_>>()
823 .join(",");
824 csv.push_str(&cells);
825 csv.push('\n');
826 }
827 csv
828}