use std::collections::BTreeMap;
use crate::Engine;
use crate::error::{Diagnostic, Error};
use crate::eval::{
MatchingCache, Settings, Wanted, any_term_short, eligible_per_term, exclusion_reasons,
failing_reasons, start_eligibility,
};
use crate::intervals::Span as MinuteSpan;
use crate::model::{
Offer, OfferEvent, OfferFlag, ReserveKind, ReserveSpan, Response, SCHEMA_VERSION, SlotCheck,
Span,
};
use crate::reasons::{Excluded, Reason, ReasonCode};
use crate::time::{Date, Instant};
pub(crate) fn response(
engine: &Engine,
request: &crate::model::Request,
settings: &Settings<'_>,
warnings: Vec<Diagnostic>,
) -> Result<Response, Error> {
let mut explain = request.explain.as_ref();
let limit = request.limit();
let mut offers = Vec::new();
let mut starts = Vec::new();
let mut truncated = false;
let mut excluded = Vec::new();
let mut reason_count = 0_usize;
let mut excluded_truncated = false;
let mut eligible = Vec::new();
let mut failed = Vec::new();
let mut matching = MatchingCache::default();
let duration = settings.part.duration.minutes();
for start in &settings.candidates {
let own = MinuteSpan::new(start.minutes(), start.minutes().saturating_add(duration))?;
start_eligibility(settings, *start, &own, &mut eligible, &mut failed);
let short = any_term_short(settings, &eligible);
let attendee_blocked = settings.attendees.iter().any(|index| !eligible[*index]);
let past_limit = offers.len() >= limit;
let (assignment, fillable) = if short {
(None, false)
} else if past_limit || attendee_blocked {
(None, matching.can_fill(settings, &eligible))
} else {
let assignment = matching.assignment_at(settings, &eligible);
let fillable = assignment.is_some();
(assignment, fillable)
};
if fillable && !attendee_blocked {
if let Some(assignment) = assignment {
let assigned: Vec<&str> = assignment.iter().flatten().map(String::as_str).collect();
let flags = calendar_flags(settings, &assigned);
let reserve = travel_reserve(settings, *start, &assigned)?;
let eligible_hosts = eligible_per_term(settings, &eligible);
let event = offer_event(settings, *start, eligible_hosts, assignment, reserve)?;
offers.push(Offer {
events: vec![event],
flags,
});
} else {
truncated = true;
}
starts.push(*start);
continue;
}
let Some(limits) = explain else {
continue;
};
let start_reason = match (fillable, attendee_blocked) {
(false, _) if !short => Some(ReasonCode::TermUnfillable),
(true, true) => Some(ReasonCode::AttendeeUnavailable),
_ => None,
};
let mut reasons = exclusion_reasons(settings, *start, &own, &failed);
if let Some(code) = start_reason {
reasons.push(Reason::start_level(code));
}
if reason_count.saturating_add(reasons.len()) > limits.limit {
excluded_truncated = true;
explain = None;
continue;
}
reason_count = reason_count.saturating_add(reasons.len());
excluded.push(Excluded {
start: *start,
part: settings.part.id.clone(),
reasons,
});
}
let dates = date_counts(settings, &starts)?;
Ok(Response {
offers,
dates,
truncated,
excluded,
excluded_truncated,
warnings,
meta: meta(engine),
})
}
pub(crate) fn slot_check(
engine: &Engine,
settings: &Settings<'_>,
start: Instant,
assignment: &[&str],
warnings: Vec<Diagnostic>,
) -> Result<SlotCheck, Error> {
let mut judged: Vec<&str> = settings
.attendees
.iter()
.map(|index| settings.participants[*index].participant.id.as_str())
.collect();
judged.extend_from_slice(assignment);
judged.sort_unstable();
judged.dedup();
let mut reasons = Vec::new();
let mut scratch = Vec::new();
let own = MinuteSpan::new(
start.minutes(),
start
.minutes()
.saturating_add(settings.part.duration.minutes()),
)?;
for id in judged {
let Some(participant) = settings
.participants
.iter()
.find(|participant| participant.participant.id == id)
else {
return Err(Error::malformed_proposal(
"proposal_host_unknown",
format!("the request carries no participant `{id}`"),
"/events".to_owned(),
));
};
scratch.clear();
failing_reasons(participant, start, &own, Wanted::All, &mut scratch);
reasons.append(&mut scratch);
}
Ok(SlotCheck {
valid: reasons.is_empty(),
reasons,
flags: calendar_flags(settings, assignment),
reserve: travel_reserve(settings, start, assignment)?,
warnings,
meta: meta(engine),
})
}
fn meta(engine: &Engine) -> crate::model::Meta {
crate::model::Meta {
engine: crate::VERSION.to_owned(),
schema: SCHEMA_VERSION,
tzdb: engine.time_zone_database().version().to_owned(),
}
}
fn calendar_flags(settings: &Settings<'_>, assigned: &[&str]) -> Vec<OfferFlag> {
if settings.unknown_calendars.is_empty() {
return Vec::new();
}
let unknown = assigned
.iter()
.any(|id| settings.unknown_calendars.contains(*id));
if unknown {
vec![OfferFlag::CalendarUnknown]
} else {
Vec::new()
}
}
fn travel_reserve(
settings: &Settings<'_>,
start: Instant,
assigned: &[&str],
) -> Result<Vec<ReserveSpan>, Error> {
if !settings.has_any_travel {
return Ok(Vec::new());
}
let mut reserve = Vec::new();
let end = start
.minutes()
.saturating_add(settings.part.duration.minutes());
let attendees = settings
.attendees
.iter()
.map(|index| settings.participants[*index].participant.id.as_str());
for id in assigned.iter().copied().chain(attendees) {
let (travel_before, travel_after) = settings.part.travel.for_participant(id);
if travel_before.minutes() > 0 {
let from =
Instant::from_minutes(start.minutes().saturating_sub(travel_before.minutes()))?;
reserve.push(ReserveSpan {
participant: id.to_owned(),
kind: ReserveKind::Travel,
span: Span::new(from, start)?,
});
}
if travel_after.minutes() > 0 {
let from = Instant::from_minutes(end)?;
let until = Instant::from_minutes(end.saturating_add(travel_after.minutes()))?;
reserve.push(ReserveSpan {
participant: id.to_owned(),
kind: ReserveKind::Travel,
span: Span::new(from, until)?,
});
}
}
reserve.sort_by(|left, right| {
left.participant
.cmp(&right.participant)
.then(left.span.start().cmp(&right.span.start()))
});
Ok(reserve)
}
fn offer_event(
settings: &Settings<'_>,
start: Instant,
eligible: Vec<Vec<String>>,
assignment: Vec<Vec<String>>,
reserve: Vec<ReserveSpan>,
) -> Result<OfferEvent, Error> {
let end = Instant::from_minutes(start.minutes() + settings.part.duration.minutes())?;
Ok(OfferEvent {
part: settings.part.id.clone(),
start,
end,
eligible,
assignment,
reserve,
})
}
fn date_counts(
settings: &Settings<'_>,
starts: &[Instant],
) -> Result<Vec<crate::model::DateCount>, Error> {
let mut by_date: BTreeMap<Date, usize> = BTreeMap::new();
for &start in starts {
*by_date
.entry(settings.display.zoned(start).date())
.or_default() += 1;
}
let (mut date, last) = settings
.display
.local_date_bounds(settings.window.start(), settings.window.end())?;
let mut counts = Vec::new();
loop {
if settings.display.date_exists(date) {
let offers = by_date.get(&date).copied().unwrap_or(0);
counts.push(crate::model::DateCount { date, offers });
}
if date >= last {
break;
}
date = date.plus_days(1)?;
}
Ok(counts)
}