use crate::model::Lifecycle;
pub type Refusal = String;
pub fn check_transition(from: Lifecycle, to: Lifecycle) -> Result<(), Refusal> {
use Lifecycle::*;
let allowed = matches!(
(from, to),
(Draft, InReview)
| (InReview, Draft)
| (Draft, Released)
| (InReview, Released)
| (Released, Superseded)
| (Released, Obsolete)
| (Superseded, Obsolete)
);
if allowed {
return Ok(());
}
Err(match from {
Obsolete => "an obsolete revision is final and cannot change state".to_string(),
Released | Superseded => format!(
"a {} revision is immutable — revise the part instead of moving it to {}",
from.as_str(),
to.as_str()
),
_ => format!(
"a {} revision cannot become {}",
from.as_str(),
to.as_str()
),
})
}
pub fn next_revision_label(previous: Option<&str>) -> String {
let Some(previous) = previous else {
return "A".to_string();
};
let mut chars: Vec<u8> = previous.trim().to_ascii_uppercase().into_bytes();
if chars.is_empty() || chars.iter().any(|c| !c.is_ascii_uppercase()) {
return "A".to_string();
}
let mut index = chars.len();
loop {
if index == 0 {
chars.insert(0, b'A');
break;
}
index -= 1;
if chars[index] == b'Z' {
chars[index] = b'A';
continue;
}
chars[index] += 1;
break;
}
String::from_utf8(chars).expect("ASCII uppercase stays UTF-8")
}
pub fn check_enabled(settings: &crate::model::Settings, to: Lifecycle) -> Result<(), crate::Error> {
if settings.status_options.iter().any(|s| s.state == to && s.enabled) {
Ok(())
} else {
Err(crate::Error::conflict("this lifecycle status is disabled in server settings"))
}
}
pub fn check_options(options: &[crate::model::StatusOption]) -> Result<(), crate::Error> {
let mut names = std::collections::BTreeSet::new();
for state in [Lifecycle::Draft, Lifecycle::InReview, Lifecycle::Released, Lifecycle::Obsolete, Lifecycle::Superseded] {
if options.iter().filter(|s| s.state == state).count() != 1 {
return Err(crate::Error::bad_request("configure each workflow state exactly once"));
}
}
for option in options {
let name = option.name.trim();
if name.is_empty() || name.len() > 80 || !names.insert(name.to_lowercase()) {
return Err(crate::Error::bad_request("status names must be unique, nonempty and at most 80 bytes"));
}
if matches!(option.state, Lifecycle::Draft | Lifecycle::Superseded) && !option.enabled {
return Err(crate::Error::bad_request("the initial and automatic superseded states must stay enabled"));
}
}
Ok(())
}