1use 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
36pub const MAX_DEPTH: usize = 32;
40
41pub 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
56pub 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
62pub 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
185pub 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
214pub 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
243pub 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#[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 pub level: usize,
291 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 pub state: String,
303 pub floating: bool,
305 pub category_path: String,
306 pub attributes: Vec<String>,
308 pub quantity: f64,
310 pub unit: String,
311 pub total: f64,
314 pub assembly: bool,
316 pub mpn: String,
319 pub manufacturer: String,
320 pub supplier: String,
322 pub spn: String,
323 pub currency: String,
324 pub unit_price: Option<f64>,
327 pub extended: Option<f64>,
329 pub costed: bool,
332 pub warnings: Vec<String>,
333 pub flags: Vec<String>, pub attachments: Vec<String>,
339}
340
341#[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 pub levels: usize,
364 pub lines: Vec<BomLine>,
365 pub totals: Vec<CurrencyTotal>,
366 pub unpriced: usize,
368 pub warnings: Vec<String>,
371}
372
373struct 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 stop: Option<String>,
385}
386
387fn 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
435fn 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
472fn 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
499fn 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
539pub 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 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 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
701pub(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#[derive(Debug, Clone, Serialize, PartialEq)]
725pub struct DiffSide {
726 pub quantity: f64,
727 pub unit: String,
728 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 pub change: &'static str,
740 pub from: Option<DiffSide>,
741 pub to: Option<DiffSide>,
742 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 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
793pub 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
851pub 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#[derive(Debug, Clone, Serialize)]
865pub struct WhereUsedLine {
866 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 pub current: bool,
878 pub uses_revision: String,
881 pub floating: bool,
882 pub quantity: f64,
883 pub unit: String,
884 pub find_number: String,
885 pub top: bool,
887}
888
889#[derive(Debug, Clone, Serialize)]
890pub struct WhereUsed {
891 pub part_id: String,
892 pub number: String,
893 pub revision_label: String,
895 pub levels: usize,
897 pub lines: Vec<WhereUsedLine>,
898}
899
900type 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
918fn 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
939pub 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
992pub(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
1011pub fn bom_csv(bom: &Bom) -> String {
1015 bom_csv_with(bom, false)
1016}
1017
1018pub 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
1077pub(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}