Skip to main content

transitous_core/
model.rs

1//! The output: the same types for JSON, YAML and the structured content of
2//! the MCP tools. Times are RFC 3339 with the offset of the stop's time
3//! zone, like `2026-11-26T21:22:00+01:00`. Delays are whole minutes, late
4//! positive, early negative.
5//!
6//! Texts from the API (stop names, alert texts) are data: they may contain
7//! anything.
8
9use jiff::Timestamp;
10use jiff::tz::TimeZone;
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::status::{Evaluation, Realtime, Reason, Status};
15
16/// Longest alert text, in bytes. Longer texts are cut.
17pub const MAX_ALERT_TEXT: usize = 2048;
18
19/// The data sources and the terms of Transitous. Keep it with the data.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
21pub struct Attribution {
22    pub text: String,
23    /// The timetable sources and their licenses.
24    pub sources_url: String,
25    /// The usage rules of the API.
26    pub usage_rules_url: String,
27}
28
29impl Default for Attribution {
30    fn default() -> Self {
31        Self {
32            text: "Data: Transitous (https://transitous.org) and its sources, \
33                   map data © OpenStreetMap contributors. Transitous is run by \
34                   volunteers, without guarantee."
35                .to_owned(),
36            sources_url: "https://transitous.org/sources/".to_owned(),
37            usage_rules_url: "https://transitous.org/api/".to_owned(),
38        }
39    }
40}
41
42/// A stop, as found by name.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
44pub struct StopMatch {
45    /// The ID to pass instead of the name.
46    pub id: String,
47    pub name: String,
48    /// The town or district, to tell stops of the same name apart.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub area: Option<String>,
51    pub lat: f64,
52    pub lon: f64,
53    /// The modes that serve the stop, like `SUBWAY`.
54    pub modes: Vec<String>,
55}
56
57impl From<&motis::Match> for StopMatch {
58    fn from(found: &motis::Match) -> Self {
59        Self {
60            id: found.id.clone(),
61            name: found.name.clone(),
62            area: area(found),
63            lat: found.lat,
64            lon: found.lon,
65            modes: found.modes.iter().map(|m| m.as_str().to_owned()).collect(),
66        }
67    }
68}
69
70/// The area to show: the default one, else the most specific.
71pub(crate) fn area(found: &motis::Match) -> Option<String> {
72    found
73        .areas
74        .iter()
75        .find(|area| area.default == Some(true))
76        .or(found.areas.first())
77        .map(|area| area.name.clone())
78}
79
80/// The answer to a stop search.
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
82pub struct FindStopResult {
83    pub query: String,
84    pub stops: Vec<StopMatch>,
85    pub attribution: Attribution,
86    pub warnings: Vec<String>,
87}
88
89/// A stop of a connection or departure.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
91pub struct Location {
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub id: Option<String>,
94    pub name: String,
95}
96
97impl From<&motis::Place> for Location {
98    fn from(place: &motis::Place) -> Self {
99        Self {
100            id: place.stop_id.clone(),
101            name: place.name.clone(),
102        }
103    }
104}
105
106/// A time by the schedule and the expected or actual one.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
108pub struct Time {
109    pub scheduled: String,
110    /// The best known time: with realtime data the expected or actual one,
111    /// else the schedule.
112    pub actual: String,
113    /// `actual` minus `scheduled`. Absent without realtime data.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub delay_minutes: Option<i64>,
116}
117
118impl Time {
119    pub(crate) fn new(
120        scheduled: Timestamp,
121        actual: Timestamp,
122        realtime: bool,
123        tz: Option<&str>,
124    ) -> Self {
125        Self {
126            scheduled: format_time(scheduled, tz),
127            actual: format_time(actual, tz),
128            delay_minutes: realtime.then(|| delay_minutes(scheduled, actual)),
129        }
130    }
131}
132
133/// Where a leg starts or ends.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
135pub struct StopEvent {
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub id: Option<String>,
138    pub name: String,
139    #[serde(flatten)]
140    pub time: Time,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub track: Option<String>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub scheduled_track: Option<String>,
145    /// Whether boarding or alighting here is cancelled.
146    pub cancelled: bool,
147}
148
149/// One leg of a connection: a ride or a walk.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
151pub struct Leg {
152    /// Like `SUBWAY`, `BUS` or `WALK`.
153    pub mode: String,
154    /// The line, like `U5`.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub line: Option<String>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub operator: Option<String>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub headsign: Option<String>,
161    /// For `transitous journey`.
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub trip_id: Option<String>,
164    pub from: StopEvent,
165    pub to: StopEvent,
166    pub duration_minutes: i64,
167    /// Whether realtime data exists for this leg.
168    pub realtime: bool,
169    /// Whether the trip is cancelled.
170    pub cancelled: bool,
171    /// Whether passengers stay in the vehicle from the previous leg.
172    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
173    pub stay_seated: bool,
174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175    pub alerts: Vec<Alert>,
176}
177
178impl From<&motis::Leg> for Leg {
179    fn from(leg: &motis::Leg) -> Self {
180        let realtime = leg.real_time;
181        let event = |place: &motis::Place, scheduled, actual, side_cancelled| StopEvent {
182            id: place.stop_id.clone(),
183            name: place.name.clone(),
184            time: Time::new(scheduled, actual, realtime, place.tz.as_deref()),
185            track: place.track.clone(),
186            scheduled_track: place.scheduled_track.clone(),
187            cancelled: place.cancelled == Some(true) || side_cancelled,
188        };
189        let not_allowed = |kind: &Option<motis::PickupDropoffType>| {
190            *kind == Some(motis::PickupDropoffType::NotAllowed)
191        };
192        let transit = leg.mode.is_transit();
193        Self {
194            mode: leg.mode.as_str().to_owned(),
195            line: non_empty(leg.display_name.as_deref()),
196            operator: non_empty(leg.agency_name.as_deref()),
197            headsign: non_empty(leg.headsign.as_deref()),
198            trip_id: leg.trip_id.clone(),
199            from: event(
200                &leg.from,
201                leg.scheduled_start_time,
202                leg.start_time,
203                transit && not_allowed(&leg.from.pickup_type),
204            ),
205            to: event(
206                &leg.to,
207                leg.scheduled_end_time,
208                leg.end_time,
209                transit && not_allowed(&leg.to.dropoff_type),
210            ),
211            duration_minutes: minutes(leg.end_time.as_second() - leg.start_time.as_second()),
212            realtime,
213            cancelled: leg.cancelled == Some(true),
214            stay_seated: leg.interline_with_previous_leg == Some(true),
215            alerts: alerts([&leg.alerts, &leg.from.alerts, &leg.to.alerts]),
216        }
217    }
218}
219
220/// A connection with its status.
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
222pub struct Connection {
223    /// What the caller has to know first; see the reasons.
224    pub status: Status,
225    /// Why the status is not `ok`, most important first.
226    pub reasons: Vec<Reason>,
227    /// Whether the rides have realtime data: all, some or none.
228    pub realtime: Realtime,
229    pub departure: Time,
230    pub arrival: Time,
231    pub duration_minutes: i64,
232    pub transfers: i64,
233    /// The largest delay of a ride, at departure or arrival.
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub max_delay_minutes: Option<i64>,
236    pub legs: Vec<Leg>,
237}
238
239impl Connection {
240    pub(crate) fn new(itinerary: &motis::Itinerary, evaluation: Evaluation) -> Self {
241        let legs: Vec<Leg> = itinerary.legs.iter().map(Leg::from).collect();
242        let first = itinerary.legs.first();
243        let last = itinerary.legs.last();
244        // Walks have no realtime data of their own: their times follow the
245        // ride they lead to or come from.
246        let mut rides = itinerary.legs.iter().filter(|leg| leg.mode.is_transit());
247        let departs_realtime = rides.next().is_some_and(|leg| leg.real_time);
248        let arrives_realtime = itinerary
249            .legs
250            .iter()
251            .rev()
252            .find(|leg| leg.mode.is_transit())
253            .is_some_and(|leg| leg.real_time);
254        let departure = first.map_or_else(
255            || Time::new(itinerary.start_time, itinerary.start_time, false, None),
256            |leg| {
257                Time::new(
258                    leg.scheduled_start_time,
259                    leg.start_time,
260                    departs_realtime,
261                    leg.from.tz.as_deref(),
262                )
263            },
264        );
265        let arrival = last.map_or_else(
266            || Time::new(itinerary.end_time, itinerary.end_time, false, None),
267            |leg| {
268                Time::new(
269                    leg.scheduled_end_time,
270                    leg.end_time,
271                    arrives_realtime,
272                    leg.to.tz.as_deref(),
273                )
274            },
275        );
276        let start = first.map_or(itinerary.start_time, |leg| leg.start_time);
277        let end = last.map_or(itinerary.end_time, |leg| leg.end_time);
278        Self {
279            status: evaluation.status,
280            reasons: evaluation.reasons,
281            realtime: evaluation.realtime,
282            departure,
283            arrival,
284            duration_minutes: minutes(end.as_second() - start.as_second()),
285            transfers: itinerary.transfers,
286            max_delay_minutes: evaluation.max_delay_minutes,
287            legs,
288        }
289    }
290}
291
292/// Cursors for the next page, to pass as `page_cursor`.
293#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
294pub struct PageCursor {
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub earlier: Option<String>,
297    #[serde(skip_serializing_if = "Option::is_none")]
298    pub later: Option<String>,
299}
300
301impl PageCursor {
302    pub(crate) fn new(earlier: &str, later: &str) -> Self {
303        Self {
304            earlier: non_empty(Some(earlier)),
305            later: non_empty(Some(later)),
306        }
307    }
308}
309
310/// The answer to a connection search.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
312pub struct TripResult {
313    pub from: Location,
314    pub to: Location,
315    /// Sorted by departure.
316    pub connections: Vec<Connection>,
317    pub page_cursor: PageCursor,
318    pub attribution: Attribution,
319    pub warnings: Vec<String>,
320}
321
322/// A departure or arrival at a stop.
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
324pub struct Departure {
325    pub mode: String,
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub line: Option<String>,
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub operator: Option<String>,
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub headsign: Option<String>,
332    /// For `transitous journey`.
333    pub trip_id: String,
334    /// The stop or platform, with the time of the departure or arrival.
335    pub stop: StopEvent,
336    pub realtime: bool,
337    /// Whether this departure or arrival is cancelled.
338    pub cancelled: bool,
339    /// Whether the whole trip is cancelled.
340    pub trip_cancelled: bool,
341    #[serde(default, skip_serializing_if = "Vec::is_empty")]
342    pub alerts: Vec<Alert>,
343}
344
345impl Departure {
346    pub(crate) fn new(stop_time: &motis::StopTime, arrivals: bool) -> Self {
347        let place = &stop_time.place;
348        let (scheduled, actual) = if arrivals {
349            (place.scheduled_arrival, place.arrival)
350        } else {
351            (place.scheduled_departure, place.departure)
352        };
353        let scheduled = scheduled.or(actual).unwrap_or_default();
354        let actual = actual.unwrap_or(scheduled);
355        Self {
356            mode: stop_time.mode.as_str().to_owned(),
357            line: non_empty(Some(&stop_time.display_name)),
358            operator: non_empty(Some(&stop_time.agency_name)),
359            headsign: non_empty(Some(&stop_time.headsign)),
360            trip_id: stop_time.trip_id.clone(),
361            stop: StopEvent {
362                id: place.stop_id.clone(),
363                name: place.name.clone(),
364                time: Time::new(scheduled, actual, stop_time.real_time, place.tz.as_deref()),
365                track: place.track.clone(),
366                scheduled_track: place.scheduled_track.clone(),
367                cancelled: stop_time.cancelled,
368            },
369            realtime: stop_time.real_time,
370            cancelled: stop_time.cancelled || stop_time.trip_cancelled,
371            trip_cancelled: stop_time.trip_cancelled,
372            alerts: alerts([&place.alerts]),
373        }
374    }
375}
376
377/// The departures or arrivals at a stop.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
379pub struct DeparturesResult {
380    pub stop: Location,
381    /// Whether these are arrivals instead of departures.
382    pub arrivals: bool,
383    pub departures: Vec<Departure>,
384    pub page_cursor: PageCursor,
385    pub attribution: Attribution,
386    pub warnings: Vec<String>,
387}
388
389/// A stop of a trip.
390#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
391pub struct JourneyStop {
392    #[serde(skip_serializing_if = "Option::is_none")]
393    pub id: Option<String>,
394    pub name: String,
395    /// Absent at the first stop.
396    #[serde(skip_serializing_if = "Option::is_none")]
397    pub arrival: Option<Time>,
398    /// Absent at the last stop.
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub departure: Option<Time>,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub track: Option<String>,
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub scheduled_track: Option<String>,
405    /// Whether the trip skips this stop.
406    pub cancelled: bool,
407}
408
409impl JourneyStop {
410    fn new(place: &motis::Place, realtime: bool) -> Self {
411        let time = |scheduled: Option<Timestamp>, actual: Option<Timestamp>| {
412            let scheduled = scheduled.or(actual)?;
413            Some(Time::new(
414                scheduled,
415                actual.unwrap_or(scheduled),
416                realtime,
417                place.tz.as_deref(),
418            ))
419        };
420        Self {
421            id: place.stop_id.clone(),
422            name: place.name.clone(),
423            arrival: time(place.scheduled_arrival, place.arrival),
424            departure: time(place.scheduled_departure, place.departure),
425            track: place.track.clone(),
426            scheduled_track: place.scheduled_track.clone(),
427            cancelled: place.cancelled == Some(true)
428                || (place.pickup_type == Some(motis::PickupDropoffType::NotAllowed)
429                    && place.dropoff_type == Some(motis::PickupDropoffType::NotAllowed)),
430        }
431    }
432}
433
434/// One trip with all its stops.
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
436pub struct JourneyResult {
437    pub trip_id: String,
438    pub mode: String,
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub line: Option<String>,
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub operator: Option<String>,
443    #[serde(skip_serializing_if = "Option::is_none")]
444    pub headsign: Option<String>,
445    pub realtime: bool,
446    /// Whether the trip is cancelled.
447    pub cancelled: bool,
448    pub stops: Vec<JourneyStop>,
449    #[serde(default, skip_serializing_if = "Vec::is_empty")]
450    pub alerts: Vec<Alert>,
451    pub attribution: Attribution,
452    pub warnings: Vec<String>,
453}
454
455impl JourneyResult {
456    pub(crate) fn new(trip_id: &str, itinerary: &motis::Itinerary, warnings: Vec<String>) -> Self {
457        let rides: Vec<&motis::Leg> = itinerary
458            .legs
459            .iter()
460            .filter(|leg| leg.mode.is_transit())
461            .collect();
462        let first = rides.first().copied();
463        let realtime = rides.iter().any(|leg| leg.real_time);
464        let mut stops: Vec<JourneyStop> = first
465            .map(|leg| JourneyStop::new(&leg.from, leg.real_time))
466            .into_iter()
467            .collect();
468        for leg in &rides {
469            stops.extend(
470                leg.intermediate_stops
471                    .iter()
472                    .chain([&leg.to])
473                    .map(|place| JourneyStop::new(place, leg.real_time)),
474            );
475        }
476        // The first stop has no arrival and the last no departure.
477        if let Some(stop) = stops.first_mut() {
478            stop.arrival = None;
479        }
480        if let Some(stop) = stops.last_mut() {
481            stop.departure = None;
482        }
483        Self {
484            trip_id: trip_id.to_owned(),
485            mode: first.map_or_else(String::new, |leg| leg.mode.as_str().to_owned()),
486            line: first.and_then(|leg| non_empty(leg.display_name.as_deref())),
487            operator: first.and_then(|leg| non_empty(leg.agency_name.as_deref())),
488            headsign: first.and_then(|leg| non_empty(leg.headsign.as_deref())),
489            realtime,
490            cancelled: rides.iter().any(|leg| leg.cancelled == Some(true)),
491            stops,
492            alerts: alerts(rides.iter().map(|leg| &leg.alerts)),
493            attribution: Attribution::default(),
494            warnings,
495        }
496    }
497}
498
499/// A service alert.
500#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
501pub struct Alert {
502    pub header: String,
503    #[serde(skip_serializing_if = "String::is_empty")]
504    pub description: String,
505    /// Like `NO_SERVICE` or `DETOUR`.
506    #[serde(skip_serializing_if = "Option::is_none")]
507    pub effect: Option<String>,
508    /// `INFO`, `WARNING` or `SEVERE`.
509    #[serde(skip_serializing_if = "Option::is_none")]
510    pub severity: Option<String>,
511    #[serde(skip_serializing_if = "Option::is_none")]
512    pub url: Option<String>,
513    /// When the alert applies.
514    #[serde(default, skip_serializing_if = "Vec::is_empty")]
515    pub periods: Vec<Period>,
516}
517
518/// A period of an alert. An absent end means until further notice.
519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
520pub struct Period {
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub start: Option<String>,
523    #[serde(skip_serializing_if = "Option::is_none")]
524    pub end: Option<String>,
525}
526
527impl From<&motis::Alert> for Alert {
528    fn from(alert: &motis::Alert) -> Self {
529        Self {
530            header: truncate(&alert.header_text),
531            description: truncate(&alert.description_text),
532            effect: alert.effect.as_ref().map(|e| e.as_str().to_owned()),
533            severity: alert.severity_level.as_ref().map(|s| s.as_str().to_owned()),
534            url: alert.url.clone(),
535            periods: alert
536                .impact_period
537                .iter()
538                .map(|period| Period {
539                    start: period.start.map(|t| format_time(t, None)),
540                    end: period.end.map(|t| format_time(t, None)),
541                })
542                .collect(),
543        }
544    }
545}
546
547/// The alerts of several lists, each once.
548fn alerts<'a>(lists: impl IntoIterator<Item = &'a Vec<motis::Alert>>) -> Vec<Alert> {
549    let mut out: Vec<Alert> = Vec::new();
550    for alert in lists.into_iter().flatten().map(Alert::from) {
551        if !out.contains(&alert) {
552            out.push(alert);
553        }
554    }
555    out
556}
557
558/// The usage of the API in the last 24 hours, by this machine.
559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
560pub struct UsageSummary {
561    /// Requests per endpoint in the last 24 hours.
562    pub last_24h: Vec<EndpointUsage>,
563    /// Requests in the last minute, all endpoints.
564    pub last_minute: u32,
565    pub per_minute_limit: u32,
566    pub plan_daily_limit: u32,
567    pub plan_remaining: u32,
568    /// The counter file.
569    pub path: String,
570}
571
572#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
573pub struct EndpointUsage {
574    pub endpoint: String,
575    pub requests: u32,
576}
577
578/// An error as output.
579#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
580pub struct ErrorBody {
581    pub error: String,
582    /// Like `ambiguous_stop` or `rate_limited`.
583    pub status: String,
584    #[serde(skip_serializing_if = "Option::is_none")]
585    pub retry_after_seconds: Option<u64>,
586    /// For `ambiguous_stop`: the stops to choose from.
587    #[serde(default, skip_serializing_if = "Vec::is_empty")]
588    pub candidates: Vec<StopMatch>,
589}
590
591/// RFC 3339 in the time zone `tz`, else UTC.
592pub(crate) fn format_time(time: Timestamp, tz: Option<&str>) -> String {
593    let zone = tz
594        .and_then(|name| TimeZone::get(name).ok())
595        .unwrap_or(TimeZone::UTC);
596    time.to_zoned_datetime(zone)
597        .strftime("%Y-%m-%dT%H:%M:%S%:z")
598        .to_string()
599}
600
601/// Seconds as whole minutes, rounded half away from zero.
602pub(crate) fn minutes(seconds: i64) -> i64 {
603    let sign = seconds.signum();
604    sign * ((seconds.abs() + 30) / 60)
605}
606
607pub(crate) fn delay_minutes(scheduled: Timestamp, actual: Timestamp) -> i64 {
608    minutes(actual.as_second() - scheduled.as_second())
609}
610
611fn non_empty(text: Option<&str>) -> Option<String> {
612    text.filter(|text| !text.is_empty()).map(str::to_owned)
613}
614
615/// At most [`MAX_ALERT_TEXT`] bytes, cut at a character boundary.
616fn truncate(text: &str) -> String {
617    if text.len() <= MAX_ALERT_TEXT {
618        return text.to_owned();
619    }
620    let mut end = MAX_ALERT_TEXT - '…'.len_utf8();
621    while !text.is_char_boundary(end) {
622        end -= 1;
623    }
624    format!("{}…", &text[..end])
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630
631    #[test]
632    fn formats_times_in_the_zone_of_the_stop() {
633        let time: Timestamp = "2026-11-26T20:22:00Z".parse().unwrap();
634        assert_eq!(
635            format_time(time, Some("Europe/Berlin")),
636            "2026-11-26T21:22:00+01:00"
637        );
638        assert_eq!(format_time(time, None), "2026-11-26T20:22:00+00:00");
639        assert_eq!(
640            format_time(time, Some("Nowhere/Else")),
641            "2026-11-26T20:22:00+00:00"
642        );
643    }
644
645    #[test]
646    fn a_stop_without_pickup_and_dropoff_is_skipped() {
647        use motis::PickupDropoffType::{Normal, NotAllowed};
648        let stop = |pickup, dropoff| motis::Place {
649            pickup_type: Some(pickup),
650            dropoff_type: Some(dropoff),
651            ..motis::Place::default()
652        };
653        assert!(JourneyStop::new(&stop(NotAllowed, NotAllowed), true).cancelled);
654        assert!(!JourneyStop::new(&stop(NotAllowed, Normal), true).cancelled);
655        assert!(!JourneyStop::new(&stop(Normal, NotAllowed), true).cancelled);
656    }
657
658    #[test]
659    fn rounds_to_whole_minutes() {
660        assert_eq!(minutes(0), 0);
661        assert_eq!(minutes(29), 0);
662        assert_eq!(minutes(30), 1);
663        assert_eq!(minutes(-90), -2);
664        assert_eq!(minutes(-89), -1);
665        assert_eq!(minutes(600), 10);
666    }
667
668    #[test]
669    fn cuts_long_texts() {
670        assert_eq!(truncate("short"), "short");
671        let long = "ä".repeat(MAX_ALERT_TEXT);
672        let cut = truncate(&long);
673        assert!(cut.len() <= MAX_ALERT_TEXT, "{}", cut.len());
674        assert!(cut.ends_with('…'));
675    }
676
677    #[test]
678    fn lists_each_alert_once() {
679        let alert = motis::Alert {
680            header_text: "Works".into(),
681            effect: Some(motis::AlertEffect::Detour),
682            severity_level: Some(motis::AlertSeverityLevel::Warning),
683            impact_period: vec![motis::TimeRange {
684                start: Some("2026-11-26T20:00:00Z".parse().unwrap()),
685                end: None,
686            }],
687            ..motis::Alert::default()
688        };
689        let same = vec![alert.clone()];
690        let out = alerts([&same, &same]);
691        assert_eq!(out.len(), 1);
692        assert_eq!(out[0].effect.as_deref(), Some("DETOUR"));
693        assert_eq!(out[0].severity.as_deref(), Some("WARNING"));
694        assert_eq!(
695            out[0].periods[0].start.as_deref(),
696            Some("2026-11-26T20:00:00+00:00")
697        );
698        assert_eq!(out[0].periods[0].end, None);
699    }
700
701    #[test]
702    fn shows_the_default_area() {
703        let area_named = |name: &str, default| motis::Area {
704            name: name.into(),
705            default,
706            ..motis::Area::default()
707        };
708        let mut found = motis::Match {
709            areas: vec![
710                area_named("Innenstadt", None),
711                area_named("Frankfurt", Some(true)),
712            ],
713            ..motis::Match::default()
714        };
715        assert_eq!(area(&found).as_deref(), Some("Frankfurt"));
716        found.areas[1].default = None;
717        assert_eq!(area(&found).as_deref(), Some("Innenstadt"));
718        found.areas.clear();
719        assert_eq!(area(&found), None);
720    }
721
722    #[test]
723    fn a_journey_without_rides_is_empty() {
724        let result = JourneyResult::new("t", &motis::Itinerary::default(), Vec::new());
725        assert_eq!(result.stops, Vec::<JourneyStop>::new());
726        assert_eq!(result.mode, "");
727        assert!(!result.realtime);
728    }
729
730    #[test]
731    fn each_end_has_the_realtime_of_its_ride() {
732        let time: Timestamp = "2026-11-26T20:00:00Z".parse().unwrap();
733        let ride = |real_time| motis::Leg {
734            mode: motis::Mode::Bus,
735            scheduled_start_time: time,
736            start_time: time,
737            scheduled_end_time: time,
738            end_time: time,
739            real_time,
740            ..motis::Leg::default()
741        };
742        let walk = motis::Leg {
743            mode: motis::Mode::Walk,
744            ..ride(false)
745        };
746        let delays = |legs: Vec<motis::Leg>| {
747            let itinerary = motis::Itinerary {
748                legs,
749                ..motis::Itinerary::default()
750            };
751            let evaluation = crate::status::evaluate(&itinerary, time, 2);
752            let connection = Connection::new(&itinerary, evaluation);
753            (
754                connection.departure.delay_minutes,
755                connection.arrival.delay_minutes,
756            )
757        };
758        assert_eq!(
759            delays(vec![walk.clone(), ride(true), ride(false), walk.clone()]),
760            (Some(0), None)
761        );
762        assert_eq!(delays(vec![ride(false), ride(true)]), (None, Some(0)));
763        assert_eq!(delays(vec![walk]), (None, None));
764    }
765
766    #[test]
767    fn a_connection_without_legs_takes_the_itinerary_times() {
768        let itinerary = motis::Itinerary {
769            start_time: "2026-11-26T20:00:00Z".parse().unwrap(),
770            end_time: "2026-11-26T20:30:00Z".parse().unwrap(),
771            ..motis::Itinerary::default()
772        };
773        let connection = Connection::new(
774            &itinerary,
775            crate::status::evaluate(&itinerary, itinerary.start_time, 2),
776        );
777        assert_eq!(connection.duration_minutes, 30);
778        assert_eq!(connection.departure.scheduled, "2026-11-26T20:00:00+00:00");
779        assert_eq!(connection.arrival.delay_minutes, None);
780    }
781}