use jiff::{SignedDuration, Timestamp};
use crate::alert::alerts;
use crate::model::{
Attribution, Connection, Departure, JourneyResult, JourneyStop, Leg, Location, StopEvent,
StopMatch, Time, dhid, minutes, non_empty,
};
use crate::status::{self, Part};
use crate::{modes, time};
fn line(product: Option<&hafas::Product>) -> Option<String> {
let product = product?;
non_empty(product.line.as_deref())
.or_else(|| non_empty(product.display_number.as_deref()))
.or_else(|| non_empty(product.name.as_deref()))
}
fn operator(product: Option<&hafas::Product>) -> Option<String> {
non_empty(product?.operator.as_deref())
}
fn mode(product: Option<&hafas::Product>) -> String {
modes::of_class(product.and_then(hafas::Product::class)).to_owned()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct Times {
scheduled: Timestamp,
actual: Timestamp,
realtime: bool,
}
impl Times {
fn new(
date: &str,
time: &str,
rt_date: Option<&str>,
rt_time: Option<&str>,
realtime: bool,
) -> Self {
let scheduled = time::parse(date, time).unwrap_or_default();
let actual = rt_time
.and_then(|rt_time| time::parse(rt_date.unwrap_or(date), rt_time))
.unwrap_or(scheduled);
Self {
scheduled,
actual,
realtime: realtime || rt_time.is_some(),
}
}
fn time(self, realtime: bool) -> Time {
Time::new(self.scheduled, self.actual, realtime)
}
}
pub(crate) fn stop_id(stop: &hafas::StopLocation) -> String {
non_empty(Some(&stop.ext_id)).unwrap_or_else(|| stop.id.clone())
}
impl From<&hafas::StopLocation> for StopMatch {
fn from(stop: &hafas::StopLocation) -> Self {
Self {
id: stop_id(stop),
name: stop.name.clone(),
area: None,
dhid: dhid(&stop.alt_id),
lat: stop.lat.unwrap_or_default(),
lon: stop.lon.unwrap_or_default(),
modes: modes::of_mask(stop.products.unwrap_or_default()),
}
}
}
impl From<&hafas::OriginDest> for Location {
fn from(place: &hafas::OriginDest) -> Self {
Self {
id: place.ext_id.clone().or_else(|| place.id.clone()),
name: place.name.clone(),
dhid: dhid(&place.alt_id),
}
}
}
impl Departure {
pub(crate) fn new(
event: &hafas::BoardEvent,
headsign: Option<&str>,
origin: Option<&str>,
) -> Self {
let product = event.product_at_stop.as_ref().or(event.product.first());
let times = Times::new(
&event.date,
&event.time,
event.rt_date.as_deref(),
event.rt_time.as_deref(),
event.prognosis_type.is_some() || event.cancelled,
);
Self {
mode: mode(product),
line: line(product),
operator: operator(product),
headsign: non_empty(headsign),
origin: non_empty(origin),
trip_id: event.journey_detail_ref.reference.clone(),
stop: StopEvent {
id: event
.stop_ext_id
.clone()
.or_else(|| non_empty(Some(&event.stopid))),
name: event.stop.clone(),
dhid: dhid(&event.alt_id),
time: times.time(times.realtime),
track: event.rt_track.clone().or_else(|| event.track.clone()),
scheduled_track: event.track.clone(),
cancelled: event.cancelled,
},
realtime: times.realtime,
cancelled: event.cancelled,
trip_cancelled: event.cancelled && !event.part_cancelled,
alerts: alerts([&event.messages]),
}
}
}
fn is_ride(leg: &hafas::Leg) -> bool {
leg.kind == "JNY"
}
fn place_times(place: &hafas::OriginDest) -> Times {
Times::new(
&place.date,
&place.time,
place.rt_date.as_deref(),
place.rt_time.as_deref(),
place.prognosis_type.is_some(),
)
}
fn leg(leg: &hafas::Leg) -> (Leg, Part) {
let ride = is_ride(leg);
let start = place_times(&leg.origin);
let end = place_times(&leg.destination);
let realtime = ride && (start.realtime || end.realtime || leg.cancelled);
let from_cancelled = ride && (leg.origin.cancelled || leg.origin.cancelled_departure);
let to_cancelled = ride && (leg.destination.cancelled || leg.destination.cancelled_arrival);
let event = |place: &hafas::OriginDest, times: Times, cancelled| StopEvent {
id: place.ext_id.clone().or_else(|| place.id.clone()),
name: place.name.clone(),
dhid: dhid(&place.alt_id),
time: times.time(realtime),
track: place.rt_track.clone().or_else(|| place.track.clone()),
scheduled_track: place.track.clone(),
cancelled,
};
let product = leg.product.first();
let output = Leg {
mode: if ride {
mode(product)
} else if matches!(leg.kind.as_str(), "WALK" | "TRSF") {
"WALK".to_owned()
} else {
leg.kind.to_ascii_uppercase()
},
line: ride.then(|| line(product)).flatten(),
operator: ride.then(|| operator(product)).flatten(),
headsign: ride.then(|| non_empty(leg.direction.as_deref())).flatten(),
trip_id: leg
.journey_detail_ref
.as_ref()
.map(|reference| reference.reference.clone()),
from: event(&leg.origin, start, from_cancelled),
to: event(&leg.destination, end, to_cancelled),
duration_minutes: minutes(end.actual.as_second() - start.actual.as_second()),
realtime,
cancelled: ride && leg.cancelled,
stay_seated: false,
alerts: alerts([&leg.messages, &leg.origin.message, &leg.destination.message]),
};
let part = Part {
transit: ride,
scheduled_start: start.scheduled,
start: start.actual,
scheduled_end: end.scheduled,
end: end.actual,
realtime,
cancelled: ride && leg.cancelled,
from_cancelled,
to_cancelled,
unreachable: ride && !leg.reachable,
};
(output, part)
}
pub(crate) fn departure(trip: &hafas::Trip) -> Timestamp {
trip.legs
.first()
.map(|leg| &leg.origin)
.or(trip.origin.as_ref())
.map(|place| place_times(place).scheduled)
.unwrap_or_default()
}
impl Connection {
pub(crate) fn new(trip: &hafas::Trip, now: Timestamp, delay_threshold_minutes: u32) -> Self {
let (legs, parts): (Vec<Leg>, Vec<Part>) = trip.legs.iter().map(leg).unzip();
let evaluation = status::evaluate(&parts, now, delay_threshold_minutes);
let first_ride = parts.iter().find(|part| part.transit);
let last_ride = parts.iter().rev().find(|part| part.transit);
let ends = |place: Option<&hafas::OriginDest>| place.map(place_times).unwrap_or_default();
let (start, end) = match (parts.first(), parts.last()) {
(Some(first), Some(last)) => {
let before = first_ride
.filter(|_| !first.transit)
.map_or(SignedDuration::ZERO, |ride| {
ride.start.duration_since(ride.scheduled_start)
});
let after = last_ride
.filter(|_| !last.transit)
.map_or(SignedDuration::ZERO, |ride| {
ride.end.duration_since(ride.scheduled_end)
});
(
Times {
scheduled: first.scheduled_start,
actual: first.start.saturating_add(before).unwrap_or(first.start),
realtime: false,
},
Times {
scheduled: last.scheduled_end,
actual: last.end.saturating_add(after).unwrap_or(last.end),
realtime: false,
},
)
}
_ => (ends(trip.origin.as_ref()), ends(trip.destination.as_ref())),
};
let rides = parts.iter().filter(|part| part.transit).count();
Self {
status: evaluation.status,
reasons: evaluation.reasons,
realtime: evaluation.realtime,
departure: start.time(first_ride.is_some_and(|part| part.realtime)),
arrival: end.time(last_ride.is_some_and(|part| part.realtime)),
duration_minutes: minutes(end.actual.as_second() - start.actual.as_second()),
transfers: trip.transfer_count.map_or_else(
|| i64::try_from(rides.saturating_sub(1)).unwrap_or_default(),
i64::from,
),
max_delay_minutes: evaluation.max_delay_minutes,
legs,
alerts: alerts([&trip.messages]),
recheck_token: non_empty(trip.ctx_recon.as_deref()),
}
}
}
impl JourneyStop {
fn new(stop: &hafas::Stop, day: &str) -> Self {
let side = |date: Option<&str>,
time: Option<&str>,
rt_date: Option<&str>,
rt_time: Option<&str>,
prognosis: bool| {
let date = date.unwrap_or(day);
let times = Times::new(date, time?, rt_date, rt_time, prognosis);
Some((times.time(times.realtime), times.realtime))
};
let arrival = side(
stop.arr_date.as_deref(),
stop.arr_time.as_deref(),
stop.rt_arr_date.as_deref(),
stop.rt_arr_time.as_deref(),
stop.arr_prognosis_type.is_some(),
);
let departure = side(
stop.dep_date.as_deref(),
stop.dep_time.as_deref(),
stop.rt_dep_date.as_deref(),
stop.rt_dep_time.as_deref(),
stop.dep_prognosis_type.is_some(),
);
let sides = [
(arrival.is_some(), stop.cancelled_arrival),
(departure.is_some(), stop.cancelled_departure),
];
let present = sides.iter().filter(|(present, _)| *present);
let all_cancelled =
present.clone().count() > 0 && present.clone().all(|(_, cancelled)| *cancelled);
Self {
id: non_empty(Some(&stop.ext_id)).or_else(|| non_empty(Some(&stop.id))),
name: stop.name.clone(),
dhid: dhid(&stop.alt_id),
arrival: arrival.map(|(time, _)| time),
departure: departure.map(|(time, _)| time),
track: stop
.rt_dep_track
.clone()
.or_else(|| stop.dep_track.clone())
.or_else(|| stop.rt_arr_track.clone())
.or_else(|| stop.arr_track.clone()),
scheduled_track: stop.dep_track.clone().or_else(|| stop.arr_track.clone()),
cancelled: stop.cancelled || all_cancelled,
}
}
fn realtime(stop: &hafas::Stop) -> bool {
stop.rt_arr_time.is_some()
|| stop.rt_dep_time.is_some()
|| stop.arr_prognosis_type.is_some()
|| stop.dep_prognosis_type.is_some()
}
}
impl JourneyResult {
pub(crate) fn new(trip_id: &str, journey: &hafas::Journey, warnings: Vec<String>) -> Self {
let product = journey
.product
.first()
.or_else(|| journey.names.iter().find_map(|name| name.product.as_ref()));
let mut stops: Vec<JourneyStop> = journey
.stops
.iter()
.map(|stop| JourneyStop::new(stop, &journey.day_of_operation))
.collect();
if let Some(stop) = stops.first_mut() {
stop.arrival = None;
}
if let Some(stop) = stops.last_mut() {
stop.departure = None;
}
let headsign = journey
.directions
.first()
.and_then(|direction| non_empty(Some(&direction.value)))
.or_else(|| journey.stops.last().map(|stop| stop.name.clone()));
Self {
trip_id: trip_id.to_owned(),
mode: mode(product),
line: line(product),
operator: operator(product),
headsign,
realtime: journey.stops.iter().any(JourneyStop::realtime) || journey.cancelled,
cancelled: journey.cancelled,
stops,
alerts: alerts([&journey.messages]),
realtime_as_of: time::plan_rt(journey.info.plan_rt_ts.as_deref()),
attribution: Attribution::default(),
warnings,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn place(time: &str, rt_time: Option<&str>) -> hafas::OriginDest {
hafas::OriginDest {
name: "Halt".into(),
ext_id: Some("3000010".into()),
date: "2026-11-28".into(),
time: time.into(),
rt_time: rt_time.map(str::to_owned),
..hafas::OriginDest::default()
}
}
fn ride(from: &str, to: &str) -> hafas::Leg {
hafas::Leg {
origin: place(from, None),
destination: place(to, None),
kind: "JNY".into(),
reachable: true,
..hafas::Leg::default()
}
}
#[test]
fn takes_the_hafas_id_without_an_external_one() {
let stop = hafas::StopLocation {
id: "A=1@L=1@".into(),
..hafas::StopLocation::default()
};
assert_eq!(stop_id(&stop), "A=1@L=1@");
let event = hafas::BoardEvent {
stopid: "A=1@L=2@".into(),
date: "2026-11-28".into(),
time: "08:00:00".into(),
..hafas::BoardEvent::default()
};
let departure = Departure::new(&event, None, None);
assert_eq!(departure.stop.id.as_deref(), Some("A=1@L=2@"));
}
#[test]
fn a_journey_takes_its_product_from_the_names() {
let journey = hafas::Journey {
names: vec![hafas::Name {
product: Some(hafas::Product {
line: Some("S8".into()),
..hafas::Product::default()
}),
..hafas::Name::default()
}],
..hafas::Journey::default()
};
let result = JourneyResult::new("x", &journey, Vec::new());
assert_eq!(result.line.as_deref(), Some("S8"));
assert_eq!(result.stops, []);
assert_eq!(result.headsign, None);
let journey = hafas::Journey {
stops: vec![hafas::Stop {
name: "Ende".into(),
..hafas::Stop::default()
}],
..journey
};
let result = JourneyResult::new("x", &journey, Vec::new());
assert_eq!(result.headsign.as_deref(), Some("Ende"));
}
#[test]
fn walks_have_no_line_and_no_realtime() {
let walk = hafas::Leg {
kind: "TRSF".into(),
..ride("08:00:00", "08:05:00")
};
let (output, part) = leg(&walk);
assert_eq!(output.mode, "WALK");
assert_eq!(output.line, None);
assert!(!output.realtime);
assert!(!part.transit);
assert_eq!(output.duration_minutes, 5);
let bike = hafas::Leg {
kind: "bike".into(),
..walk
};
assert_eq!(leg(&bike).0.mode, "BIKE");
}
#[test]
fn a_ride_with_realtime_data_has_delays() {
let late = hafas::Leg {
destination: place("08:10:00", Some("08:13:00")),
reachable: false,
..ride("08:00:00", "08:10:00")
};
let (output, part) = leg(&late);
assert!(output.realtime);
assert_eq!(output.to.time.delay_minutes, Some(3));
assert_eq!(output.from.time.delay_minutes, Some(0));
assert!(part.unreachable);
}
#[test]
fn a_trip_without_legs_takes_its_ends() {
let trip = hafas::Trip {
origin: Some(place("08:00:00", None)),
destination: Some(place("08:30:00", None)),
transfer_count: None,
..hafas::Trip::default()
};
let connection = Connection::new(&trip, Timestamp::default(), 2);
assert_eq!(connection.duration_minutes, 30);
assert_eq!(connection.transfers, 0);
assert_eq!(connection.arrival.delay_minutes, None);
assert_eq!(
departure(&trip),
time::parse("2026-11-28", "08:00").unwrap()
);
assert_eq!(departure(&hafas::Trip::default()), Timestamp::default());
let empty = Connection::new(&hafas::Trip::default(), Timestamp::default(), 2);
assert_eq!(empty.duration_minutes, 0);
}
#[test]
fn walks_at_the_ends_move_with_the_ride() {
let walk = |from: &str, to: &str| hafas::Leg {
kind: "WALK".into(),
..ride(from, to)
};
let late = hafas::Leg {
origin: place("08:00:00", Some("08:04:00")),
destination: place("08:10:00", Some("08:13:00")),
..ride("08:00:00", "08:10:00")
};
let trip = hafas::Trip {
legs: vec![
walk("07:55:00", "08:00:00"),
late,
walk("08:10:00", "08:15:00"),
],
messages: vec![hafas::Message {
id: "1".into(),
act: true,
head: Some("Bauarbeiten".into()),
..hafas::Message::default()
}],
..hafas::Trip::default()
};
let connection = Connection::new(&trip, Timestamp::default(), 2);
assert_eq!(connection.departure.delay_minutes, Some(4));
assert_eq!(connection.arrival.delay_minutes, Some(3));
assert_eq!(connection.duration_minutes, 19);
assert_eq!(connection.alerts.len(), 1);
assert_eq!(connection.alerts[0].header, "Bauarbeiten");
}
#[test]
fn counts_transfers_between_rides() {
let trip = hafas::Trip {
legs: vec![ride("08:00:00", "08:10:00"), ride("08:15:00", "08:20:00")],
..hafas::Trip::default()
};
let connection = Connection::new(&trip, Timestamp::default(), 2);
assert_eq!(connection.transfers, 1);
assert_eq!(connection.recheck_token, None);
}
#[test]
fn a_stop_whose_events_are_all_cancelled_is_skipped() {
let stop = |arr: bool, dep: bool, cancelled_arrival, cancelled_departure| hafas::Stop {
arr_time: arr.then(|| "08:00:00".to_owned()),
dep_time: dep.then(|| "08:01:00".to_owned()),
cancelled_arrival,
cancelled_departure,
..hafas::Stop::default()
};
let skipped = |stop: &hafas::Stop| JourneyStop::new(stop, "2026-11-28").cancelled;
assert!(skipped(&stop(true, true, true, true)));
assert!(!skipped(&stop(true, true, true, false)));
assert!(skipped(&stop(false, true, false, true)));
assert!(!skipped(&stop(false, false, true, true)));
}
#[test]
fn names_lines_from_what_there_is() {
let product =
|line: Option<&str>, number: Option<&str>, name: Option<&str>| hafas::Product {
line: line.map(str::to_owned),
display_number: number.map(str::to_owned),
name: name.map(str::to_owned),
..hafas::Product::default()
};
assert_eq!(
line(Some(&product(Some("21"), None, Some("Tram 21")))).as_deref(),
Some("21")
);
assert_eq!(
line(Some(&product(None, Some("X17"), None))).as_deref(),
Some("X17")
);
assert_eq!(
line(Some(&product(Some(""), None, Some("RE 30")))).as_deref(),
Some("RE 30")
);
assert_eq!(line(None), None);
assert_eq!(mode(None), modes::OTHER);
}
}