Skip to main content

telco_interop/
wechsel.rs

1//! One provider switch across WBCI and S/PRI.
2//!
3//! The gaining provider agrees the switch with the losing provider over WBCI (VA, RUEM-VA,
4//! AKM-TR), then orders the line from the network owner over S/PRI with the WBCI
5//! Vorabstimmungs-ID, which „wird im gesamten Prozessablauf als eindeutiges
6//! Identifikationsmerkmal verwendet" (S/PRI 4.4 §5.5.1.1; the sequence of p. 27). A [`Wechsel`]
7//! holds the one [`wbci::Process`] and every [`spri::process::Process`] carrying its id, and recomputes
8//! from them, on every call:
9//!
10//! - [`Wechsel::timeline`]: every event of both interfaces in time order ([`Eintrag`]);
11//! - [`Wechsel::befunde`]: where the two interfaces disagree ([`Befund`], rules below);
12//! - [`Wechsel::deadlines`]: the deadlines of both interfaces, sorted ([`Frist`]);
13//! - [`Wechsel::next_actions`]: what a party may do next on either interface ([`Aktion`]).
14//!
15//! The switch has no state of its own: the processes stay the single source of truth, and
16//! the caller keeps feeding them through [`Wechsel::wbci_mut`] and [`Wechsel::spri_mut`].
17//!
18//! ## Parties
19//!
20//! [`Partei`] unifies the roles: `EkpAuf` is the WBCI EKPauf and the S/PRI Auftraggeber,
21//! `EkpAbg` the WBCI EKPabg and the S/PRI abgebender Provider, `Netzbetreiber` the S/PRI
22//! Leistungserbringer. In a `KUE-AG` with the Vorabstimmungs-ID the Auftraggeber is the losing
23//! provider cancelling its line for the switch (S/PRI 4.4 p. 26, „KUE/VA-ID"), so there the
24//! Auftraggeber is `EkpAbg` (an interpretation of the figure on p. 27).
25//!
26//! ## Rules
27//!
28//! | Rule | Finding | Source | Party |
29//! |---|---|---|---|
30//! | `wechsel.nicht-abgestimmt` | an S/PRI order was placed while the WBCI pre-agreement was not agreed (requested, rejected, or not yet answered with a RUEM-VA) | S/PRI 4.4 §5.5.1.1 | the order's Auftraggeber |
31//! | `wechsel.leitung` | the PV's `lineId` is not among the lines (LineID) the AKM-TR takes over (when it names any) | Anl. 1 V5.4.1 §2.2; S/PRI 4.4 §5.5.1.1 | EKPauf |
32//! | `wechsel.termin` | the order's requested date (before any Terminverschiebung) or the binding date of its ABM differs from the WBCI switch date | Anl. 1 V5.4.1 §2.5; S/PRI 4.4 §5.5.1.1, §5.5.1.3 | the Auftraggeber, or the network owner for the ABM |
33//! | `wechsel.tv-zuerst-wbci` | an S/PRI Terminverschiebung names a date other than the WBCI switch date in force when it was sent: the WBCI postponement (TVS-VA, ERLM `8003`) comes first | Anl. 1 V5.4.1 §2.11 | EKPauf |
34//! | `wechsel.storno` | the WBCI pre-agreement was agreed and is now cancelled or changed, but an S/PRI order is still open and not being cancelled | Anl. 1 V5.4.1 §2.9, §2.10; S/PRI 4.4 §5.5.1.2 | the order's Auftraggeber |
35//! | `wechsel.kontinuitaet` | a PV or NEU is completed (ERLM, ERLM-PV) more than one working day of [`Calendar::wbci`] after the WBCI switch date | § 59 Abs. 1 TKG (interpretation) | network owner |
36//!
37//! The continuity rule is an **interpretation**: § 59 Abs. 1 TKG requires that the service is
38//! „nicht länger als einen Arbeitstag unterbrochen"; the real outage is not visible on the
39//! interfaces, so the S/PRI completion date stands in for the end of the outage.
40//!
41//! Findings, timeline entries and their `Display` and `Debug` carry ids, dates, message types
42//! and codes only — never a name, address or phone number.
43//!
44//! ```
45//! use telco_interop::{Partei, Wechsel, wbci};
46//! use wbci::{Anfrage, Direction, Meldung, Payload, Process, Role, RuemVa, Timestamp};
47//!
48//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
49//! # let xml = include_str!("../../wbci/tests/fixtures/va-kue-mrn.xml");
50//! let Payload::AnfrageRequest { anfrage: Anfrage::Vorabstimmung(va), .. } = Payload::from_xml(xml.as_bytes())? else {
51//!     return Err("not a pre-agreement".into());
52//! };
53//! let sent: Timestamp = "2026-11-23T08:00:00Z".parse()?;
54//! let mut wechsel = Wechsel::new(Process::new(Role::EkpAuf, va.clone(), Direction::Sent, sent)?);
55//!
56//! // The losing provider agrees …
57//! let ruem = RuemVa::zustimmung(&va, va.kundenwunschtermin);
58//! wechsel.wbci_mut().apply(Direction::Received, "2026-11-24T09:00:00Z".parse()?, Meldung::from(ruem))?;
59//!
60//! let lines: Vec<String> = wechsel.timeline().iter().map(ToString::to_string).collect();
61//! assert_eq!(lines, ["Mo 23.11.2026 09:00 WBCI EKPauf → VA-KUE-MRN", "Di 24.11.2026 10:00 WBCI EKPabg → RUEM-VA 8001"]);
62//! // … and nothing disagrees yet: no S/PRI order has been placed.
63//! assert!(wechsel.befunde().is_empty());
64//! assert!(wechsel.next_actions(Partei::EkpAuf).iter().any(|a| matches!(a, telco_interop::Aktion::Wbci(_))));
65//! # Ok(())
66//! # }
67//! ```
68
69use core::fmt;
70
71use carrier_core::calendar::berlin;
72use carrier_core::count::{Berlin, Day};
73
74use crate::{Calendar, LineId, VorabstimmungsId};
75
76use spri::process::{Message as SMessage, Pending, Role as SRole, State as SState};
77use spri::{Aenderungskennzeichen, ExterneAuftragsnummer, Geschaeftsfall as SFall, GeschaeftsfallCode, Meldungsinhalt};
78use wbci::process::{Message as WMessage, State as WState, Takeover};
79use wbci::{Anfrage, Date, Geschaeftsfall as WFall, Meldung as WMeldung, Role as WRole, Timestamp, UebernahmeLeitung};
80
81/// The interface an event or deadline belongs to.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub enum Schnittstelle {
84    /// WBCI: provider ↔ provider.
85    Wbci,
86    /// S/PRI: service provider ↔ network owner (and the losing provider in a PV).
87    Spri,
88}
89
90impl fmt::Display for Schnittstelle {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.write_str(match self {
93            Self::Wbci => "WBCI",
94            Self::Spri => "S/PRI",
95        })
96    }
97}
98
99/// A party of the switch, across both interfaces.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub enum Partei {
102    /// The gaining provider: WBCI EKPauf, S/PRI Auftraggeber.
103    EkpAuf,
104    /// The losing provider: WBCI EKPabg, S/PRI abgebender Provider (and the Auftraggeber of a
105    /// `KUE-AG` for the switch).
106    EkpAbg,
107    /// The network owner: S/PRI Leistungserbringer.
108    Netzbetreiber,
109}
110
111impl fmt::Display for Partei {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.write_str(match self {
114            Self::EkpAuf => "EKPauf",
115            Self::EkpAbg => "EKPabg",
116            Self::Netzbetreiber => "Netzbetreiber",
117        })
118    }
119}
120
121impl From<WRole> for Partei {
122    fn from(r: WRole) -> Self {
123        match r {
124            WRole::EkpAuf => Self::EkpAuf,
125            WRole::EkpAbg => Self::EkpAbg,
126        }
127    }
128}
129
130/// The party an S/PRI role plays in the switch, for an order of business case `fall`.
131const fn partei_spri(role: SRole, fall: GeschaeftsfallCode) -> Partei {
132    match role {
133        SRole::Auftraggeber if matches!(fall, GeschaeftsfallCode::KueAg) => Partei::EkpAbg,
134        SRole::Auftraggeber => Partei::EkpAuf,
135        SRole::Leistungserbringer => Partei::Netzbetreiber,
136        SRole::AbgebenderProvider => Partei::EkpAbg,
137    }
138}
139
140/// Whether an event was sent or received by the owner of the process it was recorded in.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
142pub enum Richtung {
143    /// Sent by the owner.
144    Gesendet,
145    /// Received by the owner.
146    Empfangen,
147}
148
149/// One event of the switch.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct Eintrag {
152    /// When it was sent or received.
153    pub at: Timestamp,
154    /// The interface.
155    pub schnittstelle: Schnittstelle,
156    /// The party that sent it.
157    pub partei: Partei,
158    /// Sent or received, as the process it comes from recorded it.
159    pub richtung: Richtung,
160    /// The request, order or message type, e.g. `VA-KUE-MRN`, `RUEM-VA`, `PV`, `ABM-PV`,
161    /// `Storno`, `Terminverschiebung`, `TEQ`.
162    pub nachricht: &'static str,
163    /// The codes of its positions, e.g. `8001`.
164    pub codes: Vec<String>,
165}
166
167impl fmt::Display for Eintrag {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        let z = self.at.to_zoned_datetime(berlin());
170        write!(
171            f,
172            "{} {:02}:{:02} {} {} → {}",
173            Day(z.date()),
174            z.hour(),
175            z.minute(),
176            self.schnittstelle,
177            self.partei,
178            self.nachricht
179        )?;
180        for c in &self.codes {
181            write!(f, " {c}")?;
182        }
183        Ok(())
184    }
185}
186
187/// Where the two interfaces disagree.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Befund {
190    /// The rule, e.g. `wechsel.termin`.
191    pub regel: &'static str,
192    /// Where the rule is written.
193    pub quelle: &'static str,
194    /// Who has to act.
195    pub partei: Partei,
196    /// What disagrees: ids, dates and codes only.
197    pub text: String,
198}
199
200impl fmt::Display for Befund {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        write!(f, "{} ({}) — {}: {}", self.regel, self.quelle, self.partei, self.text)
203    }
204}
205
206/// The cross-interface rules.
207pub mod regeln {
208    /// An S/PRI order placed while the WBCI pre-agreement was not agreed.
209    pub const NICHT_ABGESTIMMT: (&str, &str) = ("wechsel.nicht-abgestimmt", "S/PRI 4.4 §5.5.1.1");
210    /// A PV for a line the AKM-TR does not take over.
211    pub const LEITUNG: (&str, &str) = ("wechsel.leitung", "Anl. 1 V5.4.1 §2.2; S/PRI 4.4 §5.5.1.1");
212    /// An S/PRI date other than the WBCI switch date.
213    pub const TERMIN: (&str, &str) = ("wechsel.termin", "Anl. 1 V5.4.1 §2.5; S/PRI 4.4 §5.5.1.1, §5.5.1.3");
214    /// An S/PRI Terminverschiebung before the WBCI postponement.
215    pub const TV_ZUERST_WBCI: (&str, &str) = ("wechsel.tv-zuerst-wbci", "Anl. 1 V5.4.1 §2.11");
216    /// A WBCI cancellation or change while an S/PRI order is open.
217    pub const STORNO: (&str, &str) = ("wechsel.storno", "Anl. 1 V5.4.1 §2.9, §2.10; S/PRI 4.4 §5.5.1.2");
218    /// A completion more than one working day after the switch date (interpretation).
219    pub const KONTINUITAET: (&str, &str) = ("wechsel.kontinuitaet", "§ 59 Abs. 1 TKG (interpretation)");
220}
221
222/// Why an S/PRI process was not attached.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub struct Mismatch {
225    /// The Vorabstimmungs-ID of the switch.
226    pub erwartet: VorabstimmungsId,
227    /// The Vorabstimmungs-ID of the order, if it carries one.
228    pub gefunden: Option<VorabstimmungsId>,
229    /// The refused process, handed back so nothing is lost.
230    pub prozess: Box<spri::process::Process>,
231}
232
233impl fmt::Display for Mismatch {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        match &self.gefunden {
236            Some(id) => write!(f, "the S/PRI order carries Vorabstimmungs-ID {id}, the switch is {}", self.erwartet),
237            None => write!(f, "the S/PRI order carries no Vorabstimmungs-ID, the switch is {}", self.erwartet),
238        }?;
239        f.write_str(" (S/PRI 4.4 §5.5.1.1)")
240    }
241}
242
243impl std::error::Error for Mismatch {}
244
245/// A deadline of either interface.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum FristDetail {
248    /// A WBCI deadline.
249    Wbci(wbci::deadline::Deadline),
250    /// An S/PRI deadline.
251    Spri(spri::deadline::Deadline),
252}
253
254/// A deadline of the switch, tagged with its interface and party.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct Frist {
257    /// The interface.
258    pub schnittstelle: Schnittstelle,
259    /// Who must act, or whose window it is.
260    pub partei: Partei,
261    /// The S/PRI order it belongs to.
262    pub auftrag: Option<ExterneAuftragsnummer>,
263    /// The act must happen before this instant.
264    pub due: Timestamp,
265    /// The deadline with its rule and arithmetic.
266    pub detail: FristDetail,
267}
268
269impl Frist {
270    /// The rule's id, source and text.
271    #[must_use]
272    pub const fn rule(&self) -> (&'static str, &'static str, &'static str) {
273        match &self.detail {
274            FristDetail::Wbci(d) => (d.rule.id, d.rule.source, d.rule.text),
275            FristDetail::Spri(d) => (d.rule.id, d.rule.source, d.rule.text),
276        }
277    }
278}
279
280impl fmt::Display for Frist {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        let (_, source, text) = self.rule();
283        write!(f, "{} {}: by {} — {text} ({source})", self.schnittstelle, self.partei, Berlin(self.due))
284    }
285}
286
287/// Something a party may do next.
288#[derive(Debug, Clone, PartialEq, Eq)]
289#[non_exhaustive]
290pub enum Aktion {
291    /// A WBCI action.
292    Wbci(wbci::process::Action),
293    /// An S/PRI action on an order.
294    Spri {
295        /// The order.
296        auftrag: ExterneAuftragsnummer,
297        /// The action.
298        action: spri::process::Action,
299    },
300    /// Place the S/PRI order with the Vorabstimmungs-ID: the switch is agreed and the line
301    /// takeover announced, but no S/PRI order is attached (S/PRI 4.4 §5.5.1.1, p. 27).
302    SpriAuftragStellen,
303}
304
305/// One provider switch: a WBCI pre-agreement and the S/PRI orders carrying its id.
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct Wechsel {
308    wbci: wbci::Process,
309    spri: Vec<spri::process::Process>,
310}
311
312impl Wechsel {
313    /// A switch of the pre-agreement `wbci`, with no S/PRI order yet.
314    #[must_use]
315    pub const fn new(wbci: wbci::Process) -> Self {
316        Self { wbci, spri: Vec::new() }
317    }
318
319    /// Attaches an S/PRI process whose order carries this switch's Vorabstimmungs-ID.
320    ///
321    /// # Errors
322    ///
323    /// [`Mismatch`] when the order carries another or no Vorabstimmungs-ID (S/PRI 4.4
324    /// §5.5.1.1); the switch is unchanged.
325    pub fn attach(&mut self, process: spri::process::Process) -> Result<(), Mismatch> {
326        let erwartet = self.vorabstimmungs_id();
327        match process.vorabstimmungs_id() {
328            Some(id) if id == erwartet => {
329                self.spri.push(process);
330                Ok(())
331            }
332            gefunden => {
333                let gefunden = gefunden.cloned();
334                Err(Mismatch { erwartet: erwartet.clone(), gefunden, prozess: Box::new(process) })
335            }
336        }
337    }
338
339    /// The Vorabstimmungs-ID of the switch.
340    #[must_use]
341    pub const fn vorabstimmungs_id(&self) -> &VorabstimmungsId {
342        &self.wbci.vorabstimmung().id
343    }
344
345    /// The WBCI process.
346    #[must_use]
347    pub const fn wbci(&self) -> &wbci::Process {
348        &self.wbci
349    }
350
351    /// The WBCI process, to apply further events.
352    pub const fn wbci_mut(&mut self) -> &mut wbci::Process {
353        &mut self.wbci
354    }
355
356    /// The attached S/PRI processes, in the order they were attached.
357    #[must_use]
358    pub fn spri(&self) -> &[spri::process::Process] {
359        &self.spri
360    }
361
362    /// The attached S/PRI processes, to apply further events.
363    pub fn spri_mut(&mut self) -> &mut [spri::process::Process] {
364        &mut self.spri
365    }
366
367    /// The agreed switch date: the RUEM-VA's, moved by every accepted postponement; after a
368    /// cancellation, the last date that was agreed.
369    #[must_use]
370    pub fn wechseltermin(&self) -> Option<Date> {
371        match self.wbci.state() {
372            WState::Agreed { wechseltermin } => Some(*wechseltermin),
373            WState::Changed { wechseltermin } => *wechseltermin,
374            WState::Cancelled => self.agreed_dates().last().map(|(_, d)| *d),
375            WState::Requested | WState::Rejected { .. } => None,
376        }
377    }
378
379    /// Every event of both interfaces, in time order (stable: WBCI first, then the S/PRI
380    /// processes in the order attached). An event recorded by two attached views of the same
381    /// order (e.g. the Auftraggeber's and the network owner's) appears once.
382    #[must_use]
383    pub fn timeline(&self) -> Vec<Eintrag> {
384        let mut out: Vec<Eintrag> = self
385            .wbci
386            .history()
387            .iter()
388            .map(|e| Eintrag {
389                at: e.at,
390                schnittstelle: Schnittstelle::Wbci,
391                partei: e.sender.into(),
392                richtung: match e.direction {
393                    wbci::Direction::Sent => Richtung::Gesendet,
394                    wbci::Direction::Received => Richtung::Empfangen,
395                },
396                nachricht: wbci_label(&e.message),
397                codes: wbci_codes(&e.message),
398            })
399            .collect();
400        let mut seen: Vec<&spri::process::Event> = Vec::new();
401        for p in &self.spri {
402            let fall = p.geschaeftsfall();
403            for e in p.history() {
404                if seen.iter().any(|s| s.at == e.at && s.sender == e.sender && s.message == e.message) {
405                    continue;
406                }
407                seen.push(e);
408                out.push(Eintrag {
409                    at: e.at,
410                    schnittstelle: Schnittstelle::Spri,
411                    partei: partei_spri(e.sender, fall),
412                    richtung: match e.direction {
413                        spri::process::Direction::Sent => Richtung::Gesendet,
414                        spri::process::Direction::Received => Richtung::Empfangen,
415                    },
416                    nachricht: spri_label(&e.message),
417                    codes: spri_codes(&e.message),
418                });
419            }
420        }
421        out.sort_by_key(|e| e.at);
422        out
423    }
424
425    /// Where the two interfaces disagree, by the rules of the [module](self) in table order;
426    /// the same finding from two views of one order appears once.
427    #[must_use]
428    pub fn befunde(&self) -> Vec<Befund> {
429        let mut out = Vec::new();
430        for p in &self.spri {
431            self.nicht_abgestimmt(p, &mut out);
432        }
433        for p in &self.spri {
434            self.leitung(p, &mut out);
435        }
436        for p in &self.spri {
437            self.termin(p, &mut out);
438        }
439        for p in &self.spri {
440            self.tv_zuerst_wbci(p, &mut out);
441        }
442        for p in &self.spri {
443            self.storno(p, &mut out);
444        }
445        for p in &self.spri {
446            self.kontinuitaet(p, &mut out);
447        }
448        let mut unique: Vec<Befund> = Vec::with_capacity(out.len());
449        for b in out {
450            if !unique.contains(&b) {
451                unique.push(b);
452            }
453        }
454        unique
455    }
456
457    /// The deadlines of both interfaces, sorted by due time; the same deadline from two views
458    /// of one order appears once.
459    #[must_use]
460    pub fn deadlines(&self) -> Vec<Frist> {
461        let mut out: Vec<Frist> = self
462            .wbci
463            .deadlines()
464            .into_iter()
465            .map(|d| Frist {
466                schnittstelle: Schnittstelle::Wbci,
467                partei: d.party.into(),
468                auftrag: None,
469                due: d.due,
470                detail: FristDetail::Wbci(d),
471            })
472            .collect();
473        for p in &self.spri {
474            let fall = p.geschaeftsfall();
475            for d in p.deadlines() {
476                let f = Frist {
477                    schnittstelle: Schnittstelle::Spri,
478                    partei: partei_spri(d.party, fall),
479                    auftrag: Some(p.externe_auftragsnummer().clone()),
480                    due: d.due,
481                    detail: FristDetail::Spri(d),
482                };
483                let dup = out.iter().any(|o| {
484                    o.auftrag == f.auftrag && o.due == f.due && o.partei == f.partei && o.rule().0 == f.rule().0
485                });
486                if !dup {
487                    out.push(f);
488                }
489            }
490        }
491        out.sort_by_key(|f| f.due);
492        out
493    }
494
495    /// What `partei` may do next on either interface. WBCI answers for both providers; an
496    /// S/PRI process answers for its owner and — the network owner's view, which sees every
497    /// message — for every party.
498    #[must_use]
499    pub fn next_actions(&self, partei: Partei) -> Vec<Aktion> {
500        let mut out: Vec<Aktion> = match partei {
501            Partei::EkpAuf => self.wbci.next_actions(WRole::EkpAuf),
502            Partei::EkpAbg => self.wbci.next_actions(WRole::EkpAbg),
503            Partei::Netzbetreiber => Vec::new(),
504        }
505        .into_iter()
506        .map(Aktion::Wbci)
507        .collect();
508        if partei == Partei::EkpAuf
509            && self.spri.is_empty()
510            && matches!(self.wbci.state(), WState::Agreed { .. })
511            && matches!(self.wbci.takeover(), Some(Takeover::Announced { uebernahme: true, .. }))
512        {
513            out.push(Aktion::SpriAuftragStellen);
514        }
515        for p in &self.spri {
516            let fall = p.geschaeftsfall();
517            for role in [SRole::Auftraggeber, SRole::Leistungserbringer, SRole::AbgebenderProvider] {
518                let sees = p.role() == role || p.role() == SRole::Leistungserbringer;
519                if !sees || partei_spri(role, fall) != partei {
520                    continue;
521                }
522                for action in p.next_actions(role) {
523                    let a = Aktion::Spri { auftrag: p.externe_auftragsnummer().clone(), action };
524                    if !out.contains(&a) {
525                        out.push(a);
526                    }
527                }
528            }
529        }
530        out
531    }
532
533    // -- the rules ------------------------------------------------------------------------
534
535    /// The (time, date) of every agreement in the WBCI history: the RUEM-VA and each ERLM to a
536    /// postponement.
537    fn agreed_dates(&self) -> Vec<(Timestamp, Date)> {
538        let mut tvs: Vec<(&wbci::AenderungsId, Date)> = Vec::new();
539        let mut out = Vec::new();
540        for e in self.wbci.history() {
541            match &e.message {
542                WMessage::Anfrage(Anfrage::Terminverschiebung(t)) => {
543                    tvs.push((&t.aenderungs_id, t.neuer_kundenwunschtermin));
544                }
545                WMessage::Meldung(WMeldung::RuemVa(r)) => out.push((e.at, r.wechseltermin)),
546                WMessage::Meldung(WMeldung::Erlm(m)) if m.kopf.geschaeftsfall == WFall::TvsVa => {
547                    let requested = tvs.iter().find(|(id, _)| Some(*id) == m.aenderungs_id.as_ref()).map(|(_, d)| *d);
548                    if let Some(d) = m.wechseltermin.or(requested) {
549                        out.push((e.at, d));
550                    }
551                }
552                _ => {}
553            }
554        }
555        out
556    }
557
558    /// The WBCI switch date in force at `at`.
559    fn termin_at(&self, at: Timestamp) -> Option<Date> {
560        self.agreed_dates().into_iter().filter(|(t, _)| *t <= at).map(|(_, d)| d).next_back()
561    }
562
563    fn nicht_abgestimmt(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
564        let Some(placed) = p.history().first().map(|e| e.at) else { return };
565        let agreed_at = match self.wbci.state() {
566            WState::Requested | WState::Rejected { .. } => None,
567            _ => self.agreed_dates().first().map(|(t, _)| *t),
568        };
569        if agreed_at.is_some_and(|a| a <= placed) {
570            return;
571        }
572        let (regel, quelle) = regeln::NICHT_ABGESTIMMT;
573        out.push(Befund {
574            regel,
575            quelle,
576            partei: partei_spri(SRole::Auftraggeber, p.geschaeftsfall()),
577            text: format!(
578                "order {} ({}) was placed before the WBCI pre-agreement {} was agreed (WBCI: {})",
579                p.externe_auftragsnummer(),
580                p.geschaeftsfall(),
581                self.vorabstimmungs_id(),
582                self.wbci.state()
583            ),
584        });
585    }
586
587    fn leitung(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
588        if p.geschaeftsfall() != GeschaeftsfallCode::Pv
589            || !matches!(self.wbci.takeover(), Some(Takeover::Announced { .. }))
590        {
591            return;
592        }
593        let Some(line) = order_line(p) else { return };
594        let Some(akm) = self.wbci.history().iter().rev().find_map(|e| match &e.message {
595            WMessage::Meldung(WMeldung::AkmTr(t)) => Some(t),
596            _ => None,
597        }) else {
598            return;
599        };
600        let lines: Vec<&LineId> = akm
601            .uebernahme_leitung
602            .iter()
603            .filter_map(|l| match l {
604                UebernahmeLeitung::LineId(l) => Some(l),
605                UebernahmeLeitung::Vertragsnummer(_) => None,
606            })
607            .collect();
608        if lines.is_empty() || lines.contains(&line) {
609            return;
610        }
611        let (regel, quelle) = regeln::LEITUNG;
612        out.push(Befund {
613            regel,
614            quelle,
615            partei: Partei::EkpAuf,
616            text: format!(
617                "order {} takes over line {line}, which the AKM-TR does not name ({})",
618                p.externe_auftragsnummer(),
619                lines.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
620            ),
621        });
622    }
623
624    fn termin(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
625        let Some(x) = self.wechseltermin() else { return };
626        let tv_sent = p.history().iter().any(|e| is_tv(&e.message));
627        let tv_open = p.pending().iter().any(|q| matches!(q, Pending::Terminverschiebung { .. }));
628        // After a Terminverschiebung the requested date is the rule of the TV; while one is
629        // open the ABM is still the old one.
630        let wish = if tv_sent { None } else { order_wish(p).filter(|w| *w != x) };
631        let abm = if tv_open { None } else { p.liefertermin().filter(|l| *l != x) };
632        let partei = match (wish, abm) {
633            (None, None) => return,
634            (Some(_), _) => partei_spri(SRole::Auftraggeber, p.geschaeftsfall()),
635            (None, Some(_)) => Partei::Netzbetreiber,
636        };
637        let mut parts = Vec::new();
638        if let Some(w) = wish {
639            parts.push(format!("requested {}", Day(w)));
640        }
641        if let Some(l) = abm {
642            parts.push(format!("confirmed {}", Day(l)));
643        }
644        let (regel, quelle) = regeln::TERMIN;
645        out.push(Befund {
646            regel,
647            quelle,
648            partei,
649            text: format!(
650                "order {}: {} — the WBCI switch date is {}",
651                p.externe_auftragsnummer(),
652                parts.join(", "),
653                Day(x)
654            ),
655        });
656    }
657
658    fn tv_zuerst_wbci(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
659        for e in p.history() {
660            let SMessage::Auftrag(a) = &e.message else { continue };
661            if a.aenderungskennzeichen != Aenderungskennzeichen::Terminverschiebung {
662                continue;
663            }
664            let Some(neu) = a.termin_neu.or_else(|| wunschtermin(&a.geschaeftsfall)) else { continue };
665            let in_force = self.termin_at(e.at);
666            if in_force == Some(neu) {
667                continue;
668            }
669            let (regel, quelle) = regeln::TV_ZUERST_WBCI;
670            let wbci = in_force.map_or_else(|| "none".to_owned(), |d| Day(d).to_string());
671            out.push(Befund {
672                regel,
673                quelle,
674                partei: Partei::EkpAuf,
675                text: format!(
676                    "order {}: Terminverschiebung to {} while the WBCI switch date is {wbci}; postpone in WBCI first (TVS-VA, ERLM 8003)",
677                    p.externe_auftragsnummer(),
678                    Day(neu)
679                ),
680            });
681        }
682    }
683
684    fn storno(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
685        let what = match self.wbci.state() {
686            WState::Cancelled => "cancelled",
687            WState::Changed { .. } => "changed",
688            _ => return,
689        };
690        if self.agreed_dates().is_empty() {
691            return; // never agreed: the order is wechsel.nicht-abgestimmt
692        }
693        let open = matches!(
694            p.state(),
695            SState::Sent
696                | SState::Received
697                | SState::Accepted
698                | SState::Confirmed { .. }
699                | SState::TamOpen { .. }
700                | SState::MtamOpen { .. }
701                | SState::ErlmKCheck
702        );
703        if !open || p.pending().iter().any(|q| matches!(q, Pending::Storno { .. })) {
704            return;
705        }
706        let (regel, quelle) = regeln::STORNO;
707        out.push(Befund {
708            regel,
709            quelle,
710            partei: partei_spri(SRole::Auftraggeber, p.geschaeftsfall()),
711            text: format!(
712                "the WBCI pre-agreement {} is {what} but order {} ({}) is still open: cancel it (Storno)",
713                self.vorabstimmungs_id(),
714                p.externe_auftragsnummer(),
715                p.geschaeftsfall()
716            ),
717        });
718    }
719
720    fn kontinuitaet(&self, p: &spri::process::Process, out: &mut Vec<Befund>) {
721        if !matches!(p.geschaeftsfall(), GeschaeftsfallCode::Pv | GeschaeftsfallCode::Neu) {
722            return;
723        }
724        let Some(x) = self.wechseltermin() else { return };
725        let Some(done) = completion(p) else { return };
726        let latest = Calendar::wbci().add_working_days(x, 1);
727        if done <= latest {
728            return;
729        }
730        let (regel, quelle) = regeln::KONTINUITAET;
731        out.push(Befund {
732            regel,
733            quelle,
734            partei: Partei::Netzbetreiber,
735            text: format!(
736                "order {} completed on {}, later than one working day after the WBCI switch date {} (latest {})",
737                p.externe_auftragsnummer(),
738                Day(done),
739                Day(x),
740                Day(latest)
741            ),
742        });
743    }
744}
745
746const fn is_tv(m: &SMessage) -> bool {
747    matches!(m, SMessage::Auftrag(a) if matches!(a.aenderungskennzeichen, Aenderungskennzeichen::Terminverschiebung))
748}
749
750const fn wunschtermin(g: &SFall) -> Option<Date> {
751    match g {
752        SFall::Neu(x) => Some(x.wunschtermin.datum),
753        SFall::KueAg(x) => Some(x.wunschtermin.datum),
754        SFall::Lae(x) => Some(x.wunschtermin.datum),
755        SFall::AenLmae(x) => Some(x.wunschtermin.datum),
756        SFall::Est(x) => Some(x.wunschtermin.datum),
757        SFall::Pv(x) => Some(x.wunschtermin.datum),
758        SFall::Get(_) | SFall::Set(_) => None,
759    }
760}
761
762/// The order's own requested date — the AKM-PV's planned date in the losing provider's view.
763fn order_wish(p: &spri::process::Process) -> Option<Date> {
764    p.history().first().and_then(|e| match &e.message {
765        SMessage::Auftrag(a) => wunschtermin(&a.geschaeftsfall),
766        SMessage::Meldung(m) => match &m.inhalt {
767            Meldungsinhalt::AkmPv(a) => Some(a.aufnehmender_provider.uebernahmedatum_geplant),
768            _ => None,
769        },
770        SMessage::Teq(_) => None,
771    })
772}
773
774/// The line the order takes over — the AKM-PV's in the losing provider's view.
775fn order_line(p: &spri::process::Process) -> Option<&LineId> {
776    p.history().first().and_then(|e| match &e.message {
777        SMessage::Auftrag(a) => a.geschaeftsfall.line_id(),
778        SMessage::Meldung(m) => match &m.inhalt {
779            Meldungsinhalt::AkmPv(a) => Some(&a.line_id),
780            _ => None,
781        },
782        SMessage::Teq(_) => None,
783    })
784}
785
786/// The completion date: of the last ERLM that is not a Storno's, or of the ERLM-PV.
787fn completion(p: &spri::process::Process) -> Option<Date> {
788    p.history().iter().rev().find_map(|e| match &e.message {
789        SMessage::Meldung(m) => match &m.inhalt {
790            Meldungsinhalt::Erlm(x)
791                if m.auftragstyp.aenderungskennzeichen != Aenderungskennzeichen::Storno
792                    && !m.codes().iter().any(|c| c.as_str() == "0012") =>
793            {
794                Some(x.erledigungstermin)
795            }
796            Meldungsinhalt::ErlmPv(x) => Some(x.erledigungstermin),
797            _ => None,
798        },
799        _ => None,
800    })
801}
802
803fn wbci_label(m: &WMessage) -> &'static str {
804    match m {
805        WMessage::Anfrage(a) => a.geschaeftsfall().as_str(),
806        WMessage::Meldung(m) => m.meldungstyp().as_str(),
807        WMessage::Teq(_) => "TEQ",
808    }
809}
810
811fn wbci_codes(m: &WMessage) -> Vec<String> {
812    match m {
813        WMessage::Anfrage(_) => Vec::new(),
814        WMessage::Meldung(m) => m.codes().map(|c| c.as_str().to_owned()).collect(),
815        WMessage::Teq(t) => t.positionen.iter().map(|p| p.code.as_str().to_owned()).collect(),
816    }
817}
818
819const fn spri_label(m: &SMessage) -> &'static str {
820    match m {
821        SMessage::Auftrag(a) => match a.aenderungskennzeichen {
822            Aenderungskennzeichen::Standard => a.geschaeftsfall.code().as_str(),
823            Aenderungskennzeichen::Storno => "Storno",
824            Aenderungskennzeichen::Terminverschiebung => "Terminverschiebung",
825        },
826        SMessage::Meldung(m) => m.typ().as_str(),
827        SMessage::Teq(_) => "TEQ",
828    }
829}
830
831fn spri_codes(m: &SMessage) -> Vec<String> {
832    match m {
833        SMessage::Auftrag(_) => Vec::new(),
834        SMessage::Meldung(m) => m.codes().iter().map(|c| c.as_str().to_owned()).collect(),
835        SMessage::Teq(t) => t.positionen.iter().map(|p| p.code.as_str().to_owned()).collect(),
836    }
837}