Skip to main content

brep_plm/
lifecycle.rs

1//! The revision state machine, and the revision labels.
2//!
3//! Every lifecycle move in the server goes through [`check_transition`]. One
4//! function means the rules can be read in one place and tested without a
5//! server, and it is why "released is immutable" is a property of the type
6//! rather than a check each handler remembers.
7//!
8//! # What is NOT here
9//!
10//! Only which state may follow which. The release gates that read the rest of
11//! the store live with the write that releases (`Db::transition` in
12//! [`crate::db`]): required catalog values, the released-children gate
13//! (`require_released_children`, over the uses lists in [`crate::bom`]), the
14//! review rule, a workflow required for release, a pending bake, a held
15//! check-out and the `beforeRelease` hook.
16
17use crate::model::Lifecycle;
18
19/// Why a transition was refused. The message is user-facing: it is what the
20/// API returns and what the page shows.
21pub type Refusal = String;
22
23/// Whether `from` may become `to`, and why not when it may not.
24///
25/// The permitted moves:
26///
27/// * `Draft → InReview` — submit for review.
28/// * `InReview → Draft` — send back for more work.
29/// * `Draft → Released` / `InReview → Released` — review is OPTIONAL in this
30///   slice, so a draft may release directly.
31/// * `Released → Superseded` — applied automatically when a NEWER revision of
32///   the same part releases; never requested directly.
33/// * `Released → Obsolete`, `Superseded → Obsolete` — withdraw the part.
34///
35/// Everything else is refused, including every move OUT of `Obsolete` (it is
36/// terminal) and every move back out of `Released` other than the two above —
37/// which is the immutability rule stated as a transition.
38pub fn check_transition(from: Lifecycle, to: Lifecycle) -> Result<(), Refusal> {
39    use Lifecycle::*;
40    let allowed = matches!(
41        (from, to),
42        (Draft, InReview)
43            | (InReview, Draft)
44            | (Draft, Released)
45            | (InReview, Released)
46            | (Released, Superseded)
47            | (Released, Obsolete)
48            | (Superseded, Obsolete)
49    );
50    if allowed {
51        return Ok(());
52    }
53    Err(match from {
54        Obsolete => "an obsolete revision is final and cannot change state".to_string(),
55        Released | Superseded => format!(
56            "a {} revision is immutable — revise the part instead of moving it to {}",
57            from.as_str(),
58            to.as_str()
59        ),
60        _ => format!(
61            "a {} revision cannot become {}",
62            from.as_str(),
63            to.as_str()
64        ),
65    })
66}
67
68/// The label after `previous`: `A` → `B`, `Z` → `AA`, `AZ` → `BA`.
69///
70/// Plain base-26 over the full alphabet. Standards that skip the confusable
71/// letters (`I`, `O`, `Q`) differ on WHICH to skip, so that belongs in part-type
72/// configuration later rather than compiled in here.
73pub fn next_revision_label(previous: Option<&str>) -> String {
74    let Some(previous) = previous else {
75        return "A".to_string();
76    };
77    let mut chars: Vec<u8> = previous.trim().to_ascii_uppercase().into_bytes();
78    if chars.is_empty() || chars.iter().any(|c| !c.is_ascii_uppercase()) {
79        // A label this function did not produce (a hand-edited file, an
80        // imported vendor label like "1.2"): start a clean sequence rather
81        // than guess at its successor.
82        return "A".to_string();
83    }
84    let mut index = chars.len();
85    loop {
86        if index == 0 {
87            chars.insert(0, b'A');
88            break;
89        }
90        index -= 1;
91        if chars[index] == b'Z' {
92            chars[index] = b'A';
93            continue;
94        }
95        chars[index] += 1;
96        break;
97    }
98    String::from_utf8(chars).expect("ASCII uppercase stays UTF-8")
99}
100
101
102/// Check administrator availability without changing workflow semantics.
103pub fn check_enabled(settings: &crate::model::Settings, to: Lifecycle) -> Result<(), crate::Error> {
104    if settings.status_options.iter().any(|s| s.state == to && s.enabled) {
105        Ok(())
106    } else {
107        Err(crate::Error::conflict("this lifecycle status is disabled in server settings"))
108    }
109}
110
111pub fn check_options(options: &[crate::model::StatusOption]) -> Result<(), crate::Error> {
112    let mut names = std::collections::BTreeSet::new();
113    for state in [Lifecycle::Draft, Lifecycle::InReview, Lifecycle::Released, Lifecycle::Obsolete, Lifecycle::Superseded] {
114        if options.iter().filter(|s| s.state == state).count() != 1 {
115            return Err(crate::Error::bad_request("configure each workflow state exactly once"));
116        }
117    }
118    for option in options {
119        let name = option.name.trim();
120        if name.is_empty() || name.len() > 80 || !names.insert(name.to_lowercase()) {
121            return Err(crate::Error::bad_request("status names must be unique, nonempty and at most 80 bytes"));
122        }
123        if matches!(option.state, Lifecycle::Draft | Lifecycle::Superseded) && !option.enabled {
124            return Err(crate::Error::bad_request("the initial and automatic superseded states must stay enabled"));
125        }
126    }
127    Ok(())
128}