Skip to main content

brep_plm/
replace.rs

1//! Replace everywhere: swap one part (or one revision of it) for another in
2//! every assembly that uses it, driven by where-used.
3//!
4//! # What it touches
5//!
6//! Only DIRECT parents — the revisions whose own uses list names the old part.
7//! Grandparents use the parent, not the old part, and a parent's new revision
8//! is theirs to pick up (or not) through their own references.
9//!
10//! By default every CURRENT parent revision is a candidate: one in work, or a
11//! part's current release. Superseded and obsolete revisions are history and
12//! are never rewritten. The caller may narrow the set to named revisions.
13//!
14//! # How each parent is written (replace-everywhere defaults)
15//!
16//! - **A parent revision in work** is edited in place, in one locked write. If
17//!   another user holds its lock the row is refused; if nobody does, the write
18//!   happens without taking the lock (it is a check-out, write and check-in in
19//!   one transaction). A lock the caller holds stays held.
20//! - **A released parent** gets a NEW revision (the suggested label), which
21//!   starts from the release like any new revision and is left checked in.
22//!   If that part already has a revision in work, the released row is SKIPPED:
23//!   the revision in work is where the part is being changed, and it is a row
24//!   of its own when it still uses the old part. Nothing is merged into it.
25//!
26//! # Which lines change
27//!
28//! A line naming the old part changes when it names the revision being
29//! replaced — any revision, when none is given. A FLOATING line (no pinned
30//! revision) changes only when the whole part is being replaced; replacing
31//! one revision leaves floating lines alone, since they follow the part's
32//! releases and never pointed at that revision in particular. The new line
33//! keeps the quantity, unit, find number, reference and notes, and names the
34//! replacement pinned to the revision asked for, or floating when none is.
35//!
36//! Each parent is its own write, so one refusal leaves the others done; the
37//! report says what happened to each, like a family Generate. A dry run
38//! computes the same report from the store as it stands and writes nothing.
39
40use serde::{Deserialize, Serialize};
41use serde_json::Value;
42
43use crate::bom;
44use crate::db::{now, Db, State};
45use crate::eco::{NewEco, NewItem};
46use crate::model::{Lifecycle, Part, Revision, Use, User};
47use crate::Error;
48
49/// What the caller asks for.
50#[derive(Debug, Clone, Default, Deserialize)]
51pub struct ReplaceRequest {
52    /// The revision of the OLD part to replace, by id or label. Empty: every
53    /// revision of it (the whole part).
54    #[serde(default)]
55    pub from_revision: String,
56    /// The replacement part, by id or number. Empty: the old part itself (a
57    /// revision swap).
58    #[serde(default)]
59    pub to_part: String,
60    /// The replacement's revision, by id or label. Empty: floating.
61    #[serde(default)]
62    pub to_revision: String,
63    /// Parent revisions to touch, by readable part/revision document key. Empty: every current direct parent.
64    #[serde(default)]
65    pub parents: Vec<String>,
66    /// Compute the report without writing.
67    #[serde(default)]
68    pub dry_run: bool,
69    /// Put every written revision into a change order.
70    #[serde(default)]
71    pub eco: Option<EcoTarget>,
72}
73
74/// An existing change order by id or number, or a new one.
75#[derive(Debug, Clone, Deserialize)]
76#[serde(untagged)]
77pub enum EcoTarget {
78    Existing(String),
79    New { new: NewEco },
80}
81
82/// One changed line: what it named, and what it will name.
83#[derive(Debug, Clone, Serialize)]
84pub struct LineChange {
85    pub find_number: String,
86    pub quantity: f64,
87    pub unit: String,
88    pub from: String,
89    pub to: String,
90}
91
92/// What happened (or would happen) to one parent revision.
93#[derive(Debug, Clone, Serialize)]
94pub struct ReplaceRow {
95    pub part_id: String,
96    pub number: String,
97    pub name: String,
98    /// The parent revision where-used found.
99    pub parent_revision_id: String,
100    pub parent_revision: String,
101    pub parent_state: String,
102    /// `edit` (in place), `new-revision`, or empty when nothing is written.
103    pub plan: String,
104    /// `written`, `created`, `would-write`, `would-create`, `skipped`, `refused`.
105    pub status: String,
106    pub reason: String,
107    /// The revision written (or to be written): the parent itself for an
108    /// edit, the new one for a new revision.
109    pub revision_id: String,
110    pub revision: String,
111    pub lines: Vec<LineChange>,
112    /// Floating lines of the old part left alone.
113    pub floating_left: usize,
114    /// What adding the written revision to the change order did: `added`,
115    /// `already in it`, or why it could not be added.
116    pub eco: String,
117}
118
119#[derive(Debug, Clone, Serialize)]
120pub struct ReplaceReport {
121    pub dry_run: bool,
122    pub from_part: String,
123    pub from_revision: String,
124    pub to_part: String,
125    pub to_revision: String,
126    pub rows: Vec<ReplaceRow>,
127    pub written: usize,
128    pub skipped: usize,
129    pub refused: usize,
130    /// The change order the written revisions went into, if any.
131    pub eco_number: String,
132    pub eco_id: String,
133}
134
135/// The resolved request: ids, and the names a report prints.
136struct Target {
137    old_part: String,
138    old_number: String,
139    /// Empty: the whole part.
140    from_revision: String,
141    from_label: String,
142    new_part: String,
143    new_number: String,
144    /// Empty: floating.
145    to_revision: String,
146    to_label: String,
147}
148
149fn resolve_target(state: &State, part_key: &str, request: &ReplaceRequest) -> Result<Target, Error> {
150    let old = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
151    let (from_revision, from_label) = if request.from_revision.trim().is_empty() {
152        (String::new(), String::new())
153    } else {
154        let r = bom::find_revision(old, &request.from_revision)
155            .ok_or_else(|| Error::bad_request(format!("{} has no revision '{}'", old.number, request.from_revision.trim())))?;
156        (r.id.clone(), r.label.clone())
157    };
158    let new = if request.to_part.trim().is_empty() {
159        old
160    } else {
161        state
162            .part_by_id_or_number(request.to_part.trim())
163            .ok_or_else(|| Error::bad_request(format!("there is no part '{}'", request.to_part.trim())))?
164    };
165    let (to_revision, to_label) = if request.to_revision.trim().is_empty() {
166        (String::new(), String::new())
167    } else {
168        let r = bom::find_revision(new, &request.to_revision)
169            .ok_or_else(|| Error::bad_request(format!("{} has no revision '{}'", new.number, request.to_revision.trim())))?;
170        (r.id.clone(), r.label.clone())
171    };
172    if new.id == old.id && to_revision.is_empty() {
173        return Err(Error::bad_request(format!(
174            "name the revision of {} to use instead — replacing {} with itself, floating, changes nothing",
175            old.number, old.number
176        )));
177    }
178    if new.id == old.id && !from_revision.is_empty() && to_revision == from_revision {
179        return Err(Error::bad_request("the replacement is the revision being replaced"));
180    }
181    Ok(Target {
182        old_part: old.id.clone(),
183        old_number: old.number.clone(),
184        from_revision,
185        from_label,
186        new_part: new.id.clone(),
187        new_number: new.number.clone(),
188        to_revision,
189        to_label,
190    })
191}
192
193/// Whether `line` is one this replacement changes (see the module header).
194fn changes(target: &Target, line: &Use) -> bool {
195    if line.part != target.old_part {
196        return false;
197    }
198    if target.from_revision.is_empty() {
199        // The whole part: pinned and floating lines alike — except a line
200        // that already names exactly the replacement.
201        !(line.part == target.new_part && line.revision == target.to_revision)
202    } else {
203        line.revision == target.from_revision
204    }
205}
206
207fn floating_left(target: &Target, revision: &Revision) -> usize {
208    if target.from_revision.is_empty() {
209        return 0;
210    }
211    revision.uses.iter().filter(|u| u.part == target.old_part && u.revision.is_empty()).count()
212}
213
214fn describe(state: &State, part_id: &str, revision_id: &str) -> String {
215    let Some(part) = state.part(part_id) else { return part_id.to_string() };
216    if revision_id.is_empty() {
217        format!("{} (floating)", part.number)
218    } else {
219        let label = part.revision(revision_id).map(|r| r.label.clone()).unwrap_or_else(|| "(deleted)".into());
220        format!("{} rev {label}", part.number)
221    }
222}
223
224/// The swapped list as the JSON [`bom::check_uses`] reads, and the lines it changes.
225fn swapped(state: &State, target: &Target, uses: &[Use]) -> (Value, Vec<LineChange>) {
226    let mut out = Vec::with_capacity(uses.len());
227    let mut changed = Vec::new();
228    for line in uses {
229        let (part, revision) = if changes(target, line) {
230            changed.push(LineChange {
231                find_number: line.find_number.clone(),
232                quantity: line.quantity,
233                unit: line.unit.clone(),
234                from: describe(state, &line.part, &line.revision),
235                to: describe(state, &target.new_part, &target.to_revision),
236            });
237            (target.new_part.clone(), target.to_revision.clone())
238        } else {
239            (line.part.clone(), line.revision.clone())
240        };
241        out.push(serde_json::json!({
242            "part": part,
243            "revision": revision,
244            "quantity": line.quantity,
245            "unit": line.unit,
246            "find_number": line.find_number,
247            "reference": line.reference,
248            "notes": line.notes,
249        }));
250    }
251    (Value::Array(out), changed)
252}
253
254/// Whether a parent revision is one the default set covers.
255fn is_current(revision: &Revision) -> bool {
256    revision.lifecycle.is_editable() || revision.lifecycle == Lifecycle::Released
257}
258
259/// Plan one parent row from the store as it stands. `None` for the revision
260/// to write means the row is skipped or refused (the row says why).
261fn plan_row(state: &State, user: &User, target: &Target, parent: &Part, revision: &Revision) -> ReplaceRow {
262    let (list, lines) = swapped(state, target, &revision.uses);
263    let mut row = ReplaceRow {
264        part_id: parent.id.clone(),
265        number: parent.number.clone(),
266        name: parent.name.clone(),
267        parent_revision_id: revision.id.clone(),
268        parent_revision: revision.label.clone(),
269        parent_state: revision.lifecycle.as_str().to_string(),
270        plan: String::new(),
271        status: String::new(),
272        reason: String::new(),
273        revision_id: String::new(),
274        revision: String::new(),
275        lines,
276        floating_left: floating_left(target, revision),
277        eco: String::new(),
278    };
279    let refuse = |row: &mut ReplaceRow, status: &str, reason: String| {
280        row.status = status.to_string();
281        row.reason = reason;
282    };
283    if row.lines.is_empty() {
284        let why = if row.floating_left > 0 {
285            format!("its only use of {} is floating, which follows the part's releases", target.old_number)
286        } else {
287            format!("it no longer uses {} {}", target.old_number, target.from_label).trim_end().to_string()
288        };
289        refuse(&mut row, "skipped", why);
290        return row;
291    }
292    if !is_current(revision) {
293        refuse(&mut row, "skipped", format!("revision {} is {} — history is not rewritten", revision.label, revision.lifecycle.as_str()));
294        return row;
295    }
296    if revision.lifecycle.is_editable() {
297        row.plan = "edit".into();
298        row.revision_id = revision.id.clone();
299        row.revision = revision.label.clone();
300        if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
301            let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
302            refuse(&mut row, "refused", format!("revision {} is checked out by {holder}", revision.label));
303            return row;
304        }
305    } else {
306        // Released: a new revision, unless the part is already being changed.
307        if let Some(open) = parent.open_draft() {
308            refuse(
309                &mut row,
310                "skipped",
311                format!("revision {} is already in work — the part is changed there", open.label),
312            );
313            return row;
314        }
315        row.plan = "new-revision".into();
316        row.revision = crate::db::suggest_label(parent);
317    }
318    if let Err(error) = bom::check_uses(state, &parent.id, &list) {
319        refuse(&mut row, "refused", error.message);
320        return row;
321    }
322    row.status = if row.plan == "edit" { "would-write" } else { "would-create" }.into();
323    row
324}
325
326impl Db {
327    /// Replace everywhere (see the module header).
328    pub fn replace_everywhere(&self, user: &User, part_key: &str, request: &ReplaceRequest) -> Result<ReplaceReport, Error> {
329        if !user.can_author() {
330            return Err(Error::forbidden("replacing a part in assemblies needs the author group"));
331        }
332        let (target, plans) = self.read(|state| -> Result<_, Error> {
333            let target = resolve_target(state, part_key, request)?;
334            let old = state.part(&target.old_part).ok_or_else(|| Error::not_found("part"))?;
335            let wanted: Vec<&str> = request.parents.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect();
336            let from = old.revision(&target.from_revision);
337            let found = bom::where_used(state, old, from, 1);
338            let mut plans = Vec::new();
339            let mut seen = std::collections::BTreeSet::new();
340            for line in &found.lines {
341                let key = crate::identity::document_key(&line.part_id, &line.revision_id);
342                if !seen.insert(key.clone()) {
343                    continue;
344                }
345                if !wanted.is_empty() && !wanted.contains(&key.as_str()) {
346                    continue;
347                }
348                if wanted.is_empty() && !line.current {
349                    continue;
350                }
351                let parent = state.part(&line.part_id).ok_or_else(|| Error::not_found("part"))?;
352                let revision = parent.revision(&line.revision_id).ok_or_else(|| Error::not_found("revision"))?;
353                plans.push(plan_row(state, user, &target, parent, revision));
354            }
355            // A floating use of one revision is not found by a revision-scoped
356            // where-used when it resolves elsewhere; name the ones asked for.
357            for id in &wanted {
358                if seen.contains(*id) {
359                    continue;
360                }
361                return Err(Error::bad_request(format!("revision '{id}' does not use {}", target.old_number)));
362            }
363            Ok((target, plans))
364        })?;
365
366        let mut report = ReplaceReport {
367            dry_run: request.dry_run,
368            from_part: target.old_number.clone(),
369            from_revision: target.from_label.clone(),
370            to_part: target.new_number.clone(),
371            to_revision: target.to_label.clone(),
372            rows: Vec::new(),
373            written: 0,
374            skipped: 0,
375            refused: 0,
376            eco_number: String::new(),
377            eco_id: String::new(),
378        };
379        if request.dry_run {
380            for row in plans {
381                match row.status.as_str() {
382                    "skipped" => report.skipped += 1,
383                    "refused" => report.refused += 1,
384                    _ => {}
385                }
386                report.rows.push(row);
387            }
388            return Ok(report);
389        }
390
391        // The change order first, so a bad one refuses before anything is
392        // written.
393        let eco = match &request.eco {
394            None => None,
395            Some(EcoTarget::Existing(key)) => {
396                let (id, number) = self.read(|state| {
397                    crate::eco::find(state, key.trim())
398                        .map(|e| (e.id.clone(), e.number.clone()))
399                        .ok_or_else(|| Error::not_found(format!("change order '{}'", key.trim())))
400                })?;
401                Some((id, number))
402            }
403            Some(EcoTarget::New { new }) => {
404                let eco = self.create_eco(user, new)?;
405                Some((eco.id, eco.number))
406            }
407        };
408        if let Some((id, number)) = &eco {
409            report.eco_id = id.clone();
410            report.eco_number = number.clone();
411        }
412
413        for mut row in plans {
414            if row.status == "would-write" || row.status == "would-create" {
415                let result = if row.plan == "edit" {
416                    self.replace_in(user, &target, &row.part_id, &row.revision_id).map(|lines| {
417                        row.status = "written".into();
418                        row.lines = lines;
419                    })
420                } else {
421                    self.replace_in_new_revision(user, &target, &row.part_id, &row.parent_revision_id).map(
422                        |(revision, lines)| {
423                            row.status = "created".into();
424                            row.revision_id = revision.id;
425                            row.revision = revision.label;
426                            row.lines = lines;
427                        },
428                    )
429                };
430                if let Err(error) = result {
431                    row.status = "refused".into();
432                    row.reason = error.message;
433                }
434            }
435            match row.status.as_str() {
436                "written" | "created" => {
437                    report.written += 1;
438                    if let Some((eco_id, _)) = &eco {
439                        row.eco = self.replace_into_eco(user, eco_id, &row);
440                    }
441                }
442                "skipped" => report.skipped += 1,
443                _ => report.refused += 1,
444            }
445            report.rows.push(row);
446        }
447        Ok(report)
448    }
449
450    /// Swap the lines in a revision in work, in one locked write. The checks
451    /// the plan made are made again here: the store may have moved.
452    fn replace_in(&self, user: &User, target: &Target, part_id: &str, revision_id: &str) -> Result<Vec<LineChange>, Error> {
453        let user_id = user.id.clone();
454        self.mutate(|state| {
455            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
456            let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
457            if !revision.lifecycle.is_editable() {
458                return Err(Error::conflict(format!(
459                    "revision {} is now {}",
460                    revision.label,
461                    revision.lifecycle.as_str()
462                )));
463            }
464            if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user_id) {
465                let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
466                return Err(Error::conflict(format!("revision {} is checked out by {holder}", revision.label)));
467            }
468            let (list, lines) = swapped(state, target, &revision.uses);
469            if lines.is_empty() {
470                return Err(Error::conflict(format!("revision {} no longer uses {}", revision.label, target.old_number)));
471            }
472            let uses = bom::check_uses(state, part_id, &list)?;
473            let (_, revision) = crate::db::find_revision_mut(state, part_id, revision_id)?;
474            revision.uses = uses;
475            revision.modified_at = now();
476            Ok(lines)
477        })
478    }
479
480    /// Start a new revision of a released parent and swap the lines in it. If
481    /// the swap is refused, the new revision is deleted again, so a refused
482    /// row leaves nothing behind.
483    fn replace_in_new_revision(
484        &self,
485        user: &User,
486        target: &Target,
487        part_id: &str,
488        released_id: &str,
489    ) -> Result<(Revision, Vec<LineChange>), Error> {
490        // The plan saw no revision in work; one may have started since.
491        self.read(|state| {
492            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
493            if let Some(open) = part.open_draft() {
494                return Err(Error::conflict(format!("revision {} is already in work — the part is changed there", open.label)));
495            }
496            if part.current_release().map(|r| r.id.as_str()) != Some(released_id) {
497                return Err(Error::conflict("the part's current release changed meanwhile"));
498            }
499            Ok(())
500        })?;
501        let revision = self.create_revision(user, part_id)?;
502        match self.replace_in(user, target, part_id, &revision.id) {
503            Ok(lines) => Ok((revision, lines)),
504            Err(error) => {
505                if let Err(undo) = self.delete_draft(user, part_id, &revision.id) {
506                    eprintln!("brep-plm: replace: could not remove the new revision after a refusal: {}", undo.message);
507                }
508                Err(error)
509            }
510        }
511    }
512
513    /// Add a written revision to the change order. A refusal here does not
514    /// undo the write; the row says why it is not in the change order.
515    fn replace_into_eco(&self, user: &User, eco_id: &str, row: &ReplaceRow) -> String {
516        let already = self.read(|state| {
517            crate::eco::find(state, eco_id).is_some_and(|e| e.item(&row.part_id, &row.revision_id).is_some())
518        });
519        if already {
520            return "already in it".into();
521        }
522        let item = NewItem {
523            part: row.part_id.clone(),
524            revision: row.revision_id.clone(),
525            action: "release".into(),
526            note: String::new(),
527        };
528        match self.add_eco_item(user, eco_id, &item) {
529            Ok(_) => "added".into(),
530            Err(error) => error.message,
531        }
532    }
533}