Skip to main content

brep_plm/
bom.rs

1//! Assembly structure: the "uses" lists, and the BOM and where-used views
2//! computed from them.
3//!
4//! The CAD app publishes a revision's uses list on save and release
5//!; the server never reads geometry. Everything in
6//! this file is a pure function of [`State`]: checking a list before it is
7//! stored, walking it down into a bill of materials, walking it up into a
8//! where-used answer, and naming the children a release gate cares about.
9//!
10//! # What a reference means
11//!
12//! A [`Use`] names its child revision by id — PINNED — or leaves it empty —
13//! FLOATING, which reads as the child's current release, else its newest
14//! revision, at the moment the BOM is read. A floating reference stays
15//! floating after its parent releases: the released BOM follows the child's
16//! releases.
17//!
18//! # Cycles
19//!
20//! Checked at the PART level across every revision: a list may not name a
21//! part from which the parent part can be reached again through any
22//! revision's uses. That is stricter than a revision-level check, and it is
23//! what keeps a floating reference — which may resolve to any revision — from
24//! ever closing a loop.
25
26use std::collections::{BTreeMap, BTreeSet, HashMap};
27
28use serde::Serialize;
29use serde_json::Value;
30
31use crate::catalog;
32use crate::db::State;
33use crate::model::{Lifecycle, Part, Revision, Use};
34use crate::Error;
35
36/// How deep a BOM or where-used walk goes before it stops and says so. Cycles
37/// are refused on write, so only a store written before that check could
38/// reach this.
39pub const MAX_DEPTH: usize = 32;
40
41// ===========================================================================
42// Resolving a reference
43// ===========================================================================
44
45/// The revision a use points at: the pinned one, or for a floating use the
46/// child's current release, else its newest revision. `None` when a pinned
47/// revision no longer exists.
48pub fn resolve<'a>(part: &'a Part, line: &Use) -> Option<&'a Revision> {
49    if line.revision.is_empty() {
50        part.current_release().or(part.latest())
51    } else {
52        part.revision(&line.revision)
53    }
54}
55
56/// A revision of `part` named by id or by label.
57pub fn find_revision<'a>(part: &'a Part, key: &str) -> Option<&'a Revision> {
58    let key = key.trim();
59    part.revision(key).or_else(|| part.revision_by_label(key))
60}
61
62// ===========================================================================
63// Checking a list before it is stored
64// ===========================================================================
65
66/// Turn what a client sent into the list to store, or refuse it.
67///
68/// Accepts `{"uses": [...]}` or a bare list. Each line names its part by id or
69/// number and its revision by id or label (empty for floating); both are
70/// stored as ids. Refused: an unknown part or revision, the parent itself, a
71/// line that would close a cycle, a quantity that is not a positive number,
72/// and the same part, revision and find number listed twice.
73pub fn check_uses(state: &State, parent_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
74    let list = match body {
75        Value::Array(list) => list,
76        Value::Object(map) => map
77            .get("uses")
78            .and_then(Value::as_array)
79            .ok_or_else(|| Error::bad_request("send {\"uses\": [ ... ]} or a list"))?,
80        _ => return Err(Error::bad_request("send {\"uses\": [ ... ]} or a list")),
81    };
82    let parent = state.part(parent_id).ok_or_else(|| Error::not_found("part"))?;
83    let mut out: Vec<Use> = Vec::with_capacity(list.len());
84    for (index, raw) in list.iter().enumerate() {
85        let line = index + 1;
86        let fields = raw
87            .as_object()
88            .ok_or_else(|| Error::bad_request(format!("line {line} is not an object")))?;
89        for key in fields.keys() {
90            if !matches!(
91                key.as_str(),
92                "part" | "revision" | "quantity" | "unit" | "find_number" | "reference" | "notes"
93            ) {
94                return Err(Error::bad_request(format!(
95                    "line {line}: '{key}' is not a field of a use — part, revision, quantity, unit, find_number, reference, notes"
96                )));
97            }
98        }
99        let text = |key: &str| -> Result<String, Error> {
100            match fields.get(key) {
101                None | Some(Value::Null) => Ok(String::new()),
102                Some(Value::String(s)) => Ok(s.trim().to_string()),
103                Some(Value::Number(n)) => Ok(n.to_string()),
104                Some(_) => Err(Error::bad_request(format!("line {line}: {key} must be text"))),
105            }
106        };
107        let part_key = text("part")?;
108        if part_key.is_empty() {
109            return Err(Error::bad_request(format!("line {line} names no part")));
110        }
111        let child = state
112            .part_by_id_or_number(&part_key)
113            .ok_or_else(|| Error::bad_request(format!("line {line}: there is no part '{part_key}'")))?;
114        if child.id == parent.id {
115            return Err(Error::bad_request(format!(
116                "line {line}: {} cannot use itself",
117                parent.number
118            )));
119        }
120        let revision_key = text("revision")?;
121        let revision = if revision_key.is_empty() {
122            String::new()
123        } else {
124            find_revision(child, &revision_key)
125                .map(|r| r.id.clone())
126                .ok_or_else(|| {
127                    Error::bad_request(format!(
128                        "line {line}: {} has no revision '{revision_key}'",
129                        child.number
130                    ))
131                })?
132        };
133        let quantity = match fields.get("quantity") {
134            None | Some(Value::Null) => 1.0,
135            Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN),
136            Some(Value::String(s)) if s.trim().is_empty() => 1.0,
137            Some(Value::String(s)) => s.trim().parse::<f64>().unwrap_or(f64::NAN),
138            Some(_) => f64::NAN,
139        };
140        if !quantity.is_finite() || quantity <= 0.0 {
141            return Err(Error::bad_request(format!(
142                "line {line}: the quantity of {} must be a number above zero",
143                child.number
144            )));
145        }
146        let unit = text("unit")?;
147        let entry = Use {
148            part: child.id.clone(),
149            revision,
150            quantity,
151            unit: if unit.is_empty() { "each".to_string() } else { unit },
152            find_number: text("find_number")?,
153            reference: text("reference")?,
154            notes: text("notes")?,
155        };
156        if let Some(same) = out.iter().position(|u| {
157            u.part == entry.part && u.revision == entry.revision && u.find_number == entry.find_number
158        }) {
159            return Err(Error::bad_request(format!(
160                "line {line} repeats line {} ({}) — give one line its count as the quantity, or a different find number",
161                same + 1,
162                child.number
163            )));
164        }
165        out.push(entry);
166    }
167    for entry in &out {
168        if let Some(path) = path_to(state, &entry.part, &parent.id) {
169            let names: Vec<String> = path
170                .iter()
171                .map(|id| state.part(id).map(|p| p.number.clone()).unwrap_or_else(|| id.clone()))
172                .collect();
173            return Err(Error::conflict(format!(
174                "{} cannot use {}: that would make a cycle ({} → {})",
175                parent.number,
176                names[0],
177                parent.number,
178                names.join(" → ")
179            )));
180        }
181    }
182    Ok(out)
183}
184
185/// A chain of part ids from `from` to `to` through any revision's uses, if
186/// one exists. Breadth-first, so the chain named in a refusal is the
187/// shortest.
188pub fn path_to(state: &State, from: &str, to: &str) -> Option<Vec<String>> {
189    let mut previous: BTreeMap<String, String> = BTreeMap::new();
190    let mut seen: BTreeSet<String> = BTreeSet::from([from.to_string()]);
191    let mut queue = std::collections::VecDeque::from([from.to_string()]);
192    while let Some(id) = queue.pop_front() {
193        if id == to {
194            let mut path = vec![id.clone()];
195            let mut at = id;
196            while let Some(back) = previous.get(&at) {
197                path.push(back.clone());
198                at = back.clone();
199            }
200            path.reverse();
201            return Some(path);
202        }
203        let Some(part) = state.part(&id) else { continue };
204        for child in part.revisions.iter().flat_map(|r| &r.uses).map(|u| &u.part) {
205            if seen.insert(child.clone()) {
206                previous.insert(child.clone(), id.clone());
207                queue.push_back(child.clone());
208            }
209        }
210    }
211    None
212}
213
214// ===========================================================================
215// The release gate
216// ===========================================================================
217
218/// One sentence per child of `revision` that is not Released — what
219/// [`crate::model::Settings::require_released_children`] refuses on, and what
220/// a release warns about when that setting is off. Empty when every child is
221/// released (or the revision uses nothing).
222pub fn unreleased_children(state: &State, revision: &Revision) -> Vec<String> {
223    let mut out = Vec::new();
224    for line in &revision.uses {
225        let Some(child) = state.part(&line.part) else {
226            out.push(format!("a used part ({}) no longer exists", line.part));
227            continue;
228        };
229        match resolve(child, line) {
230            None => out.push(format!("{}: the revision it names no longer exists", child.number)),
231            Some(_) if line.revision.is_empty() && child.current_release().is_none() => {
232                out.push(format!("{} has no released revision", child.number))
233            }
234            Some(rev) if rev.lifecycle != Lifecycle::Released => {
235                out.push(format!("{} rev {} is {}", child.number, rev.label, rev.lifecycle.as_str()))
236            }
237            Some(_) => {}
238        }
239    }
240    out
241}
242
243/// The uses list with each child resolved to what a person reads — the
244/// `uses` a release hook receives.
245pub fn resolved_uses(state: &State, revision: &Revision) -> Value {
246    Value::Array(
247        revision
248            .uses
249            .iter()
250            .map(|line| {
251                let child = state.part(&line.part);
252                let rev = child.and_then(|c| resolve(c, line));
253                serde_json::json!({
254                    "part": line.part,
255                    "number": child.map(|c| c.number.clone()).unwrap_or_default(),
256                    "name": child.map(|c| c.name.clone()).unwrap_or_default(),
257                    "revision": rev.map(|r| r.id.clone()).unwrap_or_default(),
258                    "revision_label": rev.map(|r| r.label.clone()).unwrap_or_default(),
259                    "state": rev.map(|r| r.lifecycle.as_str()).unwrap_or(""),
260                    "floating": line.revision.is_empty(),
261                    "quantity": line.quantity,
262                    "unit": line.unit,
263                    "find_number": line.find_number,
264                    "reference": line.reference,
265                    "notes": line.notes,
266                })
267            })
268            .collect(),
269    )
270}
271
272// ===========================================================================
273// The bill of materials
274// ===========================================================================
275
276/// One line of a BOM. In the indented view it is one use at one place in the
277/// tree; in the flat view it is every occurrence of one part revision (and
278/// unit) added up.
279#[derive(Debug, Clone, Serialize)]
280pub struct BomLine {
281    pub part_type: String,
282    pub part_values: BTreeMap<String, Value>,
283    pub occurrence_values: Vec<crate::bom_config::Occurrence>,
284    pub owner_part: String,
285    pub owner_revision: String,
286    pub occurrence_ids: Vec<String>,
287    pub occurrence_attributes: BTreeMap<String, Value>,
288    /// Depth below the top: 1 for what the top uses directly. 0 in the flat
289    /// view.
290    pub level: usize,
291    /// `1.2.3` — the line's place in the tree. Empty in the flat view.
292    pub position: String,
293    pub find_number: String,
294    pub reference: String,
295    pub notes: String,
296    pub part_id: String,
297    pub number: String,
298    pub name: String,
299    pub revision_id: String,
300    pub revision_label: String,
301    /// The resolved revision's state; empty when it no longer exists.
302    pub state: String,
303    /// The use names no revision; this one is what it resolves to now.
304    pub floating: bool,
305    pub category_path: String,
306    /// The part's catalog values as "Name: value unit", schema order.
307    pub attributes: Vec<String>,
308    /// How many per ONE parent. In the flat view, the same as `total`.
309    pub quantity: f64,
310    pub unit: String,
311    /// How many for ONE of the top part: the quantities along the path
312    /// multiplied, and in the flat view summed over every path.
313    pub total: f64,
314    /// This part revision uses something itself.
315    pub assembly: bool,
316    /// The preferred manufacturer part number, else the first; empty with no
317    /// sourcing.
318    pub mpn: String,
319    pub manufacturer: String,
320    /// The offer priced here: the cheapest of the MPN's offers at `total`.
321    pub supplier: String,
322    pub spn: String,
323    pub currency: String,
324    /// Each, at `total` — the price break `total` reaches, or the first break
325    /// when `total` is below it (the least a supplier sells).
326    pub unit_price: Option<f64>,
327    /// `unit_price × total`.
328    pub extended: Option<f64>,
329    /// Counted in the totals: a priced line with nothing beneath it. An
330    /// assembly's own price is shown but its children are what is bought.
331    pub costed: bool,
332    pub warnings: Vec<String>,
333    /// One short word per warning, in the same order, for a chip in a table
334    /// row: `unreleased`, `superseded`, `obsolete`, `no release`, `missing`,
335    /// `bake`, `cycle`, `too deep`.
336    pub flags: Vec<String>,    /// The files on the part and on the resolved revision, by name (part
337    /// files first) — a drawing to hand the shop with the list.
338    pub attachments: Vec<String>,
339}
340
341/// A currency and what the costed lines in it add up to. Currencies are
342/// never added to each other.
343#[derive(Debug, Clone, Serialize)]
344pub struct CurrencyTotal {
345    pub currency: String,
346    pub total: f64,
347    pub lines: usize,
348}
349
350#[derive(Debug, Clone, Serialize)]
351pub struct Bom {
352    #[serde(skip_serializing_if="Option::is_none")]
353    pub comparison_lines: Option<Vec<BomLine>>,
354    pub part_id: String,
355    pub number: String,
356    pub name: String,
357    pub revision_id: String,
358    pub revision_label: String,
359    pub state: String,
360    pub flat: bool,
361    /// The depth shown in the indented view; 0 is every level. Totals are
362    /// always over the whole tree.
363    pub levels: usize,
364    pub lines: Vec<BomLine>,
365    pub totals: Vec<CurrencyTotal>,
366    /// Lines with nothing beneath them and no price — what the totals miss.
367    pub unpriced: usize,
368    /// Every line's warnings, prefixed with the line's part and revision,
369    /// once each.
370    pub warnings: Vec<String>,
371}
372
373/// How a walk reached a line.
374struct Walked<'a> {
375    parent_revision: &'a Revision,
376    parent_part: String,
377    level: usize,
378    position: String,
379    line: &'a Use,
380    child: Option<&'a Part>,
381    revision: Option<&'a Revision>,
382    total: f64,
383    /// Where the walk stopped instead of descending.
384    stop: Option<String>,
385}
386
387/// Walk the whole tree beneath `revision`, depth-first in list order.
388fn walk<'a>(state: &'a State, top: &'a Part, revision: &'a Revision) -> Vec<Walked<'a>> {
389    let mut out = Vec::new();
390    let mut path = vec![top.id.clone()];
391    descend(state, revision, 1, "", 1.0, &mut path, &mut out);
392    out
393}
394
395fn descend<'a>(
396    state: &'a State,
397    revision: &'a Revision,
398    level: usize,
399    prefix: &str,
400    multiplier: f64,
401    path: &mut Vec<String>,
402    out: &mut Vec<Walked<'a>>,
403) {
404    for (index, line) in revision.uses.iter().enumerate() {
405        let position = if prefix.is_empty() {
406            format!("{}", index + 1)
407        } else {
408            format!("{prefix}.{}", index + 1)
409        };
410        let child = state.part(&line.part);
411        let resolved = child.and_then(|c| resolve(c, line));
412        let total = multiplier * line.quantity;
413        let mut stop = None;
414        if child.is_some_and(|c| path.contains(&c.id)) {
415            stop = Some("cycle: this part is already above it — not expanded".to_string());
416        } else if level >= MAX_DEPTH && resolved.is_some_and(|r| !r.uses.is_empty()) {
417            stop = Some(format!("deeper than {MAX_DEPTH} levels — not expanded"));
418        }
419        let expand = stop.is_none();
420        out.push(Walked {
421            parent_revision: revision,
422            parent_part: path.last().cloned().unwrap_or_default(), level, position: position.clone(), line, child, revision: resolved, total, stop });
423        if expand {
424            if let (Some(child), Some(rev)) = (child, resolved) {
425                if !rev.uses.is_empty() {
426                    path.push(child.id.clone());
427                    descend(state, rev, level + 1, &position, total, path, out);
428                    path.pop();
429                }
430            }
431        }
432    }
433}
434
435/// The price of `part` at `quantity`: the preferred MPN (else the first), and
436/// among its offers the cheapest at that quantity. Offers in another currency
437/// than the first priced offer's are not compared with it.
438fn price(state: &State, part: &Part, quantity: f64) -> Option<(String, String, String, String, String, f64)> {
439    let mp = part.sourcing.iter().find(|m| m.preferred).or(part.sourcing.first())?;
440    let manufacturer = crate::sourcing::find_company(&state.manufacturers, &mp.manufacturer)
441        .map(|c| c.name.clone())
442        .unwrap_or_default();
443    let mut best: Option<(&crate::model::SupplierOffer, f64)> = None;
444    for offer in &mp.offers {
445        let mut breaks: Vec<_> = offer.price_breaks.iter().collect();
446        breaks.sort_by_key(|b| b.qty);
447        let Some(first) = breaks.first() else { continue };
448        let unit = breaks
449            .iter()
450            .rev()
451            .find(|b| (b.qty as f64) <= quantity)
452            .map(|b| b.unit_price)
453            .unwrap_or(first.unit_price);
454        match best {
455            Some((held, _)) if held.currency != offer.currency => {}
456            Some((_, cheapest)) if cheapest <= unit => {}
457            _ => best = Some((offer, unit)),
458        }
459    }
460    let (mpn, manufacturer) = (mp.mpn.clone(), manufacturer);
461    match best {
462        Some((offer, unit)) => {
463            let supplier = crate::sourcing::find_company(&state.suppliers, &offer.supplier)
464                .map(|c| c.name.clone())
465                .unwrap_or_default();
466            Some((mpn, manufacturer, supplier, offer.spn.clone(), offer.currency.clone(), unit))
467        }
468        None => Some((mpn, manufacturer, String::new(), String::new(), String::new(), f64::NAN)),
469    }
470}
471
472/// The part's catalog values as "Name: value unit", in schema order.
473fn attribute_texts(state: &State, part: &Part) -> Vec<String> {
474    let Some(category) = catalog::find(&state.categories, &part.category) else {
475        return Vec::new();
476    };
477    let Ok(schema) = catalog::schema(&state.categories, &category.id) else {
478        return Vec::new();
479    };
480    schema
481        .iter()
482        .filter_map(|e| {
483            let value = part.attributes.get(&e.def.key)?;
484            let text = match value {
485                Value::String(s) => s.clone(),
486                Value::Bool(true) => "yes".into(),
487                Value::Bool(false) => "no".into(),
488                other => other.to_string(),
489            };
490            let unit = match &e.def.kind {
491                crate::model::AttributeKind::Number { unit } if !unit.is_empty() => format!(" {unit}"),
492                _ => String::new(),
493            };
494            Some(format!("{}: {text}{unit}", e.def.name))
495        })
496        .collect()
497}
498
499/// What is wrong with the revision a line resolved to: a short flag and the
500/// sentence a person reads.
501fn line_warnings(child: Option<&Part>, line: &Use, resolved: Option<&Revision>) -> Vec<(&'static str, String)> {
502    let mut out = Vec::new();
503    let Some(child) = child else {
504        out.push(("missing", "the part no longer exists".to_string()));
505        return out;
506    };
507    let Some(rev) = resolved else {
508        out.push(("missing", "the revision it names no longer exists".to_string()));
509        return out;
510    };
511    let current = child.current_release();
512    let current_text = match current {
513        Some(c) => format!("{} is current", c.label),
514        None => "nothing is released now".to_string(),
515    };
516    match rev.lifecycle {
517        Lifecycle::Released => {}
518        Lifecycle::Superseded => out.push(("superseded", format!("uses superseded rev {}; {current_text}", rev.label))),
519        Lifecycle::Obsolete => out.push(("obsolete", format!("uses obsolete rev {}; {current_text}", rev.label))),
520        Lifecycle::Draft | Lifecycle::InReview if line.revision.is_empty() => out.push((
521            "no release",
522            format!(
523                "floating, and {} has no released revision — showing its newest, {} ({})",
524                child.number,
525                rev.label,
526                rev.lifecycle.as_str()
527            ),
528        )),
529        Lifecycle::Draft | Lifecycle::InReview => {
530            out.push(("unreleased", format!("unreleased: rev {} is {}", rev.label, rev.lifecycle.as_str())))
531        }
532    }
533    if rev.needs_bake() {
534        out.push(("bake", format!("rev {} is waiting for a bake", rev.label)));
535    }
536    out
537}
538
539/// The BOM of `revision` of `top`. `levels` limits the indented view's depth
540/// (0 = all); `flat` adds every occurrence of each part revision together.
541pub fn bom(state: &State, top: &Part, revision: &Revision, levels: usize, flat: bool) -> Bom {
542    let walked = walk(state, top, revision);
543    let mut lines: Vec<BomLine> = Vec::new();
544    if flat {
545        // Key: part, revision, unit — a part bought in two units stays two
546        // lines rather than adding millimetres to pieces.
547        let mut index: BTreeMap<(String, String, String), usize> = BTreeMap::new();
548        for w in &walked {
549            let key = (
550                w.line.part.clone(),
551                w.revision.map(|r| r.id.clone()).unwrap_or_default(),
552                w.line.unit.clone(),
553            );
554            match index.get(&key) {
555                Some(&at) => {
556                    let line = &mut lines[at];
557                    line.total += w.total;
558                    line.quantity = line.total;
559                    if !w.line.find_number.is_empty() && !line.find_number.split(", ").any(|f| f == w.line.find_number) {
560                        if !line.find_number.is_empty() {
561                            line.find_number.push_str(", ");
562                        }
563                        line.find_number.push_str(&w.line.find_number);
564                    }
565                    if !w.line.reference.is_empty() {
566                        if !line.reference.is_empty() {
567                            line.reference.push_str(", ");
568                        }
569                        line.reference.push_str(&w.line.reference);
570                    }
571                    if let Some(stop) = &w.stop {
572                        if !line.warnings.contains(stop) {
573                            line.warnings.push(stop.clone());
574                            line.flags.push(if stop.starts_with("cycle") { "cycle" } else { "too deep" }.to_string());
575                        }
576                    }
577                }
578                None => {
579                    index.insert(key, lines.len());
580                    let mut line = make_line(state, w);
581                    line.level = 0;
582                    line.position.clear();
583                    line.quantity = line.total;
584                    lines.push(line);
585                }
586            }
587        }
588        // Priced at the total bought.
589        for line in &mut lines {
590            reprice(state, line);
591        }
592        lines.sort_by(|a, b| a.number.to_ascii_lowercase().cmp(&b.number.to_ascii_lowercase()).then(a.revision_label.cmp(&b.revision_label)));
593    } else {
594        for w in &walked {
595            let mut line = make_line(state, w);
596            reprice(state, &mut line);
597            lines.push(line);
598        }
599    }
600
601    let mut totals: BTreeMap<String, (f64, usize)> = BTreeMap::new();
602    let mut unpriced = 0;
603    for line in &lines {
604        if line.assembly {
605            continue;
606        }
607        match line.extended {
608            Some(extended) if line.costed => {
609                let slot = totals.entry(line.currency.clone()).or_insert((0.0, 0));
610                slot.0 += extended;
611                slot.1 += 1;
612            }
613            _ => unpriced += 1,
614        }
615    }
616    let mut warnings: Vec<String> = Vec::new();
617    for line in &lines {
618        for warning in &line.warnings {
619            let text = format!("{} rev {}: {warning}", line.number, if line.revision_label.is_empty() { "?" } else { &line.revision_label });
620            if !warnings.contains(&text) {
621                warnings.push(text);
622            }
623        }
624    }
625    if !flat && levels > 0 {
626        lines.retain(|line| line.level <= levels);
627    }
628    Bom {
629        comparison_lines: None,
630        part_id: top.id.clone(),
631        number: top.number.clone(),
632        name: top.name.clone(),
633        revision_id: revision.id.clone(),
634        revision_label: revision.label.clone(),
635        state: revision.lifecycle.as_str().to_string(),
636        flat,
637        levels,
638        lines,
639        totals: totals
640            .into_iter()
641            .map(|(currency, (total, lines))| CurrencyTotal { currency, total, lines })
642            .collect(),
643        unpriced,
644        warnings,
645    }
646}
647
648fn make_line(state: &State, w: &Walked) -> BomLine {
649    let child = w.child;
650    let mut found = line_warnings(child, w.line, w.revision);
651    if let Some(stop) = &w.stop {
652        found.push((if stop.starts_with("cycle") { "cycle" } else { "too deep" }, stop.clone()));
653    }
654    let flags = found.iter().map(|(flag, _)| flag.to_string()).collect();
655    let warnings = found.into_iter().map(|(_, text)| text).collect();
656    BomLine {
657        part_type: child.map(|p|p.part_type.clone()).unwrap_or_default(),
658        part_values: w.revision.map(|r|r.attributes.clone()).unwrap_or_default(),
659        occurrence_values: w.parent_revision.occurrences.iter().filter(|o|o.part==w.line.part && (w.line.revision.is_empty() || o.revision==w.line.revision)).cloned().collect(),
660        owner_part: w.parent_part.clone(),
661        owner_revision: w.parent_revision.id.clone(),
662        occurrence_ids: Vec::new(),
663        occurrence_attributes: BTreeMap::new(),
664        level: w.level,
665        position: w.position.clone(),
666        find_number: w.line.find_number.clone(),
667        reference: w.line.reference.clone(),
668        notes: w.line.notes.clone(),
669        part_id: w.line.part.clone(),
670        number: child.map(|c| c.number.clone()).unwrap_or_else(|| "(removed part)".into()),
671        name: child.map(|c| c.name.clone()).unwrap_or_default(),
672        revision_id: w.revision.map(|r| r.id.clone()).unwrap_or_default(),
673        revision_label: w.revision.map(|r| r.label.clone()).unwrap_or_default(),
674        state: w.revision.map(|r| r.lifecycle.as_str().to_string()).unwrap_or_default(),
675        floating: w.line.revision.is_empty(),
676        category_path: child.map(|c| catalog::path_name(&state.categories, &c.category)).unwrap_or_default(),
677        attributes: child.map(|c| attribute_texts(state, c)).unwrap_or_default(),
678        quantity: w.line.quantity,
679        unit: w.line.unit.clone(),
680        total: w.total,
681        assembly: w.revision.is_some_and(|r| !r.uses.is_empty()),
682        mpn: String::new(),
683        manufacturer: String::new(),
684        supplier: String::new(),
685        spn: String::new(),
686        currency: String::new(),
687        unit_price: None,
688        extended: None,
689        costed: false,
690        warnings,
691        flags,
692        attachments: child
693            .map(|c| c.attachments.iter().map(|a| a.name.clone()).collect::<Vec<_>>())
694            .unwrap_or_default()
695            .into_iter()
696            .chain(w.revision.map(|r| r.attachments.iter().map(|a| a.name.clone()).collect::<Vec<_>>()).unwrap_or_default())
697            .collect(),
698    }
699}
700
701/// Fill a line's sourcing and price at its `total`.
702pub(crate) fn reprice(state: &State, line: &mut BomLine) {
703    let Some(part) = state.part(&line.part_id) else { return };
704    let Some((mpn, manufacturer, supplier, spn, currency, unit)) = price(state, part, line.total) else {
705        return;
706    };
707    line.mpn = mpn;
708    line.manufacturer = manufacturer;
709    line.supplier = supplier;
710    line.spn = spn;
711    line.currency = currency;
712    if unit.is_finite() {
713        line.unit_price = Some(unit);
714        line.extended = Some(unit * line.total);
715        line.costed = !line.assembly;
716    }
717}
718
719// ===========================================================================
720// Comparing two revisions' lists
721// ===========================================================================
722
723/// One side of a diff line: what one revision's list says about one part.
724#[derive(Debug, Clone, Serialize, PartialEq)]
725pub struct DiffSide {
726    pub quantity: f64,
727    pub unit: String,
728    /// The revision labels the lines name, `floating` for a floating line.
729    pub revisions: Vec<String>,
730    pub find_numbers: Vec<String>,
731}
732
733#[derive(Debug, Clone, Serialize)]
734pub struct DiffLine {
735    pub part_id: String,
736    pub number: String,
737    pub name: String,
738    /// `added`, `removed` or `changed`.
739    pub change: &'static str,
740    pub from: Option<DiffSide>,
741    pub to: Option<DiffSide>,
742    /// "quantity 2 → 4", "revision B → C", "find number 3 → 5".
743    pub details: Vec<String>,
744}
745
746#[derive(Debug, Clone, Serialize)]
747pub struct BomDiff {
748    pub part_id: String,
749    pub number: String,
750    pub from_revision: String,
751    pub to_revision: String,
752    pub lines: Vec<DiffLine>,
753    /// Parts whose lines are the same in both.
754    pub unchanged: usize,
755}
756
757fn sides(state: &State, revision: &Revision) -> BTreeMap<String, DiffSide> {
758    let mut out: BTreeMap<String, DiffSide> = BTreeMap::new();
759    for line in &revision.uses {
760        let label = if line.revision.is_empty() {
761            "floating".to_string()
762        } else {
763            state
764                .part(&line.part)
765                .and_then(|p| p.revision(&line.revision))
766                .map(|r| r.label.clone())
767                .unwrap_or_else(|| "(deleted)".into())
768        };
769        let side = out.entry(line.part.clone()).or_insert_with(|| DiffSide {
770            quantity: 0.0,
771            unit: line.unit.clone(),
772            revisions: Vec::new(),
773            find_numbers: Vec::new(),
774        });
775        side.quantity += line.quantity;
776        if side.unit != line.unit && !side.unit.contains(&line.unit) {
777            side.unit = format!("{}, {}", side.unit, line.unit);
778        }
779        if !side.revisions.contains(&label) {
780            side.revisions.push(label);
781        }
782        if !line.find_number.is_empty() && !side.find_numbers.contains(&line.find_number) {
783            side.find_numbers.push(line.find_number.clone());
784        }
785    }
786    for side in out.values_mut() {
787        side.revisions.sort();
788        side.find_numbers.sort();
789    }
790    out
791}
792
793/// What changed in the uses list from `from` to `to`, one level, part by
794/// part.
795pub fn diff(state: &State, part: &Part, from: &Revision, to: &Revision) -> BomDiff {
796    let a = sides(state, from);
797    let b = sides(state, to);
798    let keys: BTreeSet<&String> = a.keys().chain(b.keys()).collect();
799    let mut lines = Vec::new();
800    let mut unchanged = 0;
801    for key in keys {
802        let child = state.part(key);
803        let (number, name) = child
804            .map(|c| (c.number.clone(), c.name.clone()))
805            .unwrap_or_else(|| ("(removed part)".into(), String::new()));
806        let (before, after) = (a.get(key), b.get(key));
807        let (change, details) = match (before, after) {
808            (None, Some(s)) => ("added", vec![format!("{} {}", qty(s.quantity), s.unit)]),
809            (Some(s), None) => ("removed", vec![format!("{} {}", qty(s.quantity), s.unit)]),
810            (Some(x), Some(y)) if x == y => {
811                unchanged += 1;
812                continue;
813            }
814            (Some(x), Some(y)) => {
815                let mut details = Vec::new();
816                if x.quantity != y.quantity || x.unit != y.unit {
817                    details.push(format!("quantity {} {} → {} {}", qty(x.quantity), x.unit, qty(y.quantity), y.unit));
818                }
819                if x.revisions != y.revisions {
820                    details.push(format!("revision {} → {}", x.revisions.join(", "), y.revisions.join(", ")));
821                }
822                if x.find_numbers != y.find_numbers {
823                    let show = |f: &Vec<String>| if f.is_empty() { "none".to_string() } else { f.join(", ") };
824                    details.push(format!("find number {} → {}", show(&x.find_numbers), show(&y.find_numbers)));
825                }
826                ("changed", details)
827            }
828            (None, None) => continue,
829        };
830        lines.push(DiffLine {
831            part_id: key.clone(),
832            number,
833            name,
834            change,
835            from: before.cloned(),
836            to: after.cloned(),
837            details,
838        });
839    }
840    lines.sort_by(|x, y| x.number.to_ascii_lowercase().cmp(&y.number.to_ascii_lowercase()));
841    BomDiff {
842        part_id: part.id.clone(),
843        number: part.number.clone(),
844        from_revision: from.label.clone(),
845        to_revision: to.label.clone(),
846        lines,
847        unchanged,
848    }
849}
850
851/// A quantity as a person writes it: `4`, not `4.0`.
852pub fn qty(value: f64) -> String {
853    if value.fract() == 0.0 && value.abs() < 1e15 {
854        format!("{}", value as i64)
855    } else {
856        format!("{value}")
857    }
858}
859
860// ===========================================================================
861// Where-used
862// ===========================================================================
863
864#[derive(Debug, Clone, Serialize)]
865pub struct WhereUsedLine {
866    /// 1 for a direct parent, 2 for its parents, and so on.
867    pub level: usize,
868    pub part_id: String,
869    pub number: String,
870    pub name: String,
871    pub revision_id: String,
872    pub revision_label: String,
873    pub state: String,
874    /// The parent revision is the part's current release, or in work — the
875    /// ones a replacement would still have to touch. A superseded or obsolete
876    /// parent is history.
877    pub current: bool,
878    /// The child revision this use points at: its label, or
879    /// `floating → <label>` for a floating use.
880    pub uses_revision: String,
881    pub floating: bool,
882    pub quantity: f64,
883    pub unit: String,
884    pub find_number: String,
885    /// Nothing uses this parent revision in turn: a top-level assembly.
886    pub top: bool,
887}
888
889#[derive(Debug, Clone, Serialize)]
890pub struct WhereUsed {
891    pub part_id: String,
892    pub number: String,
893    /// The revision asked about, or empty for any revision.
894    pub revision_label: String,
895    /// 0 is every level up.
896    pub levels: usize,
897    pub lines: Vec<WhereUsedLine>,
898}
899
900/// Every uses-list line in the store, by the part it names: built once per
901/// where-used question, in one pass, so climbing a level looks up its
902/// parents instead of scanning every part again. In store order, so the
903/// answer's order is the one a scan gives.
904type UsedBy<'a> = HashMap<&'a str, Vec<(&'a Part, &'a Revision, &'a Use)>>;
905
906fn used_by(state: &State) -> UsedBy<'_> {
907    let mut index: UsedBy<'_> = HashMap::new();
908    for parent in &state.parts {
909        for rev in &parent.revisions {
910            for line in &rev.uses {
911                index.entry(line.part.as_str()).or_default().push((parent, rev, line));
912            }
913        }
914    }
915    index
916}
917
918/// Every revision that uses `part` — `revision` of it when one is given, a
919/// floating use counting when it resolves to that revision now.
920fn parents<'a>(
921    index: &UsedBy<'a>,
922    part: &'a Part,
923    revision: Option<&'a Revision>,
924) -> Vec<(&'a Part, &'a Revision, &'a Use, Option<&'a Revision>)> {
925    let Some(lines) = index.get(part.id.as_str()) else { return Vec::new() };
926    lines
927        .iter()
928        .filter_map(|&(parent, rev, line)| {
929            let resolved = resolve(part, line);
930            let hit = match revision {
931                None => true,
932                Some(wanted) => resolved.is_some_and(|r| r.id == wanted.id),
933            };
934            hit.then_some((parent, rev, line, resolved))
935        })
936        .collect()
937}
938
939/// Where `part` (or one revision of it) is used, up to `levels` levels (0 =
940/// all the way to the top).
941pub fn where_used(state: &State, part: &Part, revision: Option<&Revision>, levels: usize) -> WhereUsed {
942    let index = used_by(state);
943    let mut lines = Vec::new();
944    let mut path = vec![part.id.clone()];
945    climb(&index, part, revision, 1, levels, &mut path, &mut lines);
946    WhereUsed {
947        part_id: part.id.clone(),
948        number: part.number.clone(),
949        revision_label: revision.map(|r| r.label.clone()).unwrap_or_default(),
950        levels,
951        lines,
952    }
953}
954
955fn climb<'a>(
956    index: &UsedBy<'a>,
957    part: &'a Part,
958    revision: Option<&'a Revision>,
959    level: usize,
960    levels: usize,
961    path: &mut Vec<String>,
962    out: &mut Vec<WhereUsedLine>,
963) {
964    for (parent, rev, line, resolved) in parents(index, part, revision) {
965        let top = parents(index, parent, Some(rev)).is_empty();
966        let label = resolved.map(|r| r.label.clone()).unwrap_or_else(|| "(deleted)".into());
967        out.push(WhereUsedLine {
968            level,
969            part_id: parent.id.clone(),
970            number: parent.number.clone(),
971            name: parent.name.clone(),
972            revision_id: rev.id.clone(),
973            revision_label: rev.label.clone(),
974            state: rev.lifecycle.as_str().to_string(),
975            current: rev.lifecycle.is_editable() || rev.lifecycle == Lifecycle::Released,
976            uses_revision: if line.revision.is_empty() { format!("floating → {label}") } else { label },
977            floating: line.revision.is_empty(),
978            quantity: line.quantity,
979            unit: line.unit.clone(),
980            find_number: line.find_number.clone(),
981            top,
982        });
983        let deeper = levels == 0 || level < levels;
984        if deeper && !top && level < MAX_DEPTH && !path.contains(&parent.id) {
985            path.push(parent.id.clone());
986            climb(index, parent, Some(rev), level + 1, levels, path, out);
987            path.pop();
988        }
989    }
990}
991
992// ===========================================================================
993// CSV
994// ===========================================================================
995
996/// One CSV cell: quoted (inner quotes doubled) when it holds a comma, a quote
997/// or a line break. The ONE quoting rule for every CSV the server writes (BOM,
998/// BOM layouts, the audit export, the backup's parts and files lists).
999pub(crate) fn csv_cell(text: &str) -> String {
1000    if text.contains([',', '"', '\n', '\r']) {
1001        format!("\"{}\"", text.replace('"', "\"\""))
1002    } else {
1003        text.to_string()
1004    }
1005}
1006
1007fn money(value: Option<f64>) -> String {
1008    value.map(|v| format!("{v:.4}").trim_end_matches('0').trim_end_matches('.').to_string()).unwrap_or_default()
1009}
1010
1011/// The BOM as CSV, one row per line, the indented view with its level and
1012/// position columns, the flat view without them. Totals follow as rows of
1013/// their own.
1014pub fn bom_csv(bom: &Bom) -> String {
1015    bom_csv_with(bom, false)
1016}
1017
1018/// [`bom_csv`], with an `Attachments` column when `attachments` is set.
1019pub fn bom_csv_with(bom: &Bom, attachments: bool) -> String {
1020    let mut header = Vec::new();
1021    if !bom.flat {
1022        header.extend(["Level", "Position"]);
1023    }
1024    header.extend([
1025        "Find", "Number", "Name", "Rev", "State", "Qty", "Unit", "Total qty", "Category", "Attributes", "MPN",
1026        "Manufacturer", "Supplier", "SPN", "Currency", "Unit price", "Extended", "Reference", "Warnings",
1027    ]);
1028    if attachments {
1029        header.push("Attachments");
1030    }
1031    let mut out = header.join(",");
1032    out.push('\n');
1033    for line in &bom.lines {
1034        let mut row: Vec<String> = Vec::new();
1035        if !bom.flat {
1036            row.push(line.level.to_string());
1037            row.push(line.position.clone());
1038        }
1039        let rev = if line.floating { format!("{} (floating)", line.revision_label) } else { line.revision_label.clone() };
1040        row.extend([
1041            line.find_number.clone(),
1042            line.number.clone(),
1043            line.name.clone(),
1044            rev,
1045            line.state.clone(),
1046            qty(line.quantity),
1047            line.unit.clone(),
1048            qty(line.total),
1049            line.category_path.clone(),
1050            line.attributes.join("; "),
1051            line.mpn.clone(),
1052            line.manufacturer.clone(),
1053            line.supplier.clone(),
1054            line.spn.clone(),
1055            line.currency.clone(),
1056            money(line.unit_price),
1057            if line.costed { money(line.extended) } else { String::new() },
1058            line.reference.clone(),
1059            line.warnings.join("; "),
1060        ]);
1061        if attachments {
1062            row.push(line.attachments.join("; "));
1063        }
1064        out.push_str(&row.iter().map(|c| csv_cell(c)).collect::<Vec<_>>().join(","));
1065        out.push('\n');
1066    }
1067    for total in &bom.totals {
1068        out.push_str(&format!("Total {},{}\n", csv_cell(&total.currency), money(Some(total.total))));
1069    }
1070    if bom.unpriced > 0 {
1071        out.push_str(&format!("Unpriced lines,{}\n", bom.unpriced));
1072    }
1073    out
1074}
1075
1076
1077/// Walk the placements themselves, including one subtree for every repeated
1078/// subassembly instance. Each row still edits the occurrence's actual owner.
1079pub(crate) fn occurrence_lines(state:&State,top:&Part,revision:&Revision)->Vec<BomLine>{
1080    fn descend_values(state:&State,parent:&Part,revision:&Revision,prefix:&str,level:usize,multiplier:f64,path:&mut Vec<String>,out:&mut Vec<BomLine>){
1081        let mut ordinal=0;
1082        for line in &revision.uses{
1083            let child=state.part(&line.part);let resolved=child.and_then(|p|resolve(p,line));
1084            let occurrences:Vec<&crate::bom_config::Occurrence>=revision.occurrences.iter().filter(|o|o.part==line.part&&(line.revision.is_empty()||o.revision==line.revision)).collect();
1085            let placements:Vec<Option<&crate::bom_config::Occurrence>>=if occurrences.is_empty(){vec![None]}else{occurrences.iter().map(|o|Some(*o)).collect()};
1086            let quantity=line.quantity/placements.len() as f64;
1087            for occurrence in placements{
1088                ordinal+=1;let position=if prefix.is_empty(){ordinal.to_string()}else{format!("{prefix}.{ordinal}")};
1089                let cycle=child.is_some_and(|p|path.contains(&p.id));
1090                let stop=if cycle{Some("cycle: this part is already above it — not expanded".into())}else if level>=MAX_DEPTH{Some(format!("deeper than {MAX_DEPTH} levels — not expanded"))}else{None};
1091                let mut row=make_line(state,&Walked{parent_revision:revision,parent_part:parent.id.clone(),level,position:position.clone(),line,child,revision:resolved,total:multiplier*quantity,stop});
1092                row.quantity=quantity;row.occurrence_values.clear();
1093                if let Some(occurrence)=occurrence{
1094                    row.occurrence_ids=vec![occurrence.id.clone()];row.occurrence_attributes=occurrence.attributes.clone();
1095                    row.find_number=occurrence.attributes.get("Find_Number").and_then(Value::as_str).unwrap_or("").into();
1096                    row.reference=occurrence.attributes.get("Reference_Designator").and_then(Value::as_str).unwrap_or(&occurrence.id).into();
1097                    row.notes=occurrence.attributes.get("Notes").and_then(Value::as_str).unwrap_or("").into();
1098                }
1099                out.push(row);
1100                if !cycle&&level<MAX_DEPTH{
1101                    if let (Some(child),Some(revision))=(child,resolved){
1102                        path.push(child.id.clone());descend_values(state,child,revision,&position,level+1,multiplier*quantity,path,out);path.pop();
1103                    }
1104                }
1105            }
1106        }
1107    }
1108    let mut lines=Vec::new();descend_values(state,top,revision,"",1,1.0,&mut vec![top.id.clone()],&mut lines);lines
1109}