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::model::{Lifecycle, Part, Revision, Use, User};
46use crate::Error;
47
48/// What the caller asks for.
49#[derive(Debug, Clone, Default, Deserialize)]
50#[serde(deny_unknown_fields)]
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}
70
71/// One changed line: what it named, and what it will name.
72#[derive(Debug, Clone, Serialize)]
73pub struct LineChange {
74    pub find_number: String,
75    pub quantity: f64,
76    pub unit: String,
77    pub from: String,
78    pub to: String,
79}
80
81/// What happened (or would happen) to one parent revision.
82#[derive(Debug, Clone, Serialize)]
83pub struct ReplaceRow {
84    pub part_id: String,
85    pub number: String,
86    pub name: String,
87    /// The parent revision where-used found.
88    pub parent_revision_id: String,
89    pub parent_revision: String,
90    pub parent_state: String,
91    /// `edit` (in place), `new-revision`, or empty when nothing is written.
92    pub plan: String,
93    /// `written`, `created`, `would-write`, `would-create`, `skipped`, `refused`.
94    pub status: String,
95    pub reason: String,
96    /// The revision written (or to be written): the parent itself for an
97    /// edit, the new one for a new revision.
98    pub revision_id: String,
99    pub revision: String,
100    pub lines: Vec<LineChange>,
101    /// Floating lines of the old part left alone.
102    pub floating_left: usize,
103}
104
105#[derive(Debug, Clone, Serialize)]
106pub struct ReplaceReport {
107    pub dry_run: bool,
108    pub from_part: String,
109    pub from_revision: String,
110    pub to_part: String,
111    pub to_revision: String,
112    pub rows: Vec<ReplaceRow>,
113    pub written: usize,
114    pub skipped: usize,
115    pub refused: usize,
116}
117
118/// The resolved request: ids, and the names a report prints.
119struct Target {
120    old_part: String,
121    old_number: String,
122    /// Empty: the whole part.
123    from_revision: String,
124    from_label: String,
125    new_part: String,
126    new_number: String,
127    /// Empty: floating.
128    to_revision: String,
129    to_label: String,
130}
131
132fn resolve_target(state: &State, part_key: &str, request: &ReplaceRequest) -> Result<Target, Error> {
133    let old = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
134    let (from_revision, from_label) = if request.from_revision.trim().is_empty() {
135        (String::new(), String::new())
136    } else {
137        let r = bom::find_revision(old, &request.from_revision)
138            .ok_or_else(|| Error::bad_request(format!("{} has no revision '{}'", old.number, request.from_revision.trim())))?;
139        (r.id.clone(), r.label.clone())
140    };
141    let new = if request.to_part.trim().is_empty() {
142        old
143    } else {
144        state
145            .part_by_id_or_number(request.to_part.trim())
146            .ok_or_else(|| Error::bad_request(format!("there is no part '{}'", request.to_part.trim())))?
147    };
148    let (to_revision, to_label) = if request.to_revision.trim().is_empty() {
149        (String::new(), String::new())
150    } else {
151        let r = bom::find_revision(new, &request.to_revision)
152            .ok_or_else(|| Error::bad_request(format!("{} has no revision '{}'", new.number, request.to_revision.trim())))?;
153        (r.id.clone(), r.label.clone())
154    };
155    if new.id == old.id && to_revision.is_empty() {
156        return Err(Error::bad_request(format!(
157            "name the revision of {} to use instead — replacing {} with itself, floating, changes nothing",
158            old.number, old.number
159        )));
160    }
161    if new.id == old.id && !from_revision.is_empty() && to_revision == from_revision {
162        return Err(Error::bad_request("the replacement is the revision being replaced"));
163    }
164    Ok(Target {
165        old_part: old.id.clone(),
166        old_number: old.number.clone(),
167        from_revision,
168        from_label,
169        new_part: new.id.clone(),
170        new_number: new.number.clone(),
171        to_revision,
172        to_label,
173    })
174}
175
176/// Whether `line` is one this replacement changes (see the module header).
177fn changes(target: &Target, line: &Use) -> bool {
178    if line.part != target.old_part {
179        return false;
180    }
181    if target.from_revision.is_empty() {
182        // The whole part: pinned and floating lines alike — except a line
183        // that already names exactly the replacement.
184        !(line.part == target.new_part && line.revision == target.to_revision)
185    } else {
186        line.revision == target.from_revision
187    }
188}
189
190fn floating_left(target: &Target, revision: &Revision) -> usize {
191    if target.from_revision.is_empty() {
192        return 0;
193    }
194    revision.uses.iter().filter(|u| u.part == target.old_part && u.revision.is_empty()).count()
195}
196
197fn describe(state: &State, part_id: &str, revision_id: &str) -> String {
198    let Some(part) = state.part(part_id) else { return part_id.to_string() };
199    if revision_id.is_empty() {
200        format!("{} (floating)", part.number)
201    } else {
202        let label = part.revision(revision_id).map(|r| r.label.clone()).unwrap_or_else(|| "(deleted)".into());
203        format!("{} rev {label}", part.number)
204    }
205}
206
207/// The swapped list as the JSON [`bom::check_uses`] reads, and the lines it changes.
208fn swapped(state: &State, target: &Target, uses: &[Use]) -> (Value, Vec<LineChange>) {
209    let mut out = Vec::with_capacity(uses.len());
210    let mut changed = Vec::new();
211    for line in uses {
212        let (part, revision) = if changes(target, line) {
213            changed.push(LineChange {
214                find_number: line.find_number.clone(),
215                quantity: line.quantity,
216                unit: line.unit.clone(),
217                from: describe(state, &line.part, &line.revision),
218                to: describe(state, &target.new_part, &target.to_revision),
219            });
220            (target.new_part.clone(), target.to_revision.clone())
221        } else {
222            (line.part.clone(), line.revision.clone())
223        };
224        out.push(serde_json::json!({
225            "part": part,
226            "revision": revision,
227            "quantity": line.quantity,
228            "unit": line.unit,
229            "find_number": line.find_number,
230            "reference": line.reference,
231            "notes": line.notes,
232        }));
233    }
234    (Value::Array(out), changed)
235}
236
237/// Whether a parent revision is one the default set covers.
238fn is_current(revision: &Revision) -> bool {
239    revision.lifecycle.is_editable() || revision.lifecycle == Lifecycle::Released
240}
241
242/// Plan one parent row from the store as it stands. `None` for the revision
243/// to write means the row is skipped or refused (the row says why).
244fn plan_row(state: &State, user: &User, target: &Target, parent: &Part, revision: &Revision) -> ReplaceRow {
245    let (list, lines) = swapped(state, target, &revision.uses);
246    let mut row = ReplaceRow {
247        part_id: parent.id.clone(),
248        number: parent.number.clone(),
249        name: parent.name.clone(),
250        parent_revision_id: revision.id.clone(),
251        parent_revision: revision.label.clone(),
252        parent_state: revision.lifecycle.as_str().to_string(),
253        plan: String::new(),
254        status: String::new(),
255        reason: String::new(),
256        revision_id: String::new(),
257        revision: String::new(),
258        lines,
259        floating_left: floating_left(target, revision),
260
261    };
262    let refuse = |row: &mut ReplaceRow, status: &str, reason: String| {
263        row.status = status.to_string();
264        row.reason = reason;
265    };
266    if row.lines.is_empty() {
267        let why = if row.floating_left > 0 {
268            format!("its only use of {} is floating, which follows the part's releases", target.old_number)
269        } else {
270            format!("it no longer uses {} {}", target.old_number, target.from_label).trim_end().to_string()
271        };
272        refuse(&mut row, "skipped", why);
273        return row;
274    }
275    if !is_current(revision) {
276        refuse(&mut row, "skipped", format!("revision {} is {} — history is not rewritten", revision.label, revision.lifecycle.as_str()));
277        return row;
278    }
279    if revision.lifecycle.is_editable() {
280        row.plan = "edit".into();
281        row.revision_id = revision.id.clone();
282        row.revision = revision.label.clone();
283        if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
284            let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
285            refuse(&mut row, "refused", format!("revision {} is checked out by {holder}", revision.label));
286            return row;
287        }
288    } else {
289        // Released: a new revision, unless the part is already being changed.
290        if let Some(open) = parent.open_draft() {
291            refuse(
292                &mut row,
293                "skipped",
294                format!("revision {} is already in work — the part is changed there", open.label),
295            );
296            return row;
297        }
298        row.plan = "new-revision".into();
299        row.revision = crate::db::suggest_label(parent);
300    }
301    if let Err(error) = bom::check_uses(state, &parent.id, &list) {
302        refuse(&mut row, "refused", error.message);
303        return row;
304    }
305    row.status = if row.plan == "edit" { "would-write" } else { "would-create" }.into();
306    row
307}
308
309impl Db {
310    /// Replace everywhere (see the module header).
311    pub fn replace_everywhere(&self, user: &User, part_key: &str, request: &ReplaceRequest) -> Result<ReplaceReport, Error> {
312        if !user.can_author() {
313            return Err(Error::forbidden("replacing a part in assemblies needs the author group"));
314        }
315        let (target, plans) = self.read(|state| -> Result<_, Error> {
316            let target = resolve_target(state, part_key, request)?;
317            let old = state.part(&target.old_part).ok_or_else(|| Error::not_found("part"))?;
318            let wanted: Vec<&str> = request.parents.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect();
319            let from = old.revision(&target.from_revision);
320            let found = bom::where_used(state, old, from, 1);
321            let mut plans = Vec::new();
322            let mut seen = std::collections::BTreeSet::new();
323            for line in &found.lines {
324                let key = crate::identity::document_key(&line.part_id, &line.revision_id);
325                if !seen.insert(key.clone()) {
326                    continue;
327                }
328                if !wanted.is_empty() && !wanted.contains(&key.as_str()) {
329                    continue;
330                }
331                if wanted.is_empty() && !line.current {
332                    continue;
333                }
334                let parent = state.part(&line.part_id).ok_or_else(|| Error::not_found("part"))?;
335                let revision = parent.revision(&line.revision_id).ok_or_else(|| Error::not_found("revision"))?;
336                plans.push(plan_row(state, user, &target, parent, revision));
337            }
338            // A floating use of one revision is not found by a revision-scoped
339            // where-used when it resolves elsewhere; name the ones asked for.
340            for id in &wanted {
341                if seen.contains(*id) {
342                    continue;
343                }
344                return Err(Error::bad_request(format!("revision '{id}' does not use {}", target.old_number)));
345            }
346            Ok((target, plans))
347        })?;
348
349        let mut report = ReplaceReport {
350            dry_run: request.dry_run,
351            from_part: target.old_number.clone(),
352            from_revision: target.from_label.clone(),
353            to_part: target.new_number.clone(),
354            to_revision: target.to_label.clone(),
355            rows: Vec::new(),
356            written: 0,
357            skipped: 0,
358            refused: 0,
359
360        };
361        if request.dry_run {
362            for row in plans {
363                match row.status.as_str() {
364                    "skipped" => report.skipped += 1,
365                    "refused" => report.refused += 1,
366                    _ => {}
367                }
368                report.rows.push(row);
369            }
370            return Ok(report);
371        }
372
373        for mut row in plans {
374            if row.status == "would-write" || row.status == "would-create" {
375                let result = if row.plan == "edit" {
376                    self.replace_in(user, &target, &row.part_id, &row.revision_id).map(|lines| {
377                        row.status = "written".into();
378                        row.lines = lines;
379                    })
380                } else {
381                    self.replace_in_new_revision(user, &target, &row.part_id, &row.parent_revision_id).map(
382                        |(revision, lines)| {
383                            row.status = "created".into();
384                            row.revision_id = revision.id;
385                            row.revision = revision.label;
386                            row.lines = lines;
387                        },
388                    )
389                };
390                if let Err(error) = result {
391                    row.status = "refused".into();
392                    row.reason = error.message;
393                }
394            }
395            match row.status.as_str() {
396                "written" | "created" => {
397                    report.written += 1;
398                }
399                "skipped" => report.skipped += 1,
400                _ => report.refused += 1,
401            }
402            report.rows.push(row);
403        }
404        Ok(report)
405    }
406
407    /// Swap the lines in a revision in work, in one locked write. The checks
408    /// the plan made are made again here: the store may have moved.
409    fn replace_in(&self, user: &User, target: &Target, part_id: &str, revision_id: &str) -> Result<Vec<LineChange>, Error> {
410        let user_id = user.id.clone();
411        self.mutate(|state| {
412            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
413            let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
414            if !revision.lifecycle.is_editable() {
415                return Err(Error::conflict(format!(
416                    "revision {} is now {}",
417                    revision.label,
418                    revision.lifecycle.as_str()
419                )));
420            }
421            if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user_id) {
422                let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
423                return Err(Error::conflict(format!("revision {} is checked out by {holder}", revision.label)));
424            }
425            let (list, lines) = swapped(state, target, &revision.uses);
426            if lines.is_empty() {
427                return Err(Error::conflict(format!("revision {} no longer uses {}", revision.label, target.old_number)));
428            }
429            let uses = bom::check_uses(state, part_id, &list)?;
430            let (_, revision) = crate::db::find_revision_mut(state, part_id, revision_id)?;
431            revision.uses = uses;
432            revision.modified_at = now();
433            Ok(lines)
434        })
435    }
436
437    /// Start a new revision of a released parent and swap the lines in it. If
438    /// the swap is refused, the new revision is deleted again, so a refused
439    /// row leaves nothing behind.
440    fn replace_in_new_revision(
441        &self,
442        user: &User,
443        target: &Target,
444        part_id: &str,
445        released_id: &str,
446    ) -> Result<(Revision, Vec<LineChange>), Error> {
447        // The plan saw no revision in work; one may have started since.
448        self.read(|state| {
449            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
450            if let Some(open) = part.open_draft() {
451                return Err(Error::conflict(format!("revision {} is already in work — the part is changed there", open.label)));
452            }
453            if part.current_release().map(|r| r.id.as_str()) != Some(released_id) {
454                return Err(Error::conflict("the part's current release changed meanwhile"));
455            }
456            Ok(())
457        })?;
458        let revision = self.create_revision(user, part_id)?;
459        match self.replace_in(user, target, part_id, &revision.id) {
460            Ok(lines) => Ok((revision, lines)),
461            Err(error) => {
462                if let Err(undo) = self.delete_draft(user, part_id, &revision.id) {
463                    eprintln!("brep-plm: replace: could not remove the new revision after a refusal: {}", undo.message);
464                }
465                Err(error)
466            }
467        }
468    }
469
470}