use crate::model::Block;
use crate::tags::Tag;
use crate::time::Instant;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ReasonCode {
LeadTimeMin,
LeadTimeMax,
OutsideWindow,
Blackout,
Blocked,
Travel,
Clearance,
Rest,
CapReached,
AttendeeUnavailable,
TermUnfillable,
}
impl ReasonCode {
pub const ALL: [Self; 11] = [
Self::LeadTimeMin,
Self::LeadTimeMax,
Self::OutsideWindow,
Self::Blackout,
Self::Blocked,
Self::Travel,
Self::Clearance,
Self::Rest,
Self::CapReached,
Self::AttendeeUnavailable,
Self::TermUnfillable,
];
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::LeadTimeMin => "lead_time_min",
Self::LeadTimeMax => "lead_time_max",
Self::OutsideWindow => "outside_window",
Self::Blackout => "blackout",
Self::Blocked => "blocked",
Self::Travel => "travel",
Self::Clearance => "clearance",
Self::Rest => "rest",
Self::CapReached => "cap_reached",
Self::AttendeeUnavailable => "attendee_unavailable",
Self::TermUnfillable => "term_unfillable",
}
}
const fn text(self) -> &'static str {
match self {
Self::LeadTimeMin => "starts before the minimum notice allows",
Self::LeadTimeMax => "starts after the latest start the horizon allows",
Self::OutsideWindow => "outside the participant's window",
Self::Blackout => "inside a blackout",
Self::Blocked => "blocked by an existing event",
Self::Travel => "travel time is not clear",
Self::Clearance => "too close to an existing event",
Self::Rest => "too early after a late finish",
Self::CapReached => "would take the participant past a workload cap",
Self::AttendeeUnavailable => "an attendee the booking needs is not available",
Self::TermUnfillable => "no distinct hosts can fill every requirement term",
}
}
}
impl core::fmt::Display for ReasonCode {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reason {
pub participant: Option<String>,
pub code: ReasonCode,
pub rule: Option<String>,
pub event_key: Option<String>,
pub tags: Vec<Tag>,
pub params: Option<ReasonParams>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReasonParams {
CapReached {
used: u64,
limit: u32,
bucket: String,
},
}
impl Reason {
#[must_use]
pub fn new(participant: impl Into<String>, code: ReasonCode) -> Self {
Self {
participant: Some(participant.into()),
code,
rule: None,
event_key: None,
tags: Vec::new(),
params: None,
}
}
#[must_use]
pub fn start_level(code: ReasonCode) -> Self {
Self {
participant: None,
code,
rule: None,
event_key: None,
tags: Vec::new(),
params: None,
}
}
#[must_use]
pub fn with_rule(mut self, rule: impl Into<String>) -> Self {
self.rule = Some(rule.into());
self
}
#[must_use]
pub fn with_block(mut self, block: &Block) -> Self {
self.event_key.clone_from(&block.event_key);
self.tags.clone_from(&block.tags);
self
}
#[must_use]
pub fn with_params(mut self, params: ReasonParams) -> Self {
self.params = Some(params);
self
}
}
impl core::fmt::Display for Reason {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(participant) = &self.participant {
write!(f, "{participant}: ")?;
}
f.write_str(self.code.text())?;
if let Some(rule) = &self.rule {
write!(f, " (rule `{rule}`)")?;
}
if let Some(event_key) = &self.event_key {
write!(f, " (event `{event_key}`)")?;
}
if let Some(params) = &self.params {
match params {
ReasonParams::CapReached {
used,
limit,
bucket,
} => write!(f, " (used {used} of {limit} in {bucket})")?,
}
}
if !self.tags.is_empty() {
let tags: Vec<&str> = self.tags.iter().map(Tag::as_str).collect();
write!(f, " [{}]", tags.join(", "))?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Excluded {
pub start: Instant,
pub part: String,
pub reasons: Vec<Reason>,
}
#[cfg(test)]
mod tests {
use super::{Reason, ReasonCode, ReasonParams};
#[test]
fn the_registry_lists_the_codes_in_precedence_order() {
let codes: Vec<&str> = ReasonCode::ALL.iter().map(ReasonCode::as_str).collect();
assert_eq!(
codes,
[
"lead_time_min",
"lead_time_max",
"outside_window",
"blackout",
"blocked",
"travel",
"clearance",
"rest",
"cap_reached",
"attendee_unavailable",
"term_unfillable"
]
);
assert!(
ReasonCode::ALL.windows(2).all(|pair| pair[0] < pair[1]),
"the registry and the derived ordering disagree"
);
}
#[test]
fn a_cap_reason_reports_its_bucket_and_usage() {
let reason = Reason::new("ana", ReasonCode::CapReached)
.with_rule("r_cap")
.with_params(ReasonParams::CapReached {
used: 2,
limit: 2,
bucket: "2027-03-09".to_owned(),
});
let Some(ReasonParams::CapReached {
used,
limit,
bucket,
}) = reason.params.as_ref()
else {
panic!("a cap reason carries cap parameters");
};
assert_eq!(*used, 2);
assert_eq!(*limit, 2);
assert_eq!(bucket, "2027-03-09");
assert_eq!(
reason.to_string(),
"ana: would take the participant past a workload cap (rule `r_cap`) \
(used 2 of 2 in 2027-03-09)"
);
}
#[test]
fn a_reason_reads_as_english() {
let reason = Reason::new("tom", ReasonCode::Blocked);
assert_eq!(reason.to_string(), "tom: blocked by an existing event");
assert_eq!(
Reason::new("tom", ReasonCode::Travel)
.with_rule("r_hours")
.to_string(),
"tom: travel time is not clear (rule `r_hours`)"
);
let start_level = Reason::start_level(ReasonCode::AttendeeUnavailable);
assert_eq!(start_level.participant, None);
assert_eq!(
start_level.to_string(),
"an attendee the booking needs is not available"
);
}
#[test]
fn a_block_caused_reason_carries_the_event_key_and_tags() {
use crate::model::{Block, Span};
use crate::tags::Tag;
use crate::time::Instant;
let mut block = Block::new(Span::new(Instant::MIN, Instant::MAX).unwrap());
block.event_key = Some("evt_91".to_owned());
block.tags = vec![Tag::new("veto/crm-freeze").unwrap()];
let reason = Reason::new("ana", ReasonCode::Clearance).with_block(&block);
assert_eq!(reason.event_key.as_deref(), Some("evt_91"));
assert_eq!(reason.tags, block.tags);
assert_eq!(
reason.to_string(),
"ana: too close to an existing event (event `evt_91`) [veto/crm-freeze]"
);
}
}