use std::cmp::Ordering;
use crate::intervals::Span as MinuteSpan;
use crate::matching;
use crate::reasons::{Reason, ReasonCode, ReasonParams};
use crate::time::{Date, Instant};
use super::ParticipantSettings;
use super::Settings;
use super::allowed::representable;
use super::blocked::{BlockedSpan, blackout_overlapping, block_overlapping, overlaps};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Wanted {
First,
All,
}
impl Wanted {
const fn stops(self) -> bool {
!matches!(self, Self::All)
}
}
pub(crate) fn failing_reasons(
participant: &ParticipantSettings<'_>,
start: Instant,
own: &MinuteSpan,
wanted: Wanted,
out: &mut Vec<Reason>,
) -> bool {
let id = participant.participant.id.as_str();
let occupied_start = own.start().saturating_sub(participant.travel.0);
if occupied_start < participant.lead_min_at {
out.push(cite(
Reason::new(id, ReasonCode::LeadTimeMin),
participant.rules.lead_min_rule.map(|(rule, _)| rule),
));
if wanted.stops() {
return true;
}
}
if let Some((rule, bound)) = &participant.lead_bound
&& !bound.allows(start)
{
out.push(Reason::new(id, ReasonCode::LeadTimeMax).with_rule(*rule));
if wanted.stops() {
return true;
}
}
let own_allowed = participant.inside_windows(own);
if !own_allowed {
out.push(cite(
Reason::new(id, ReasonCode::OutsideWindow),
participant.excluding_window(own),
));
if wanted.stops() {
return true;
}
}
let own_blackout = blackout_overlapping(&participant.blackouts, own);
if let Some(rule) = own_blackout {
out.push(Reason::new(id, ReasonCode::Blackout).with_rule(rule));
if wanted.stops() {
return true;
}
}
let own_block = block_overlapping(&participant.blocked, own);
if let Some(blocked) = own_block {
out.push(Reason::new(id, ReasonCode::Blocked).with_block(blocked.block));
if wanted.stops() {
return true;
}
}
if own_allowed
&& own_blackout.is_none()
&& own_block.is_none()
&& let Some(cause) = travel_conflict(participant, start, own.end())
{
out.push(cause.reason(id));
if wanted.stops() {
return true;
}
}
let Some(occupied) = occupied_span(participant, own) else {
return !out.is_empty();
};
if let Some((blocked, rule)) = clearance_conflict(participant, &occupied) {
out.push(cite(
Reason::new(id, ReasonCode::Clearance).with_block(blocked.block),
rule,
));
if wanted.stops() {
return true;
}
}
if let Some(rule) = crate::rest::rest_conflict(
&participant.rests,
&participant.schedule,
&participant.date_jumps,
&occupied,
) {
out.push(Reason::new(id, ReasonCode::Rest).with_rule(rule));
if wanted.stops() {
return true;
}
}
if let Some(conflict) = cap_conflict(participant, start) {
out.push(conflict.reason(id));
return true;
}
!out.is_empty()
}
fn cap_conflict<'a>(
participant: &'a ParticipantSettings<'_>,
start: Instant,
) -> Option<CapConflict<'a>> {
participant.caps.iter().find_map(|cap| {
cap.exceeded(&participant.schedule, start)
.map(|(used, bucket)| CapConflict {
rule: cap.rule,
used,
limit: cap.limit,
bucket,
})
})
}
struct CapConflict<'a> {
rule: &'a str,
used: u64,
limit: u32,
bucket: Date,
}
impl CapConflict<'_> {
fn reason(&self, id: &str) -> Reason {
Reason::new(id, ReasonCode::CapReached)
.with_rule(self.rule)
.with_params(ReasonParams::CapReached {
used: self.used,
limit: self.limit,
bucket: self.bucket.to_string(),
})
}
}
fn travel_conflict<'a>(
participant: &'a ParticipantSettings<'_>,
start: Instant,
own_end: i64,
) -> Option<TravelConflict<'a>> {
let start_minutes = start.minutes();
let (before, after) = participant.travel;
let spans = [
(before, start_minutes.saturating_sub(before), start_minutes),
(after, own_end, own_end.saturating_add(after)),
];
for (minutes, from, to) in spans {
if minutes == 0 {
continue;
}
let Ok(span) = MinuteSpan::new(from, to) else {
continue;
};
if !participant.inside_windows(&span) {
return Some(TravelConflict::OutsideWindow(
participant.excluding_window(&span),
));
}
if let Some(rule) = blackout_overlapping(&participant.blackouts, &span) {
return Some(TravelConflict::Blackout(rule));
}
if let Some(blocked) = block_overlapping(&participant.blocked, &span) {
return Some(TravelConflict::Blocked(blocked));
}
}
None
}
enum TravelConflict<'a> {
OutsideWindow(Option<&'a str>),
Blackout(&'a str),
Blocked(&'a BlockedSpan<'a>),
}
impl TravelConflict<'_> {
fn reason(&self, id: &str) -> Reason {
let reason = Reason::new(id, ReasonCode::Travel);
match self {
Self::OutsideWindow(rule) => cite(reason, *rule),
Self::Blackout(rule) => reason.with_rule(*rule),
Self::Blocked(blocked) => reason.with_block(blocked.block),
}
}
}
fn clearance_conflict<'a, 'b>(
participant: &'b ParticipantSettings<'a>,
occupied: &MinuteSpan,
) -> Option<(&'b BlockedSpan<'a>, Option<&'a str>)> {
let mut best: Option<(usize, &'b BlockedSpan<'a>, Option<&'a str>)> = None;
for blocked in participant.blocked.widened_candidates(occupied) {
if !overlaps(&blocked.widened, occupied) || overlaps(&blocked.occupied, occupied) {
continue;
}
let supplier = clearance_rule(participant, blocked, occupied);
let position = supplier.map_or(usize::MAX, |(_, position)| position);
match best {
Some((seen, _, _)) if seen <= position => {}
_ => best = Some((position, blocked, supplier.map(|(rule, _)| rule))),
}
}
best.map(|(_, blocked, rule)| (blocked, rule))
}
fn clearance_rule<'a>(
participant: &ParticipantSettings<'a>,
blocked: &BlockedSpan<'a>,
occupied: &MinuteSpan,
) -> crate::rules::Supplier<'a> {
let rules = participant.rules.clearance_rules;
let clearance = participant.rules.clearance;
let (gap, gap_rule) = if occupied.end() <= blocked.occupied.start() {
(clearance.after, rules.after)
} else {
(clearance.before, rules.before)
};
match gap.cmp(&clearance.min_gap) {
Ordering::Greater => gap_rule,
Ordering::Less => rules.min_gap,
Ordering::Equal => [gap_rule, rules.min_gap]
.into_iter()
.flatten()
.min_by_key(|(_, position)| *position),
}
}
fn cite(reason: Reason, rule: Option<&str>) -> Reason {
match rule {
Some(rule) => reason.with_rule(rule),
None => reason,
}
}
pub(crate) fn is_participant_eligible(
participant: &ParticipantSettings<'_>,
start: Instant,
own: &MinuteSpan,
) -> bool {
let occupied_start = own.start().saturating_sub(participant.travel.0);
if occupied_start < participant.lead_min_at {
return false;
}
if let Some((_, bound)) = &participant.lead_bound
&& !bound.allows(start)
{
return false;
}
let Some(occupied) = occupied_span(participant, own) else {
return true;
};
if !participant.usable.contains_span(&occupied) {
return false;
}
if participant.cap_always_blocked || participant.cap_blocked.contains_minute(start.minutes()) {
return false;
}
if occupied.end() - occupied.start() == participant.occupied_len {
if participant
.rest_self_blocked
.contains_minute(occupied.start())
{
return false;
}
} else {
for rest in &participant.rests {
if rest.late.overlaps(&occupied)
&& rest.early.overlaps(&occupied)
&& crate::rest::rest_self_conflict(
rest,
&participant.schedule,
&participant.date_jumps,
&occupied,
)
{
return false;
}
}
}
true
}
fn occupied_span(participant: &ParticipantSettings<'_>, own: &MinuteSpan) -> Option<MinuteSpan> {
let from = own.start().saturating_sub(participant.travel.0);
let until = own.end().saturating_add(participant.travel.1);
representable(MinuteSpan::new(from, until).ok()?)
}
pub(crate) fn start_eligibility(
settings: &Settings<'_>,
start: Instant,
own: &MinuteSpan,
eligible: &mut Vec<bool>,
failed: &mut Vec<usize>,
) {
eligible.clear();
eligible.resize(settings.participants.len(), false);
failed.clear();
for &index in &settings.reported {
let participant = &settings.participants[index];
if is_participant_eligible(participant, start, own) {
eligible[index] = true;
} else {
failed.push(index);
}
}
}
pub(crate) fn exclusion_reasons(
settings: &Settings<'_>,
start: Instant,
own: &MinuteSpan,
failed: &[usize],
) -> Vec<Reason> {
let mut reasons = Vec::new();
let mut scratch = Vec::new();
for &index in failed {
scratch.clear();
let still_fails = failing_reasons(
&settings.participants[index],
start,
own,
Wanted::First,
&mut scratch,
);
debug_assert!(still_fails, "an ineligible participant reports no reason");
reasons.append(&mut scratch);
}
reasons
}
pub(crate) fn any_term_short(settings: &Settings<'_>, eligible: &[bool]) -> bool {
settings.terms.iter().any(|term| {
term.hosts
.iter()
.filter(|index| eligible[**index])
.take(term.count)
.count()
< term.count
})
}
pub(crate) fn eligible_per_term(settings: &Settings<'_>, eligible: &[bool]) -> Vec<Vec<String>> {
settings
.terms
.iter()
.map(|term| {
term.hosts
.iter()
.filter(|index| eligible[**index])
.map(|index| settings.participants[*index].participant.id.clone())
.collect()
})
.collect()
}
#[derive(Default)]
pub(crate) struct MatchingCache {
shape: Shape,
known: bool,
}
#[derive(Default)]
struct Shape {
hosts: Vec<Vec<usize>>,
slots: usize,
counts: Vec<usize>,
answer: ShapeAnswer,
}
#[derive(Default)]
enum ShapeAnswer {
#[default]
Unasked,
Unfillable,
Fillable,
Assigned(Vec<Vec<String>>),
}
impl ShapeAnswer {
const fn fillable(&self) -> Option<bool> {
match self {
Self::Unasked => None,
Self::Unfillable => Some(false),
Self::Fillable | Self::Assigned(_) => Some(true),
}
}
}
impl MatchingCache {
fn matches_shape(&self, settings: &Settings<'_>, eligible: &[bool]) -> bool {
self.known
&& self.shape.slots == settings.slots
&& self.shape.hosts.len() == settings.terms.len()
&& self.shape.counts.len() == settings.terms.len()
&& settings
.terms
.iter()
.zip(&self.shape.counts)
.all(|(term, count)| term.count == *count)
&& settings
.terms
.iter()
.zip(&self.shape.hosts)
.all(|(term, cached)| {
term.hosts_by_weight
.iter()
.copied()
.filter(|&index| eligible[index])
.take(settings.slots)
.eq(cached.iter().copied())
})
}
fn load(&mut self, settings: &Settings<'_>, eligible: &[bool]) -> &mut Shape {
debug_assert_eq!(
eligible.len(),
settings.participants.len(),
"eligibility is judged for every participant the settings carry"
);
if !self.matches_shape(settings, eligible) {
self.shape.hosts.resize_with(settings.terms.len(), Vec::new);
for (term, slot) in settings.terms.iter().zip(&mut self.shape.hosts) {
slot.clear();
slot.extend(
term.hosts_by_weight
.iter()
.copied()
.filter(|&index| eligible[index])
.take(settings.slots),
);
}
self.shape.slots = settings.slots;
self.shape.counts.clear();
self.shape
.counts
.extend(settings.terms.iter().map(|term| term.count));
self.shape.answer = ShapeAnswer::Unasked;
self.known = true;
}
&mut self.shape
}
pub(crate) fn assignment_at(
&mut self,
settings: &Settings<'_>,
eligible: &[bool],
) -> Option<Vec<Vec<String>>> {
if settings.terms_disjoint {
return disjoint_assignment(settings, eligible);
}
let shape = self.load(settings, eligible);
match &shape.answer {
ShapeAnswer::Assigned(assignment) => return Some(assignment.clone()),
ShapeAnswer::Unfillable => return None,
ShapeAnswer::Unasked | ShapeAnswer::Fillable => {}
}
let candidates = candidates_of(settings, &shape.hosts);
let terms = terms(settings, &candidates);
let assignment = matching::assign(&terms).map(|assignment| assignment.terms);
shape.answer = match &assignment {
Some(assignment) => ShapeAnswer::Assigned(assignment.clone()),
None => ShapeAnswer::Unfillable,
};
assignment
}
pub(crate) fn can_fill(&mut self, settings: &Settings<'_>, eligible: &[bool]) -> bool {
if settings.terms_disjoint {
return !any_term_short(settings, eligible);
}
let shape = self.load(settings, eligible);
if let Some(fillable) = shape.answer.fillable() {
return fillable;
}
let candidates = candidates_of(settings, &shape.hosts);
let terms = terms(settings, &candidates);
let fillable = matching::jointly_fillable(&terms);
shape.answer = if fillable {
ShapeAnswer::Fillable
} else {
ShapeAnswer::Unfillable
};
fillable
}
}
fn disjoint_assignment(settings: &Settings<'_>, eligible: &[bool]) -> Option<Vec<Vec<String>>> {
settings
.terms
.iter()
.map(|term| {
let mut chosen: Vec<usize> = term
.hosts_by_weight
.iter()
.copied()
.filter(|index| eligible[*index])
.take(term.count)
.collect();
if chosen.len() < term.count {
return None;
}
chosen.sort_by(|left, right| {
settings.participants[*left]
.participant
.id
.cmp(&settings.participants[*right].participant.id)
});
Some(
chosen
.into_iter()
.map(|index| settings.participants[index].participant.id.clone())
.collect(),
)
})
.collect()
}
fn candidates_of<'a>(
settings: &'a Settings<'_>,
hosts: &'a [Vec<usize>],
) -> Vec<Vec<matching::Candidate<'a>>> {
hosts
.iter()
.map(|term| {
term.iter()
.map(|index| matching::Candidate {
id: settings.participants[*index].participant.id.as_str(),
weight: settings.weights[*index],
})
.collect()
})
.collect()
}
fn terms<'a>(
settings: &Settings<'_>,
candidates: &'a [Vec<matching::Candidate<'a>>],
) -> Vec<matching::Term<'a>> {
settings
.terms
.iter()
.zip(candidates)
.map(|(term, candidates)| matching::Term {
count: term.count,
candidates: candidates.as_slice(),
})
.collect()
}
#[cfg(all(test, feature = "bundled-tzdb"))]
mod tests {
use super::{Wanted, failing_reasons, is_participant_eligible};
use crate::Engine;
use crate::eval::slot_settings;
use crate::intervals::Span as MinuteSpan;
use crate::model::{Goal, Part, Participant, Request, Requirement, Span, Term};
use crate::reasons::ReasonCode;
use crate::tags::{Role, Selector};
use crate::time::{Duration, Instant, ZoneName};
#[test]
fn every_wanted_mode_answers_whether_the_participant_can_book() {
let engine = Engine::builder().build().unwrap();
let zone = ZoneName::new("UTC").unwrap();
let at = |count: i64| Instant::from_minutes(Instant::MIN.minutes() + count).unwrap();
let start = at(10 * 60);
let mut participant = Participant::new("rich", zone.clone());
participant.calendar = Some(Vec::new());
let mut request = Request::new(
at(11 * 60),
Goal::new(
zone,
Span::new(at(0), at(24 * 60)).unwrap(),
vec![Part::new(
Duration::from_minutes(30),
Requirement::new(vec![Term::at_least(1, Selector::role(Role::Host))]),
)],
),
);
request.participants = vec![participant];
let settings = slot_settings(&engine, &request, start).unwrap();
let own = MinuteSpan::new(start.minutes(), start.minutes() + 30).unwrap();
assert!(!is_participant_eligible(
&settings.participants[0],
start,
&own
));
for wanted in [Wanted::First, Wanted::All] {
let mut reasons = Vec::new();
let failed =
failing_reasons(&settings.participants[0], start, &own, wanted, &mut reasons);
assert!(
failed,
"{wanted:?}: a start an hour in the past is excluded"
);
assert_eq!(reasons.len(), 1);
assert_eq!(reasons[0].code, ReasonCode::LeadTimeMin);
}
}
}