Skip to main content

brep_plm/
bom_config.rs

1//! Revision and occurrence fields and the BOM layouts shared by CAD and PLM.
2use 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    /// None is shared; otherwise this is a user's private configuration.
28    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/// The editable resource and payload key are part of the server field registry.
40#[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
204/// Overlay authoritative values onto a document. CAD saves cannot replace
205/// an attribute accepted from the other interface with a stale cached value.
206pub 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    /// Keep the model, revision metadata, hash and change feed together.
498    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
548/// Import the occurrence identities on CAD publish. Attribute changes for an
549/// existing identity arrive through the explicit edit API, never stale saves.
550pub 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        // Current CAD documents may carry custom occurrence values; validate configured fields.
582        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
598/// A configurable BOM exposes the actual placements. Packing includes all
599/// occurrence values, so changing the visible columns cannot merge distinct data.
600pub 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
667/// The uses list a CAD document implies (S5, derived on the server): one line
668/// per part revision its components place, in the order each first appears;
669/// `quantity` the count, `reference` the occurrences' reference designators
670/// (else their ids) joined by ", ", `unit` "each" — exactly the `{"uses":
671/// [...]}` body the CAD app sends to `PUT …/uses` (`plm::uses::uses_lines`).
672/// `None` for a document that publishes no list (a plain part: no component
673/// and no parts library). `Err` names every occurrence that places no PLM
674/// revision: the app publishes nothing then, and neither does the server.
675pub fn document_uses(document: &Value) -> Option<Result<Value, String>> {
676    let features = document.get("features")?.as_array()?;
677    let library = document.get("partsLibrary").and_then(Value::as_object);
678    let components: Vec<&Value> = features
679        .iter()
680        .filter(|feature| matches!(feature["type"].as_str(), Some("ACOMP") | Some("ASSEMBLY COMPONENT")))
681        .collect();
682    if components.is_empty() && library.is_none_or(|library| library.is_empty()) {
683        return None;
684    }
685    let mut lines: Vec<(String, String, u32, Vec<String>)> = Vec::new();
686    let mut refusals: Vec<String> = Vec::new();
687    for feature in components {
688        let params = &feature["inputParams"];
689        let id = params["id"].as_str().unwrap_or_default().to_string();
690        let designator = params["bom"]["Reference_Designator"].as_str().map(str::trim).unwrap_or_default();
691        let label = if designator.is_empty() { id.clone() } else { designator.to_string() };
692        let part_name = params["partName"].as_str().unwrap_or_default();
693        let Some(entry) = library.and_then(|library| library.get(part_name)) else {
694            refusals.push(format!("{label}: the document has no parts-library entry '{part_name}'"));
695            continue;
696        };
697        let key = entry["sourceKey"].as_str().unwrap_or_default();
698        if key.is_empty() {
699            refusals.push(format!("{label}: '{part_name}' is embedded in this document and was never a part — insert it from the PLM"));
700            continue;
701        }
702        let key = key.strip_prefix("/models/").unwrap_or(key);
703        let key = match key.rsplit_once('.') {
704            Some((stem, extension)) if !extension.contains('/') => stem,
705            _ => key,
706        };
707        let Some((part, revision)) = crate::identity::split_key(key) else {
708            refusals.push(format!("{label}: '{part_name}' is a local component without a PLM revision — import it into PLM first"));
709            continue;
710        };
711        match lines.iter_mut().find(|(p, r, _, _)| *p == part && *r == revision) {
712            Some(line) => {
713                line.2 += 1;
714                line.3.push(label);
715            }
716            None => lines.push((part, revision, 1, vec![label])),
717        }
718    }
719    if !refusals.is_empty() {
720        return Some(Err(format!(
721            "the uses list was not published — {} occurrence{} name{} no PLM revision: {}",
722            refusals.len(),
723            if refusals.len() == 1 { "" } else { "s" },
724            if refusals.len() == 1 { "s" } else { "" },
725            refusals.join("; ")
726        )));
727    }
728    let uses: Vec<Value> = lines
729        .into_iter()
730        .map(|(part, revision, quantity, labels)| {
731            json!({"part": part, "revision": revision, "quantity": quantity, "unit": "each", "find_number": "", "reference": labels.join(", "), "notes": ""})
732        })
733        .collect();
734    Some(Ok(json!({ "uses": uses })))
735}
736
737pub fn document_occurrences(document: &Value) -> Option<Vec<Occurrence>> {
738    let features = document.get("features")?.as_array()?;
739    let library = document.get("partsLibrary").and_then(Value::as_object);
740    let occurrences = features
741        .iter()
742        .filter(|feature| {
743            matches!(
744                feature["type"].as_str(),
745                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
746            )
747        })
748        .filter_map(|feature| {
749            let params = &feature["inputParams"];
750            let id = params["id"].as_str()?.to_string();
751            let entry = library?.get(params["partName"].as_str()?)?;
752            let source = entry["sourceKey"]
753                .as_str()?
754                .strip_prefix("/models/")
755                .unwrap_or(entry["sourceKey"].as_str()?);
756            let source = [".nbrep", ".abrep", ".fbrep", ".tbrep", ".json"]
757                .iter()
758                .find_map(|suffix| source.strip_suffix(suffix))
759                .unwrap_or(source);
760            let (part, revision) = crate::identity::split_key(source)?;
761            let attributes = serde_json::from_value(
762                params
763                    .get("bom")
764                    .filter(|v| v.is_object())
765                    .cloned()
766                    .unwrap_or_else(|| json!({})),
767            )
768            .ok()?;
769            Some(Occurrence {
770                id,
771                part,
772                revision,
773                attributes,
774            })
775        })
776        .collect();
777    Some(occurrences)
778}
779
780pub fn synchronize_uses(revision: &mut Revision) {
781    for line in &mut revision.uses {
782        let occurrences: Vec<&Occurrence> = revision
783            .occurrences
784            .iter()
785            .filter(|o| {
786                o.part == line.part && (line.revision.is_empty() || o.revision == line.revision)
787            })
788            .collect();
789        if occurrences.is_empty() {
790            continue;
791        }
792        line.reference = occurrences
793            .iter()
794            .map(|o| {
795                o.attributes
796                    .get("Reference_Designator")
797                    .and_then(Value::as_str)
798                    .filter(|s| !s.is_empty())
799                    .unwrap_or(&o.id)
800            })
801            .collect::<Vec<_>>()
802            .join(", ");
803        let common = |key: &str| {
804            let first = occurrences[0]
805                .attributes
806                .get(key)
807                .and_then(Value::as_str)
808                .unwrap_or("");
809            if occurrences
810                .iter()
811                .all(|o| o.attributes.get(key).and_then(Value::as_str).unwrap_or("") == first)
812            {
813                first.to_string()
814            } else {
815                String::new()
816            }
817        };
818        line.find_number = common("Find_Number");
819        line.notes = common("Notes");
820    }
821}
822pub fn release_problems(
823    state: &State,
824    part: &crate::model::Part,
825    revision: &Revision,
826) -> Vec<String> {
827    let mut problems = Vec::new();
828    let mut check = |defs: &[AttributeDef], values: &BTreeMap<String, Value>, owner: &str| {
829        for def in defs {
830            match values.get(&def.key).map(|v| catalog::check_value(def, v)) {
831                Some(Ok(Some(_))) => {}
832                Some(Err(error)) => problems.push(format!("{owner}: {error}")),
833                _ if def.required => problems.push(format!("{owner}: {} is required", def.name)),
834                _ => {}
835            }
836        }
837    };
838    if let Some(defs) = state.bom_configuration.part_fields.get(&part.part_type) {
839        check(defs, &revision.attributes, "Revision attributes");
840    }
841    for occurrence in &revision.occurrences {
842        check(
843            &state.bom_configuration.occurrence_fields,
844            &occurrence.attributes,
845            &occurrence.id,
846        );
847    }
848    problems
849}
850
851pub fn layout_csv(bom: &crate::bom::Bom, layout: &Layout, fields: &[Field]) -> String {
852    let columns: Vec<&Field> = layout
853        .columns
854        .iter()
855        .filter_map(|id| fields.iter().find(|f| f.id == *id))
856        .collect();
857    let mut csv = columns
858        .iter()
859        .map(|f| crate::bom::csv_cell(&f.name))
860        .collect::<Vec<_>>()
861        .join(",");
862    csv.push('\n');
863    for line in &bom.lines {
864        let builtins = serde_json::to_value(line).unwrap_or_default();
865        let cells = columns
866            .iter()
867            .map(|field| {
868                let value = if field.scope == "part" {
869                    if field.part_type.as_deref() == Some(&line.part_type) {
870                        line.part_values.get(&field.key)
871                    } else {
872                        None
873                    }
874                } else if field.scope == "occurrence" && !field.id.starts_with("builtin.") {
875                    line.occurrence_attributes.get(&field.key)
876                } else {
877                    builtins.get(&field.key)
878                };
879                crate::bom::csv_cell(&match value {
880                    None | Some(Value::Null) => String::new(),
881                    Some(Value::String(s)) => s.clone(),
882                    Some(v) => v.to_string(),
883                })
884            })
885            .collect::<Vec<_>>()
886            .join(",");
887        csv.push_str(&cells);
888        csv.push('\n');
889    }
890    csv
891}