Skip to main content

spri/
process.rs

1//! The life of one S/PRI order, as one party sees it.
2//!
3//! A [`Process`] is created from an order ([`Process::new`]), from the network owner's
4//! cancellation announcement ([`Process::from_kdle`]) or, for the losing provider of a provider
5//! switch, from the AKM-PV ([`Process::from_akm_pv`]). It is then fed every order, message and
6//! technical receipt that is sent or received for it, with its time. It checks that the event
7//! is allowed — right sender, right order, right moment for the business case — and refuses it
8//! otherwise, leaving itself unchanged. It reports its [`State`], the open Storno and
9//! Terminverschiebung ([`Pending`]), the provider-switch leg with the losing provider
10//! ([`PvLeg`]), what each side may do next, the open deadlines and its history. It performs no
11//! I/O and reads no clock.
12//!
13//! Sources: the EPKs of Anlage 7 V.13 (`Anl. 7 EPK V.13 p.N`: p.1 NEU, p.2 NEU Konnektivität,
14//! p.3 KUE-AG, p.4 KUE-LE, p.5 AEN-LMAE, p.6 LAE, p.7 PV, p.8 EST, p.9 DIAG, p.10 TEQ, p.11 Storno,
15//! p.12 Terminverschiebung), the Providervereinbarung S/PRI V4.4 (`S/PRI 4.4 §x`) and the
16//! Arbeitshandbuch S/PRI 4.x V2.9.5 (`AH 2.9.5 §x`).
17//!
18//! ```
19//! use spri::process::{Action, Direction, Process, Role, State};
20//! use spri::*;
21//!
22//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
23//! let ext = ExterneAuftragsnummer::new("K-2026-0001")?;
24//! let ag = Auftraggebernummer::new("4711")?;
25//! let kdle = Meldung {
26//!     auftragstyp: Auftragstyp {
27//!         geschaeftsfall: GeschaeftsfallCode::KueLe,
28//!         aenderungskennzeichen: Aenderungskennzeichen::Standard,
29//!         geschaeftsfallart: GeschaeftsfallArt::Kuendigung,
30//!     },
31//!     inhalt: Meldungsinhalt::Kdle(Kdle {
32//!         vertragsnummer: Vertragsnummer::new("V123456")?,
33//!         externe_auftragsnummer: ext.clone(),
34//!         auftraggebernummer: ag.clone(),
35//!         abschaltungstermin: "2027-06-30".parse()?,
36//!         abschaltungsgrund: None,
37//!         positionen: vec![Position::new(Meldungscode::C8006)],
38//!     }),
39//! };
40//!
41//! // The service provider receives the network owner's cancellation and acknowledges it.
42//! let mut p = Process::from_kdle(Role::Auftraggeber, &kdle, Direction::Received, "2026-11-23T08:00:00Z".parse()?)?;
43//! assert_eq!(p.next_actions(Role::Auftraggeber), [Action::Acknowledge]);
44//! p.apply(Direction::Sent, "2026-11-23T08:00:01Z".parse()?, Teq::new(Meldungscode::Ok, Some(ext.clone()), Some(ag.clone())))?;
45//! assert_eq!(*p.state(), State::Confirmed { liefertermin: "2027-06-30".parse()? });
46//!
47//! // An ENTM before the ERLM is refused, and nothing changes.
48//! let entm = Meldung {
49//!     auftragstyp: kdle.auftragstyp,
50//!     inhalt: Meldungsinhalt::Entm(Entm {
51//!         vertragsnummer: Vertragsnummer::new("V123456")?,
52//!         externe_auftragsnummer: ext,
53//!         auftraggebernummer: ag,
54//!         auftraggebernummer_besteller: None,
55//!         vorabstimmungs_id: None,
56//!         entgelttermin: "2027-06-30".parse()?,
57//!         anlage: None,
58//!         positionen: vec![Position::new(Meldungscode::C0010)],
59//!     }),
60//! };
61//! let before = p.clone();
62//! let refusal = p.apply(Direction::Received, "2026-11-24T08:00:00Z".parse()?, entm).unwrap_err();
63//! assert!(refusal.reason.contains("ENTM"));
64//! assert_eq!(p, before);
65//! # Ok(())
66//! # }
67//! ```
68//!
69//! ## Interpretations
70//!
71//! - The Storno and Terminverschiebung window is 36 hours of elapsed time before 0:00 of the
72//!   binding date (AH 2.9.5 §3.4, §3.5); the code fact sheets say 3 Arbeitstage. After a TAM the
73//!   window does not apply (AH 2.9.5 §3.4).
74//! - A TEQ answers the oldest sent item still awaiting one in that direction (the receipt is
75//!   the synchronous response of the call, S/PRI 4.4 §11.2.3), and a later message from the
76//!   receiver proves delivery of what was sent to it before (§11.2.3.3: the order of messages
77//!   is guaranteed).
78//! - A negative TEQ to a message of the network owner does not undo it: the network owner
79//!   counts it as delivered (S/PRI 4.4 §11.2.3.2; for KDLE also AH 2.9.5 §2.6). The same is
80//!   assumed for its messages to the losing provider. A negative TEQ to anything the service
81//!   provider or the losing provider sent restores the process to before that item.
82//! - Where the EPK and the text disagree, the EPK is followed: a TV is allowed in LAE (Anl. 7
83//!   EPK V.13 p.6, against S/PRI 4.4 §5.3.2.4), and an EST draws an ENTM (p.8) but also ends at
84//!   the ERLM (S/PRI 4.4 §8.2.4).
85//! - An ABBM is accepted from the receipt of the order until the ERLM (S/PRI 4.4 §8.2.5), also
86//!   where an EPK draws none; codes with a fixed place are checked (`1198` after an MTAM, `7015`
87//!   after an EST TAM, `0041`/`0042` after a negative or missing RUEM-PV).
88//! - A message answers the open Storno or TV when its Änderungskennzeichen says so, or by its
89//!   code when it carries Standard (`1086`, `1087`, ERLM `0012` for a Storno; `1085`,
90//!   `7522`–`7524` for a TV; `1007` when only one of them is open). A new ABM answers the TV.
91//! - The ABM-PV is applied after its ABM (they are sent together, S/PRI 4.4 §8.2.13). The
92//!   ABBM-PV `0040` is expected whenever the switch ends without taking place after an AKM-PV
93//!   (S/PRI 4.4 §5.5.1.2), also on the TAM path, which the EPK does not draw.
94//! - A RUEM-PV after the antwortfrist is refused: the network owner aborts (S/PRI 4.4
95//!   §5.5.1.1). A RUEM-PV is negative when `zustimmungProviderwechsel` is `N` or its
96//!   `antwortcode` is one of `LnB`, `KVE`, `TAV`, `VnB`, `Vnv` (AH 2.9.5 §6.5; Anl. 7 EPK V.13 p.7
97//!   writes `LNB`), compared ignoring ASCII case.
98//! - A NEU is a Konnektivität (build-out) order when the caller says so
99//!   ([`Process::with_konnektivitaet`]) or its first ABM carries a LineID whose line code is
100//!   all zeros (S/PRI 4.4 §5.1.6). It completes only after an ABM with a real LineID.
101//! - The effects of a KDLE on other orders of the line (S/PRI 4.4 §5.2.2.2) and of an
102//!   Auftragsklammer are reported ([`Process::is_aborted_by_kdle`]), not enforced across
103//!   processes.
104
105use core::fmt;
106
107use carrier_core::Calendar;
108use carrier_core::count::day_of;
109use jiff::Timestamp;
110use jiff::civil::Date;
111
112use crate::deadline::{self, Deadline};
113use crate::{
114    Aenderungskennzeichen, Antwortcode, Auftrag, ExterneAuftragsnummer, Geschaeftsfall, GeschaeftsfallCode, JaNein,
115    LineId, Meldung, Meldungscode, Meldungsinhalt, Meldungstyp, StoerungsNr, Teq, VorabstimmungsId,
116};
117
118/// A party of an S/PRI order.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Role {
121    /// The service provider (EKP, in a provider switch the EKPauf): sends orders, Storno,
122    /// Terminverschiebung, ERLM-K, ZWM-AG, TBK-AG.
123    Auftraggeber,
124    /// The network owner (NGA, NGAB): sends TEQ, QEB, ABM, ABBM, VZM, TAM, MTAM, ERLM, ENTM,
125    /// ZWM-LE, TBK-LE, KDLE and the messages to the losing provider.
126    Leistungserbringer,
127    /// The losing provider of a provider switch (EKPab): answers the AKM-PV with a RUEM-PV.
128    AbgebenderProvider,
129}
130
131impl fmt::Display for Role {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.write_str(match self {
134            Self::Auftraggeber => "Auftraggeber",
135            Self::Leistungserbringer => "Leistungserbringer",
136            Self::AbgebenderProvider => "abgebender Provider",
137        })
138    }
139}
140
141/// Whether an event was sent by the owner of the process or received by it.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
143pub enum Direction {
144    /// Sent by the owner.
145    Sent,
146    /// Received by the owner.
147    Received,
148}
149
150/// What travels between the parties.
151#[derive(Debug, Clone, PartialEq, Eq)]
152#[allow(clippy::large_enum_variant)]
153pub enum Message {
154    /// An order; with Änderungskennzeichen Storno or Terminverschiebung the Storno or TV of the
155    /// order with the same order number.
156    Auftrag(Auftrag),
157    /// A business message.
158    Meldung(Meldung),
159    /// A technical receipt.
160    Teq(Teq),
161}
162
163impl From<Auftrag> for Message {
164    fn from(a: Auftrag) -> Self {
165        Self::Auftrag(a)
166    }
167}
168impl From<Meldung> for Message {
169    fn from(m: Meldung) -> Self {
170        Self::Meldung(m)
171    }
172}
173impl From<Teq> for Message {
174    fn from(t: Teq) -> Self {
175        Self::Teq(t)
176    }
177}
178
179/// One accepted event in the history.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct Event {
182    /// When it was sent or received.
183    pub at: Timestamp,
184    /// Sent or received by the owner.
185    pub direction: Direction,
186    /// The party that sent it.
187    pub sender: Role,
188    /// What it was.
189    pub message: Message,
190}
191
192/// Where an order stands.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum State {
195    /// Sent; no technical receipt yet.
196    Sent,
197    /// Not delivered: the receipt was negative. `0991` asks to send the same order again
198    /// later, any other code to correct it first (Anl. 7 EPK V.13 p.10).
199    Rejected {
200        /// The receipt's code.
201        code: Meldungscode,
202    },
203    /// Delivered (positive TEQ); awaiting the QEB (DIAG: the ERLM).
204    Received,
205    /// Commercially admissible (QEB); awaiting the ABM (EST: the repair).
206    Accepted,
207    /// Confirmed for a binding date (ABM; KUE-LE: the KDLE's shutdown date).
208    Confirmed {
209        /// The binding date (verbindlicher Liefertermin).
210        liefertermin: Date,
211    },
212    /// The network owner asked for a new appointment (TAM).
213    TamOpen {
214        /// When the TAM was sent.
215        since: Timestamp,
216    },
217    /// The network owner asked again (MTAM).
218    MtamOpen {
219        /// When the MTAM was sent.
220        since: Timestamp,
221    },
222    /// The service provider reported the service done (ERLM-K); the network owner checks.
223    ErlmKCheck,
224    /// Realised (ERLM); the ENTM follows (optional in EST).
225    Completed {
226        /// The completion date.
227        erledigungstermin: Date,
228    },
229    /// Cancelled by a confirmed Storno (ERLM `0012`); the ENTM follows.
230    Cancelled,
231    /// Billed (ENTM) or, for DIAG, answered (ERLM): nothing more happens.
232    Closed,
233    /// Aborted with an ABBM: nothing more happens.
234    Aborted {
235        /// The first code of the ABBM.
236        code: Meldungscode,
237    },
238}
239
240impl State {
241    /// Whether nothing more can happen to the order (the provider-switch leg may still owe
242    /// its last message).
243    #[must_use]
244    pub const fn is_terminal(&self) -> bool {
245        matches!(self, Self::Closed | Self::Aborted { .. })
246    }
247
248    /// Whether the order is still being worked on: after the receipt, before the ERLM.
249    const fn is_open(&self) -> bool {
250        matches!(
251            self,
252            Self::Received
253                | Self::Accepted
254                | Self::Confirmed { .. }
255                | Self::TamOpen { .. }
256                | Self::MtamOpen { .. }
257                | Self::ErlmKCheck
258        )
259    }
260
261    /// After the QEB and before the ERLM.
262    const fn is_after_qeb(&self) -> bool {
263        self.is_open() && !matches!(self, Self::Received)
264    }
265}
266
267impl fmt::Display for State {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::Sent => f.write_str("sent"),
271            Self::Rejected { code } => write!(f, "not delivered ({})", code.as_str()),
272            Self::Received => f.write_str("received"),
273            Self::Accepted => f.write_str("accepted (QEB)"),
274            Self::Confirmed { liefertermin } => write!(f, "confirmed for {liefertermin}"),
275            Self::TamOpen { .. } => f.write_str("appointment requested (TAM)"),
276            Self::MtamOpen { .. } => f.write_str("appointment requested again (MTAM)"),
277            Self::ErlmKCheck => f.write_str("reported done (ERLM-K)"),
278            Self::Completed { erledigungstermin } => write!(f, "completed on {erledigungstermin}"),
279            Self::Cancelled => f.write_str("cancelled"),
280            Self::Closed => f.write_str("closed"),
281            Self::Aborted { code } => write!(f, "aborted ({})", code.as_str()),
282        }
283    }
284}
285
286/// An open Storno or Terminverschiebung (at most one of each, Anl. 7 EPK V.13 p.11, p.12).
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub enum Pending {
289    /// A Storno awaiting ERLM (cancelled) or ABBM (failed, the order continues).
290    Storno {
291        /// When it was sent.
292        since: Timestamp,
293    },
294    /// A Terminverschiebung awaiting a new ABM (moved) or ABBM (failed, the order continues).
295    Terminverschiebung {
296        /// When it was sent.
297        since: Timestamp,
298        /// The requested new date.
299        termin: Option<Date>,
300    },
301}
302
303impl Pending {
304    const fn is_storno(&self) -> bool {
305        matches!(self, Self::Storno { .. })
306    }
307}
308
309/// How the losing provider answered the AKM-PV.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub enum PvAnswer {
312    /// RUEM-PV with consent.
313    Positive,
314    /// RUEM-PV refusing the switch.
315    Negative,
316    /// No RUEM-PV by the end of the antwortfrist.
317    Missing,
318}
319
320/// The provider-switch leg between the network owner and the losing provider (Anl. 7 EPK V.13
321/// p.7; S/PRI 4.4 §5.5.1). The service provider does not see it.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum PvLeg {
324    /// AKM-PV sent; the RUEM-PV is due by the end of `antwortfrist`.
325    AwaitRuem {
326        /// The answer date of the AKM-PV.
327        antwortfrist: Date,
328    },
329    /// The losing provider refused: ABBM `0041` to the service provider and ABBM-PV `0040`
330    /// are due.
331    Refused {
332        /// The RUEM-PV's `antwortcode`.
333        antwortcode: Option<Antwortcode>,
334    },
335    /// No answer in time: ABBM `0042` and ABBM-PV `0040` are due.
336    Missed,
337    /// The losing provider agreed (RUEM-PV `0021`).
338    Agreed,
339    /// The switch date was confirmed (ABM-PV).
340    Confirmed {
341        /// `uebernahmedatumVerbindlich`.
342        uebernahmedatum: Date,
343    },
344    /// The line was taken over (ERLM-PV); the ENTM-PV follows.
345    Completed,
346    /// The losing provider's billing ends (ENTM-PV).
347    Closed,
348    /// The switch was aborted (ABBM-PV); the losing provider's contract stays.
349    Aborted {
350        /// What the losing provider had answered.
351        answer: PvAnswer,
352    },
353}
354
355impl PvLeg {
356    const fn is_open(&self) -> bool {
357        !matches!(self, Self::Closed | Self::Aborted { .. })
358    }
359}
360
361/// Something a party may do next.
362#[derive(Debug, Clone, PartialEq, Eq)]
363#[non_exhaustive]
364pub enum Action {
365    /// Send the technical receipt (TEQ) for something received.
366    Acknowledge,
367    /// Send the same order or message again later: the receiver was overloaded (`0991`).
368    Resend,
369    /// Correct the order or message before sending it again (TEQ `0990`, `0993`, `0995`,
370    /// `0999`).
371    Correct,
372    /// Send a message of this type.
373    Send(Meldungstyp),
374    /// Abort with an ABBM carrying this code (`0041`, `0042`, `1198`, `7015`).
375    Abort(Meldungscode),
376    /// Cancel the order (Storno).
377    Storno,
378    /// Move the date (Terminverschiebung).
379    Terminverschiebung,
380    /// Answer the open Storno (VZM, ABBM or ERLM).
381    AnswerStorno,
382    /// Answer the open Terminverschiebung (VZM, ABBM or a new ABM).
383    AnswerTerminverschiebung,
384    /// Complain about the repair (EST Reklamation with the same order number, S/PRI 4.4 §6.1.5).
385    Reklamation,
386}
387
388/// Why an event was refused: the message type and the rule, without values.
389#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
390#[error("{reason}")]
391pub struct Refusal {
392    /// Why, naming the message type and the rule's source.
393    pub reason: String,
394    /// For a Storno or Terminverschiebung the network owner receives: the ABBM code to answer
395    /// with (1007 change marker not allowed, 1085 TV not possible, 1086 Storno already open,
396    /// 1087 Storno not possible).
397    pub answer: Option<Meldungscode>,
398}
399
400fn refuse<T>(reason: impl Into<String>) -> Result<T, Refusal> {
401    Err(Refusal { reason: reason.into(), answer: None })
402}
403
404fn refuse_with<T>(answer: Meldungscode, reason: impl Into<String>) -> Result<T, Refusal> {
405    Err(Refusal { reason: reason.into(), answer: Some(answer) })
406}
407
408/// What an awaited receipt is for.
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410enum Item {
411    Order,
412    Storno,
413    Tv,
414    Meldung(Meldungstyp),
415}
416
417/// Something sent by a party that could not be delivered.
418#[derive(Debug, Clone, PartialEq, Eq)]
419struct Undelivered {
420    from: Role,
421    code: Meldungscode,
422}
423
424/// The mutable part, snapshotted before each sent item so a negative receipt can undo it.
425#[derive(Debug, Clone, PartialEq, Eq)]
426#[allow(clippy::struct_excessive_bools)] // independent facts of one order
427struct Core {
428    state: State,
429    liefertermin: Option<Date>,
430    wunschtermin: Option<Date>,
431    konnektivitaet: bool,
432    activated: bool,
433    abm_seen: bool,
434    pending: Vec<Pending>,
435    pv: Option<PvLeg>,
436    pv_ext: Option<ExterneAuftragsnummer>,
437    abm_pv_owed: bool,
438    undelivered: Option<Undelivered>,
439    stoerungs_nr: Option<StoerungsNr>,
440}
441
442impl Core {
443    fn new(state: State) -> Self {
444        Self {
445            state,
446            liefertermin: None,
447            wunschtermin: None,
448            konnektivitaet: false,
449            activated: false,
450            abm_seen: false,
451            pending: Vec::new(),
452            pv: None,
453            pv_ext: None,
454            abm_pv_owed: false,
455            undelivered: None,
456            stoerungs_nr: None,
457        }
458    }
459}
460
461/// An item awaiting its receipt.
462#[derive(Debug, Clone, PartialEq, Eq)]
463struct Awaiting {
464    from: Role,
465    to: Role,
466    at: Timestamp,
467    attachment: bool,
468    item: Item,
469    before: Box<Core>,
470}
471
472/// What a handler accepted: the sender, and the item that now awaits a receipt.
473struct Accepted {
474    sender: Role,
475    hop: Option<(Role, Item, bool)>,
476}
477
478/// One S/PRI order from the point of view of one party.
479#[derive(Debug, Clone, PartialEq, Eq)]
480pub struct Process {
481    role: Role,
482    fall: GeschaeftsfallCode,
483    ext: ExterneAuftragsnummer,
484    calendar: Calendar,
485    core: Core,
486    awaiting: Vec<Awaiting>,
487    history: Vec<Event>,
488}
489
490const fn sender_of(typ: Meldungstyp) -> Role {
491    match typ {
492        Meldungstyp::ErlmK | Meldungstyp::ZwmAg | Meldungstyp::TbkAg => Role::Auftraggeber,
493        Meldungstyp::RuemPv => Role::AbgebenderProvider,
494        _ => Role::Leistungserbringer,
495    }
496}
497
498const fn is_leg(typ: Meldungstyp) -> bool {
499    matches!(
500        typ,
501        Meldungstyp::AkmPv
502            | Meldungstyp::RuemPv
503            | Meldungstyp::AbmPv
504            | Meldungstyp::ErlmPv
505            | Meldungstyp::EntmPv
506            | Meldungstyp::AbbmPv
507    )
508}
509
510const fn receiver_of(typ: Meldungstyp) -> Role {
511    match typ {
512        Meldungstyp::ErlmK | Meldungstyp::ZwmAg | Meldungstyp::TbkAg | Meldungstyp::RuemPv => Role::Leistungserbringer,
513        t if is_leg(t) => Role::AbgebenderProvider,
514        _ => Role::Auftraggeber,
515    }
516}
517
518const fn meldung_has_attachment(m: &Meldungsinhalt) -> bool {
519    match m {
520        Meldungsinhalt::Erlm(x) => x.anlage.is_some(),
521        Meldungsinhalt::Entm(x) => x.anlage.is_some(),
522        Meldungsinhalt::ZwmLe(x) => x.anlage.is_some(),
523        Meldungsinhalt::ZwmAg(x) => x.anlage.is_some(),
524        Meldungsinhalt::AkmPv(x) => x.anlage.is_some(),
525        _ => false,
526    }
527}
528
529const fn order_has_attachment(g: &Geschaeftsfall) -> bool {
530    match g {
531        Geschaeftsfall::Neu(x) => x.anlage.is_some(),
532        Geschaeftsfall::KueAg(x) => x.anlage.is_some(),
533        Geschaeftsfall::Lae(x) => x.anlage.is_some(),
534        Geschaeftsfall::AenLmae(x) => x.anlage.is_some(),
535        Geschaeftsfall::Est(x) => x.anlage.is_some(),
536        Geschaeftsfall::Pv(x) => x.anlage.is_some(),
537        Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => false,
538    }
539}
540
541const fn wunschtermin_of(g: &Geschaeftsfall) -> Option<Date> {
542    match g {
543        Geschaeftsfall::Neu(x) => Some(x.wunschtermin.datum),
544        Geschaeftsfall::KueAg(x) => Some(x.wunschtermin.datum),
545        Geschaeftsfall::Lae(x) => Some(x.wunschtermin.datum),
546        Geschaeftsfall::AenLmae(x) => Some(x.wunschtermin.datum),
547        Geschaeftsfall::Est(x) => Some(x.wunschtermin.datum),
548        Geschaeftsfall::Pv(x) => Some(x.wunschtermin.datum),
549        Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => None,
550    }
551}
552
553/// A LineID whose line code (the part after the carrier code) is all zeros: the dummy LineID
554/// of a Konnektivität order's first ABM (S/PRI 4.4 §5.1.6).
555fn is_dummy(line: &LineId) -> bool {
556    line.as_str().rsplit('.').next().is_some_and(|c| !c.is_empty() && c.bytes().all(|b| b == b'0'))
557}
558
559fn has_code(m: &Meldungsinhalt, codes: &[&str]) -> bool {
560    m.codes().iter().any(|c| codes.contains(&c.as_str()))
561}
562
563/// The cases with a Storno (all but DIAG and KUE-LE, Anl. 7 EPK V.13 p.4, p.9).
564pub(crate) const fn has_storno(fall: GeschaeftsfallCode) -> bool {
565    !matches!(fall, GeschaeftsfallCode::Get | GeschaeftsfallCode::Set | GeschaeftsfallCode::KueLe)
566}
567
568/// The cases with a Terminverschiebung (NEU, KUE-AG, LAE, PV; Anl. 7 EPK V.13 p.1–3, p.6, p.7;
569/// none in AEN-LMAE, S/PRI 4.4 §5.3.1.3, EST, §6.1.3, DIAG and KUE-LE).
570pub(crate) const fn has_tv(fall: GeschaeftsfallCode) -> bool {
571    matches!(
572        fall,
573        GeschaeftsfallCode::Neu | GeschaeftsfallCode::KueAg | GeschaeftsfallCode::Lae | GeschaeftsfallCode::Pv
574    )
575}
576
577/// The cases with the TAM/MTAM/ERLM-K loop (AH 2.9.5 §3.6).
578const fn has_tam_loop(fall: GeschaeftsfallCode) -> bool {
579    matches!(fall, GeschaeftsfallCode::Neu | GeschaeftsfallCode::Lae | GeschaeftsfallCode::Pv)
580}
581
582/// The losing provider's refusal reasons (S/PRI 4.4 §5.5.1.1; AH 2.9.5 §6.5: `LnB`, `KVE`,
583/// `TAV`, `VnB`, `Vnv`). Compared ignoring ASCII case: the handbook writes `LnB`, the EPK `LNB`
584/// (interpretation).
585pub(crate) const REFUSAL_CODES: [&str; 5] = ["LnB", "KVE", "TAV", "VnB", "Vnv"];
586
587/// Whether `code` is one of [`REFUSAL_CODES`].
588pub(crate) fn is_refusal_code(code: &Antwortcode) -> bool {
589    REFUSAL_CODES.iter().any(|c| c.eq_ignore_ascii_case(code.as_str()))
590}
591
592/// A negative RUEM-PV (S/PRI 4.4 §5.5.1.1; Anl. 7 EPK V.13 p.7).
593fn ruem_negative(r: &crate::RuemPv) -> bool {
594    r.abgebender_provider.zustimmung == JaNein::Nein
595        || r.abgebender_provider.antwortcode.as_ref().is_some_and(is_refusal_code)
596}
597
598impl Process {
599    fn start(role: Role, fall: GeschaeftsfallCode, ext: ExterneAuftragsnummer, core: Core) -> Self {
600        Self { role, fall, ext, calendar: Calendar::werktage(), core, awaiting: Vec::new(), history: Vec::new() }
601    }
602
603    /// Starts the process of `auftrag` (ÄKZ Standard), sent by the service provider
604    /// (`role` [`Role::Auftraggeber`], [`Direction::Sent`]) or received by the network owner
605    /// (`role` [`Role::Leistungserbringer`], [`Direction::Received`]) at `at`. Counts Werktage
606    /// with [`Calendar::werktage`].
607    ///
608    /// # Errors
609    ///
610    /// The direction contradicts the role (only the service provider sends orders), the role
611    /// is the losing provider (use [`Process::from_akm_pv`]), or the order is a Storno or
612    /// Terminverschiebung (they continue an existing process).
613    pub fn new(role: Role, auftrag: &Auftrag, direction: Direction, at: Timestamp) -> Result<Self, Refusal> {
614        let expected = match direction {
615            Direction::Sent => Role::Auftraggeber,
616            Direction::Received => Role::Leistungserbringer,
617        };
618        if role != expected {
619            return refuse("an order is sent by the Auftraggeber to the Leistungserbringer (S/PRI 4.4 §8.3)");
620        }
621        if auftrag.aenderungskennzeichen != Aenderungskennzeichen::Standard {
622            return refuse(
623                "a Storno or Terminverschiebung repeats the order number of an existing order (S/PRI 4.4 §5.1.3, §5.1.4)",
624            );
625        }
626        let mut core = Core::new(State::Sent);
627        core.wunschtermin = wunschtermin_of(&auftrag.geschaeftsfall);
628        let fall = auftrag.geschaeftsfall.code();
629        let mut p = Self::start(role, fall, auftrag.externe_auftragsnummer.clone(), core);
630        p.awaiting.push(Awaiting {
631            from: Role::Auftraggeber,
632            to: Role::Leistungserbringer,
633            at,
634            attachment: order_has_attachment(&auftrag.geschaeftsfall),
635            item: Item::Order,
636            before: Box::new(p.core.clone()),
637        });
638        p.history.push(Event { at, direction, sender: Role::Auftraggeber, message: Message::Auftrag(auftrag.clone()) });
639        Ok(p)
640    }
641
642    /// Starts the process of the network owner's cancellation (KUE-LE, Anl. 7 EPK V.13 p.4):
643    /// `kdle` sent by the network owner or received by the service provider at `at`. The
644    /// state is [`State::Confirmed`] for the shutdown date; ERLM and ENTM follow.
645    ///
646    /// The KDLE also aborts the other open orders of the line except EST and DIAG (S/PRI 4.4
647    /// §5.2.2.2) and a provider switch (§5.5.1.4); see [`Process::is_aborted_by_kdle`].
648    ///
649    /// # Errors
650    ///
651    /// The message is not a KDLE of business case KUE-LE, the direction contradicts the role,
652    /// or the shutdown date is not in the future (S/PRI 4.4 §8.2.11).
653    pub fn from_kdle(role: Role, kdle: &Meldung, direction: Direction, at: Timestamp) -> Result<Self, Refusal> {
654        let Meldungsinhalt::Kdle(k) = &kdle.inhalt else {
655            return refuse("a KUE-LE process starts with a KDLE (Anl. 7 EPK V.13 p.4)");
656        };
657        if kdle.auftragstyp.geschaeftsfall != GeschaeftsfallCode::KueLe {
658            return refuse("a KDLE belongs to business case KUE-LE (Anl. 7 EPK V.13 p.4)");
659        }
660        let expected = match direction {
661            Direction::Sent => Role::Leistungserbringer,
662            Direction::Received => Role::Auftraggeber,
663        };
664        if role != expected {
665            return refuse("a KDLE is sent by the Leistungserbringer to the Auftraggeber (S/PRI 4.4 §8.2.11)");
666        }
667        if k.abschaltungstermin <= day_of(at) {
668            return refuse("a KDLE names a shutdown date in the future (S/PRI 4.4 §8.2.11)");
669        }
670        let mut core = Core::new(State::Confirmed { liefertermin: k.abschaltungstermin });
671        core.liefertermin = Some(k.abschaltungstermin);
672        let mut p = Self::start(role, GeschaeftsfallCode::KueLe, k.externe_auftragsnummer.clone(), core);
673        p.awaiting.push(Awaiting {
674            from: Role::Leistungserbringer,
675            to: Role::Auftraggeber,
676            at,
677            attachment: false,
678            item: Item::Meldung(Meldungstyp::Kdle),
679            before: Box::new(p.core.clone()),
680        });
681        p.history.push(Event {
682            at,
683            direction,
684            sender: Role::Leistungserbringer,
685            message: Message::Meldung(kdle.clone()),
686        });
687        Ok(p)
688    }
689
690    /// Starts the losing provider's view of a provider switch from the AKM-PV it received at
691    /// `at` (Anl. 7 EPK V.13 p.7). The process follows only the leg: RUEM-PV, ABM-PV, ERLM-PV,
692    /// ENTM-PV, ABBM-PV and their receipts; its [`State`] mirrors the switch (confirmed by the
693    /// ABM-PV, completed by the ERLM-PV, closed by the ENTM-PV, aborted by the ABBM-PV).
694    ///
695    /// # Errors
696    ///
697    /// The message is not an AKM-PV of business case PV.
698    pub fn from_akm_pv(akm_pv: &Meldung, at: Timestamp) -> Result<Self, Refusal> {
699        let Meldungsinhalt::AkmPv(a) = &akm_pv.inhalt else {
700            return refuse("the losing provider's process starts with an AKM-PV (Anl. 7 EPK V.13 p.7)");
701        };
702        if akm_pv.auftragstyp.geschaeftsfall != GeschaeftsfallCode::Pv {
703            return refuse("an AKM-PV belongs to business case PV (Anl. 7 EPK V.13 p.7)");
704        }
705        let mut core = Core::new(State::Accepted);
706        core.pv = Some(PvLeg::AwaitRuem { antwortfrist: a.aufnehmender_provider.antwortfrist });
707        core.pv_ext = Some(a.externe_auftragsnummer.clone());
708        core.wunschtermin = Some(a.aufnehmender_provider.uebernahmedatum_geplant);
709        let mut p =
710            Self::start(Role::AbgebenderProvider, GeschaeftsfallCode::Pv, a.externe_auftragsnummer.clone(), core);
711        p.awaiting.push(Awaiting {
712            from: Role::Leistungserbringer,
713            to: Role::AbgebenderProvider,
714            at,
715            attachment: a.anlage.is_some(),
716            item: Item::Meldung(Meldungstyp::AkmPv),
717            before: Box::new(p.core.clone()),
718        });
719        p.history.push(Event {
720            at,
721            direction: Direction::Received,
722            sender: Role::Leistungserbringer,
723            message: Message::Meldung(akm_pv.clone()),
724        });
725        Ok(p)
726    }
727
728    /// Marks a NEU as a Konnektivität (build-out) order (Anl. 7 EPK V.13 p.2; S/PRI 4.4
729    /// §5.1.6): no Terminverschiebung before the first ABM, and completion only after the
730    /// activation ABM with a real LineID. Has no effect on other business cases.
731    #[must_use]
732    pub fn with_konnektivitaet(mut self) -> Self {
733        if self.fall == GeschaeftsfallCode::Neu {
734            self.core.konnektivitaet = true;
735            for w in &mut self.awaiting {
736                w.before.konnektivitaet = true;
737            }
738        }
739        self
740    }
741
742    /// Counts Werktage with `calendar` (default [`Calendar::werktage`]), e.g. with a closed day
743    /// added.
744    #[must_use]
745    pub fn with_calendar(mut self, calendar: Calendar) -> Self {
746        self.calendar = calendar;
747        self
748    }
749
750    /// The owner's side.
751    #[must_use]
752    pub const fn role(&self) -> Role {
753        self.role
754    }
755
756    /// The business case.
757    #[must_use]
758    pub const fn geschaeftsfall(&self) -> GeschaeftsfallCode {
759        self.fall
760    }
761
762    /// The order number every message of the process repeats.
763    #[must_use]
764    pub const fn externe_auftragsnummer(&self) -> &ExterneAuftragsnummer {
765        &self.ext
766    }
767
768    /// The state.
769    #[must_use]
770    pub const fn state(&self) -> &State {
771        &self.core.state
772    }
773
774    /// The WBCI Vorabstimmungs-ID of the order — of the AKM-PV in the losing provider's view —
775    /// if it carries one (S/PRI 4.4 §5.5.1.1).
776    #[must_use]
777    pub fn vorabstimmungs_id(&self) -> Option<&VorabstimmungsId> {
778        self.history.first().and_then(|e| match &e.message {
779            Message::Auftrag(a) => a.geschaeftsfall.vorabstimmungs_id(),
780            Message::Meldung(Meldung { inhalt: Meldungsinhalt::AkmPv(a), .. }) => a.vorabstimmungs_id.as_ref(),
781            Message::Meldung(_) | Message::Teq(_) => None,
782        })
783    }
784
785    /// The binding date of the latest ABM (KUE-LE: the shutdown date).
786    #[must_use]
787    pub const fn liefertermin(&self) -> Option<Date> {
788        self.core.liefertermin
789    }
790
791    /// Whether the order is a Konnektivität order (declared or detected from the first ABM).
792    #[must_use]
793    pub const fn is_konnektivitaet(&self) -> bool {
794        self.core.konnektivitaet
795    }
796
797    /// The open Storno and Terminverschiebung.
798    #[must_use]
799    pub fn pending(&self) -> &[Pending] {
800        &self.core.pending
801    }
802
803    /// The provider-switch leg with the losing provider, once the AKM-PV is sent (not visible
804    /// to the service provider).
805    #[must_use]
806    pub const fn pv(&self) -> Option<&PvLeg> {
807        self.core.pv.as_ref()
808    }
809
810    /// Every accepted event, in order.
811    #[must_use]
812    pub fn history(&self) -> &[Event] {
813        &self.history
814    }
815
816    /// Whether a KDLE for this order's line aborts this order: an open order of any business
817    /// case but EST, DIAG and KUE-LE (S/PRI 4.4 §5.2.2.2, §5.5.1.4). The caller applies it.
818    #[must_use]
819    pub const fn is_aborted_by_kdle(&self) -> bool {
820        !matches!(
821            self.fall,
822            GeschaeftsfallCode::Est | GeschaeftsfallCode::Get | GeschaeftsfallCode::Set | GeschaeftsfallCode::KueLe
823        ) && (self.core.state.is_open() || matches!(self.core.state, State::Sent))
824    }
825
826    /// Applies `message`, sent or received by the owner at `at`.
827    ///
828    /// # Errors
829    ///
830    /// [`Refusal`] naming the message type and the rule; the process is unchanged.
831    pub fn apply(&mut self, direction: Direction, at: Timestamp, message: impl Into<Message>) -> Result<(), Refusal> {
832        let message = message.into();
833        let before = self.core.clone();
834        let before_awaiting = self.awaiting.clone();
835        let result = match &message {
836            Message::Auftrag(a) => self.auftrag(a, direction, at),
837            Message::Meldung(m) => self.meldung(m, direction, at),
838            Message::Teq(t) => self.teq(t, direction),
839        };
840        match result {
841            Ok(Accepted { sender, hop }) => {
842                if let Some((to, item, attachment)) = hop {
843                    // The receiver answering proves delivery of what was sent to it before
844                    // (S/PRI 4.4 §11.2.3.3).
845                    self.awaiting.retain(|w| w.to != sender);
846                    if self.core.undelivered.as_ref().is_some_and(|u| u.from == sender) {
847                        self.core.undelivered = None;
848                    }
849                    self.awaiting.push(Awaiting { from: sender, to, at, attachment, item, before: Box::new(before) });
850                }
851                self.history.push(Event { at, direction, sender, message });
852                Ok(())
853            }
854            Err(e) => {
855                self.core = before;
856                self.awaiting = before_awaiting;
857                Err(e)
858            }
859        }
860    }
861
862    fn check_direction(&self, direction: Direction, from: Role, to: Role, what: &str) -> Result<(), Refusal> {
863        match direction {
864            Direction::Sent if self.role != from => refuse(format!("{what} is sent by the {from}")),
865            Direction::Received if self.role != to => refuse(format!("{what} is addressed to the {to}")),
866            _ => Ok(()),
867        }
868    }
869
870    fn auftrag(&mut self, a: &Auftrag, direction: Direction, at: Timestamp) -> Result<Accepted, Refusal> {
871        self.check_direction(direction, Role::Auftraggeber, Role::Leistungserbringer, "an order")?;
872        if a.externe_auftragsnummer != self.ext {
873            return refuse("an order with another order number starts its own process (S/PRI 4.4 §11.4)");
874        }
875        if a.geschaeftsfall.code() != self.fall {
876            return refuse("a Storno or Terminverschiebung keeps the business case of the order (S/PRI 4.4 §5.1.3)");
877        }
878        let attachment = order_has_attachment(&a.geschaeftsfall);
879        let item = match a.aenderungskennzeichen {
880            Aenderungskennzeichen::Standard => {
881                self.resend_or_reklamation(a)?;
882                Item::Order
883            }
884            Aenderungskennzeichen::Storno => {
885                self.check_storno(at)?;
886                self.core.pending.push(Pending::Storno { since: at });
887                Item::Storno
888            }
889            Aenderungskennzeichen::Terminverschiebung => {
890                let termin = a.termin_neu.or_else(|| wunschtermin_of(&a.geschaeftsfall));
891                self.check_tv(at, termin)?;
892                if self.core.state == State::Accepted {
893                    // Before the ABM a TV just replaces the requested date (AH 2.9.5 §3.4).
894                    self.core.wunschtermin = termin;
895                }
896                self.core.pending.push(Pending::Terminverschiebung { since: at, termin });
897                Item::Tv
898            }
899        };
900        Ok(Accepted { sender: Role::Auftraggeber, hop: Some((Role::Leistungserbringer, item, attachment)) })
901    }
902
903    fn resend_or_reklamation(&mut self, a: &Auftrag) -> Result<(), Refusal> {
904        match (&self.core.state, &a.geschaeftsfall) {
905            (State::Rejected { .. }, _) => {
906                // Not delivered: the same order number is sent again (Anl. 7 EPK V.13 p.10).
907                self.core.state = State::Sent;
908                self.core.wunschtermin = wunschtermin_of(&a.geschaeftsfall);
909                Ok(())
910            }
911            (State::Completed { .. } | State::Closed, Geschaeftsfall::Est(e)) if e.reklamation.is_some() => {
912                if let (Some(known), Some(r)) = (&self.core.stoerungs_nr, &e.reklamation)
913                    && *known != r.stoerungs_nr_leistungserbringer
914                {
915                    return refuse(
916                        "an EST Reklamation names the network owner's ticket of the repair (S/PRI 4.4 §6.1.5)",
917                    );
918                }
919                let stoerungs_nr = self.core.stoerungs_nr.take();
920                self.core = Core::new(State::Sent);
921                self.core.stoerungs_nr = stoerungs_nr;
922                self.core.wunschtermin = Some(e.wunschtermin.datum);
923                Ok(())
924            }
925            (State::Completed { .. } | State::Closed, Geschaeftsfall::Est(_)) => refuse(
926                "after a repair the same order number returns only as a Reklamation (Anl. 7 EPK V.13 p.8; S/PRI 4.4 §6.1.5)",
927            ),
928            _ => refuse("the order was already sent; a repeated order is refused (S/PRI 4.4 §11.4)"),
929        }
930    }
931
932    fn has_pending(&self, storno: bool) -> bool {
933        self.core.pending.iter().any(|p| p.is_storno() == storno)
934    }
935
936    fn take_pending(&mut self, storno: bool) -> bool {
937        let before = self.core.pending.len();
938        self.core.pending.retain(|p| p.is_storno() != storno);
939        self.core.pending.len() != before
940    }
941
942    /// The Storno rules (Anl. 7 EPK V.13 p.11; AH 2.9.5 §3.5).
943    fn check_storno(&self, at: Timestamp) -> Result<(), Refusal> {
944        if !has_storno(self.fall) {
945            return refuse_with(Meldungscode::C1007, "no Storno in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
946        }
947        if !self.core.state.is_after_qeb() {
948            return refuse_with(
949                Meldungscode::C1087,
950                "a Storno is sent after the QEB and before the ERLM (AH 2.9.5 §3.5)",
951            );
952        }
953        if self.has_pending(true) {
954            return refuse_with(Meldungscode::C1086, "a Storno is already open (Anl. 7 EPK V.13 p.11)");
955        }
956        if let State::Confirmed { liefertermin } = self.core.state {
957            let latest = deadline::storno_latest(liefertermin);
958            if latest.is_overdue(at) {
959                return refuse_with(Meldungscode::C1087, format!("Storno too late: {}", latest.rule.text));
960            }
961        }
962        Ok(())
963    }
964
965    /// The Terminverschiebung rules (Anl. 7 EPK V.13 p.12; AH 2.9.5 §3.4, §3.4.1).
966    fn check_tv(&self, at: Timestamp, termin: Option<Date>) -> Result<(), Refusal> {
967        if !has_tv(self.fall) {
968            return refuse_with(
969                Meldungscode::C1007,
970                "no Terminverschiebung in AEN-LMAE, EST, DIAG and KUE-LE (S/PRI 4.4 §5.3.1.3, §6.1.3; Anl. 7 EPK V.13 p.9)",
971            );
972        }
973        if !self.core.state.is_after_qeb() {
974            return refuse_with(
975                Meldungscode::C1085,
976                "a Terminverschiebung is sent after the QEB and before the ERLM (AH 2.9.5 §3.4)",
977            );
978        }
979        if self.has_pending(false) {
980            return refuse_with(Meldungscode::C1085, "a Terminverschiebung is already open (Anl. 7 EPK V.13 p.12)");
981        }
982        if self.core.konnektivitaet && !self.core.abm_seen {
983            return refuse_with(
984                Meldungscode::C1085,
985                "no Terminverschiebung before the first ABM of a Konnektivität order (AH 2.9.5 §3.4.1; S/PRI 4.4 §5.1.4)",
986            );
987        }
988        let current = self.core.liefertermin.or(self.core.wunschtermin);
989        if let (Some(new), Some(old)) = (termin, current) {
990            if new == old {
991                return refuse_with(Meldungscode::C1085, "a Terminverschiebung names a new date (S/PRI 4.4 §5.1.4)");
992            }
993            if self.fall == GeschaeftsfallCode::Pv && new < old {
994                return refuse_with(
995                    Meldungscode::C1085,
996                    "in PV the date cannot move earlier after the positive pre-agreement (AH 2.9.5 §3.4)",
997                );
998            }
999        }
1000        if let State::Confirmed { liefertermin } = self.core.state {
1001            let latest = deadline::terminverschiebung_latest(liefertermin);
1002            if latest.is_overdue(at) {
1003                return refuse_with(Meldungscode::C1085, format!("Terminverschiebung too late: {}", latest.rule.text));
1004            }
1005        }
1006        Ok(())
1007    }
1008
1009    /// Which open request a message of the network owner answers: by its Änderungskennzeichen,
1010    /// else by its code. `Some(true)` is the Storno, `Some(false)` the TV.
1011    fn answers(&self, m: &Meldung) -> Option<bool> {
1012        match m.auftragstyp.aenderungskennzeichen {
1013            Aenderungskennzeichen::Storno => return Some(true),
1014            Aenderungskennzeichen::Terminverschiebung => return Some(false),
1015            Aenderungskennzeichen::Standard => {}
1016        }
1017        match &m.inhalt {
1018            Meldungsinhalt::Abbm(_) => {
1019                if has_code(&m.inhalt, &["1086", "1087"]) {
1020                    Some(true)
1021                } else if has_code(&m.inhalt, &["1085", "7523"])
1022                    || (self.has_pending(false) && has_code(&m.inhalt, &["7522", "7524"]))
1023                {
1024                    Some(false)
1025                } else if has_code(&m.inhalt, &["1007"]) && self.core.pending.len() == 1 {
1026                    self.core.pending.first().map(Pending::is_storno)
1027                } else {
1028                    None
1029                }
1030            }
1031            Meldungsinhalt::Erlm(_) if has_code(&m.inhalt, &["0012"]) => Some(true),
1032            _ => None,
1033        }
1034    }
1035
1036    fn meldung(&mut self, m: &Meldung, direction: Direction, at: Timestamp) -> Result<Accepted, Refusal> {
1037        let typ = m.typ();
1038        let (from, to) = (sender_of(typ), receiver_of(typ));
1039        self.check_direction(direction, from, to, &format!("a {typ}"))?;
1040        if m.auftragstyp.geschaeftsfall != self.fall {
1041            return refuse(format!("a {typ} of another business case"));
1042        }
1043        let ext = m.externe_auftragsnummer();
1044        if is_leg(typ) {
1045            if self.core.pv_ext.as_ref().is_some_and(|e| e != ext) {
1046                return refuse(format!("a {typ} refers to another provider switch"));
1047            }
1048            self.leg(m, typ, at)?;
1049        } else {
1050            if *ext != self.ext {
1051                return refuse(format!("a {typ} refers to another order number"));
1052            }
1053            if self.core.state.is_terminal() {
1054                return refuse(format!("no {typ} after the order has ended (S/PRI 4.4 §8.2.4, §8.2.5)"));
1055            }
1056            match self.core.state {
1057                State::Rejected { .. } => {
1058                    return refuse(format!("no {typ}: the order was not delivered (Anl. 7 EPK V.13 p.10)"));
1059                }
1060                State::Sent if from == Role::Leistungserbringer => self.core.state = State::Received,
1061                _ => {}
1062            }
1063            self.order_meldung(m, typ, at)?;
1064        }
1065        Ok(Accepted { sender: from, hop: Some((to, Item::Meldung(typ), meldung_has_attachment(&m.inhalt))) })
1066    }
1067
1068    #[allow(clippy::too_many_lines)] // one transition table
1069    fn order_meldung(&mut self, m: &Meldung, typ: Meldungstyp, at: Timestamp) -> Result<(), Refusal> {
1070        use GeschaeftsfallCode as G;
1071        let fall = self.fall;
1072        let state = self.core.state.clone();
1073        let diag = matches!(fall, G::Get | G::Set);
1074        match &m.inhalt {
1075            Meldungsinhalt::Qeb(q) => {
1076                if diag || fall == G::KueLe {
1077                    return refuse("no QEB in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
1078                }
1079                if state != State::Received {
1080                    return refuse("a QEB is the first message, once, before the ABM (S/PRI 4.4 §8.2.1, §8.2.2)");
1081                }
1082                self.core.state = State::Accepted;
1083                self.core.stoerungs_nr.clone_from(&q.stoerungs_nr_leistungserbringer);
1084            }
1085            Meldungsinhalt::Vzm(_) => {
1086                if diag || fall == G::KueLe {
1087                    return refuse("no VZM in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
1088                }
1089                match self.answers(m) {
1090                    Some(true) if fall == G::Est => {
1091                        return refuse("no VZM to a Storno in EST (Anl. 7 EPK V.13 p.11)");
1092                    }
1093                    Some(storno) if !self.has_pending(storno) => {
1094                        return refuse(
1095                            "a VZM to a Storno or Terminverschiebung needs one open (Anl. 7 EPK V.13 p.11, p.12)",
1096                        );
1097                    }
1098                    None if !state.is_open() => {
1099                        return refuse("a VZM comes between the receipt and the ERLM (S/PRI 4.4 §8.2.6)");
1100                    }
1101                    _ => {}
1102                }
1103            }
1104            Meldungsinhalt::Abm(a) => self.abm(m, a, &state)?,
1105            Meldungsinhalt::Abbm(_) => self.abbm(m, &state, at)?,
1106            Meldungsinhalt::Erlm(e) => {
1107                if self.answers(m) == Some(false) {
1108                    return refuse("a Terminverschiebung is not answered with an ERLM (Anl. 7 EPK V.13 p.12)");
1109                }
1110                if self.answers(m) == Some(true) {
1111                    if !self.take_pending(true) {
1112                        return refuse("an ERLM to a Storno needs an open Storno (Anl. 7 EPK V.13 p.11)");
1113                    }
1114                    self.core.pending.clear();
1115                    self.core.state = State::Cancelled;
1116                    return Ok(());
1117                }
1118                let allowed = match fall {
1119                    G::Get | G::Set => state == State::Received,
1120                    G::KueLe => matches!(state, State::Confirmed { .. }),
1121                    G::Est => state == State::Accepted,
1122                    _ => matches!(state, State::Confirmed { .. } | State::ErlmKCheck),
1123                };
1124                if !allowed {
1125                    return refuse(match fall {
1126                        G::Get | G::Set => "a DIAG ends with ERLM or ABBM after the receipt (Anl. 7 EPK V.13 p.9)",
1127                        G::Est => "an EST is completed after the QEB, outside a TAM (Anl. 7 EPK V.13 p.8)",
1128                        _ => {
1129                            "an ERLM follows the ABM, or the check of an ERLM-K (Anl. 7 EPK V.13 p.1, p.3, p.5–7; S/PRI 4.4 §8.2.3)"
1130                        }
1131                    });
1132                }
1133                if self.core.konnektivitaet && !self.core.activated {
1134                    return refuse(
1135                        "a Konnektivität order completes after the activation ABM with a real LineID (Anl. 7 EPK V.13 p.2; S/PRI 4.4 §5.1.6)",
1136                    );
1137                }
1138                self.core.pending.clear();
1139                self.core.state =
1140                    if diag { State::Closed } else { State::Completed { erledigungstermin: e.erledigungstermin } };
1141            }
1142            Meldungsinhalt::Entm(_) => {
1143                if diag {
1144                    return refuse("no ENTM in DIAG (Anl. 7 EPK V.13 p.9)");
1145                }
1146                if !matches!(state, State::Completed { .. } | State::Cancelled) {
1147                    return refuse("an ENTM follows the ERLM (S/PRI 4.4 §8.2.3, §8.2.4)");
1148                }
1149                self.core.state = State::Closed;
1150            }
1151            Meldungsinhalt::Tam(_) => {
1152                let ok = match fall {
1153                    G::Est => state == State::Accepted,
1154                    f if has_tam_loop(f) => matches!(state, State::Confirmed { .. } | State::ErlmKCheck),
1155                    _ => false,
1156                };
1157                if !ok {
1158                    return refuse(
1159                        "a TAM comes after the ABM (EST: after the QEB) in NEU, LAE, PV and EST (S/PRI 4.4 §8.2.7; AH 2.9.5 §3.6)",
1160                    );
1161                }
1162                self.core.state = State::TamOpen { since: at };
1163            }
1164            Meldungsinhalt::Mtam(_) => {
1165                if !has_tam_loop(fall) || !matches!(state, State::TamOpen { .. }) {
1166                    return refuse("an MTAM follows an unanswered TAM in NEU, LAE and PV (AH 2.9.5 §3.6)");
1167                }
1168                self.core.state = State::MtamOpen { since: at };
1169            }
1170            Meldungsinhalt::ErlmK(_) => {
1171                let ok = has_tam_loop(fall)
1172                    && (matches!(state, State::TamOpen { .. } | State::MtamOpen { .. })
1173                        || (fall == G::Pv && matches!(state, State::Confirmed { .. })));
1174                if !ok {
1175                    return refuse(
1176                        "an ERLM-K answers a TAM or MTAM in NEU, LAE and PV, in PV also after the ABM (AH 2.9.5 §3.6; Anl. 7 EPK V.13 p.7)",
1177                    );
1178                }
1179                self.core.state = State::ErlmKCheck;
1180            }
1181            Meldungsinhalt::TbkLe(_) => {
1182                if fall != G::Est || state != State::Accepted {
1183                    return refuse("a TBK-LE comes in an EST after the QEB (Anl. 7 EPK V.13 p.8)");
1184                }
1185            }
1186            Meldungsinhalt::TbkAg(_) => {
1187                if fall != G::Est || !matches!(state, State::TamOpen { .. }) {
1188                    return refuse("a TBK-AG answers the TAM of an EST (Anl. 7 EPK V.13 p.8)");
1189                }
1190                self.core.state = State::Accepted;
1191            }
1192            Meldungsinhalt::ZwmLe(_) | Meldungsinhalt::ZwmAg(_) => {
1193                if !matches!(fall, G::Neu | G::Est) || !state.is_after_qeb() {
1194                    return refuse(format!(
1195                        "a {typ} comes between the QEB and the ERLM in NEU and EST (S/PRI 4.4 §8.2.9, §8.3.1; Anl. 7 EPK V.13 p.1, p.8)"
1196                    ));
1197                }
1198            }
1199            Meldungsinhalt::Kdle(_) => {
1200                return refuse("a KDLE starts its own process (Anl. 7 EPK V.13 p.4)");
1201            }
1202            Meldungsinhalt::AkmPv(_)
1203            | Meldungsinhalt::RuemPv(_)
1204            | Meldungsinhalt::AbmPv(_)
1205            | Meldungsinhalt::ErlmPv(_)
1206            | Meldungsinhalt::EntmPv(_)
1207            | Meldungsinhalt::AbbmPv(_) => {}
1208        }
1209        Ok(())
1210    }
1211
1212    fn abm(&mut self, m: &Meldung, a: &crate::Abm, state: &State) -> Result<(), Refusal> {
1213        use GeschaeftsfallCode as G;
1214        let fall = self.fall;
1215        if matches!(fall, G::Est | G::Get | G::Set | G::KueLe) {
1216            return refuse("no ABM in EST, DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.8, p.9)");
1217        }
1218        if m.auftragstyp.aenderungskennzeichen != Aenderungskennzeichen::Standard {
1219            return refuse("an ABM carries the Änderungskennzeichen Standard, also after a TV (AH 2.9.5 §3.4)");
1220        }
1221        let tv_open = self.has_pending(false);
1222        match state {
1223            State::Accepted => {
1224                if self.role == Role::Leistungserbringer
1225                    && fall == G::Pv
1226                    && !matches!(self.core.pv, Some(PvLeg::Agreed | PvLeg::Confirmed { .. }))
1227                {
1228                    return refuse("in PV the ABM follows a positive RUEM-PV (Anl. 7 EPK V.13 p.7)");
1229                }
1230            }
1231            State::Confirmed { .. } | State::TamOpen { .. } | State::MtamOpen { .. } | State::ErlmKCheck => {
1232                let repeat = m.codes().iter().any(|c| {
1233                    ["6012", "8500", "8501", "8502"].contains(&c.as_str()) && c.applies(Meldungstyp::Abm, fall)
1234                });
1235                if !repeat && !tv_open {
1236                    return refuse(
1237                        "a repeated ABM carries 6012 or 8500–8502 or confirms a Terminverschiebung (Anl. 7 EPK V.13 p.1, p.3, p.6, p.7, p.12)",
1238                    );
1239                }
1240            }
1241            State::Received => return refuse("the QEB comes before the ABM (S/PRI 4.4 §8.2.2)"),
1242            _ => return refuse("an ABM comes after the QEB and before the ERLM (S/PRI 4.4 §8.2.2, §8.2.3)"),
1243        }
1244        let dummy = is_dummy(&a.anschluss.line_id);
1245        if fall == G::Neu && !self.core.abm_seen && dummy {
1246            self.core.konnektivitaet = true;
1247        }
1248        if self.core.konnektivitaet && !dummy {
1249            self.core.activated = true;
1250        }
1251        self.take_pending(false);
1252        self.core.abm_seen = true;
1253        let date = a.verbindlicher_liefertermin.datum;
1254        self.core.liefertermin = Some(date);
1255        self.core.state = State::Confirmed { liefertermin: date };
1256        if self.role == Role::Leistungserbringer && self.core.pv.is_some() {
1257            self.core.abm_pv_owed = true;
1258        }
1259        Ok(())
1260    }
1261
1262    fn abbm(&mut self, m: &Meldung, state: &State, at: Timestamp) -> Result<(), Refusal> {
1263        use GeschaeftsfallCode as G;
1264        let fall = self.fall;
1265        if fall == G::KueLe {
1266            return refuse("no ABBM in KUE-LE (Anl. 7 EPK V.13 p.4)");
1267        }
1268        if let Some(storno) = self.answers(m) {
1269            if !self.take_pending(storno) {
1270                return refuse("an ABBM to a Storno or Terminverschiebung needs one open (Anl. 7 EPK V.13 p.11, p.12)");
1271            }
1272            return Ok(());
1273        }
1274        if !state.is_open() {
1275            return refuse("an ABBM comes between the receipt and the ERLM (S/PRI 4.4 §8.2.5)");
1276        }
1277        let le = self.role == Role::Leistungserbringer;
1278        if has_code(&m.inhalt, &["1198"]) && !matches!(state, State::MtamOpen { .. }) {
1279            return refuse("ABBM 1198 follows an unanswered MTAM (AH 2.9.5 §3.6)");
1280        }
1281        if has_code(&m.inhalt, &["7015"]) && !(fall == G::Est && matches!(state, State::TamOpen { .. })) {
1282            return refuse("ABBM 7015 follows an unanswered TAM of an EST (Anl. 7 EPK V.13 p.8)");
1283        }
1284        if has_code(&m.inhalt, &["0041"]) {
1285            let ok = if le {
1286                matches!(self.core.pv, Some(PvLeg::Refused { .. } | PvLeg::Aborted { answer: PvAnswer::Negative }))
1287            } else {
1288                fall == G::Pv && *state == State::Accepted
1289            };
1290            if !ok {
1291                return refuse("ABBM 0041 follows a negative RUEM-PV (Anl. 7 EPK V.13 p.7)");
1292            }
1293        }
1294        if has_code(&m.inhalt, &["0042"]) {
1295            let ok = if le {
1296                match &self.core.pv {
1297                    Some(PvLeg::AwaitRuem { antwortfrist }) => {
1298                        let missed = deadline::ruem_pv(*antwortfrist).is_overdue(at);
1299                        if missed {
1300                            self.core.pv = Some(PvLeg::Missed);
1301                        }
1302                        missed
1303                    }
1304                    Some(PvLeg::Missed | PvLeg::Aborted { answer: PvAnswer::Missing }) => true,
1305                    _ => false,
1306                }
1307            } else {
1308                fall == G::Pv && *state == State::Accepted
1309            };
1310            if !ok {
1311                return refuse("ABBM 0042 follows the antwortfrist of the AKM-PV without RUEM-PV (S/PRI 4.4 §5.5.1.1)");
1312            }
1313        }
1314        let code = m.codes().first().map_or_else(|| Meldungscode::parse(""), |c| (*c).clone());
1315        self.core.pending.clear();
1316        self.core.state = State::Aborted { code };
1317        Ok(())
1318    }
1319
1320    #[allow(clippy::too_many_lines)] // one transition table
1321    fn leg(&mut self, m: &Meldung, typ: Meldungstyp, at: Timestamp) -> Result<(), Refusal> {
1322        if self.fall != GeschaeftsfallCode::Pv {
1323            return refuse(format!("a {typ} belongs to a provider switch (Anl. 7 EPK V.13 p.7)"));
1324        }
1325        let le = self.role == Role::Leistungserbringer;
1326        let ekp_ab = self.role == Role::AbgebenderProvider;
1327        let leg = self.core.pv.clone();
1328        match &m.inhalt {
1329            Meldungsinhalt::AkmPv(a) => {
1330                if leg.is_some() {
1331                    return refuse("one AKM-PV per order; no new AKM-PV on a TV (S/PRI 4.4 §5.5.1.3)");
1332                }
1333                if self.core.state != State::Accepted {
1334                    return refuse("the AKM-PV follows the QEB, before the ABM (Anl. 7 EPK V.13 p.7)");
1335                }
1336                self.core.pv = Some(PvLeg::AwaitRuem { antwortfrist: a.aufnehmender_provider.antwortfrist });
1337                self.core.pv_ext = Some(a.externe_auftragsnummer.clone());
1338            }
1339            Meldungsinhalt::RuemPv(r) => {
1340                let Some(PvLeg::AwaitRuem { antwortfrist }) = leg else {
1341                    return refuse("a RUEM-PV answers the AKM-PV, once (Anl. 7 EPK V.13 p.7)");
1342                };
1343                if deadline::ruem_pv(antwortfrist).is_overdue(at) {
1344                    return refuse(
1345                        "a RUEM-PV after the antwortfrist comes too late: the network owner aborts (S/PRI 4.4 §5.5.1.1)",
1346                    );
1347                }
1348                if le && !self.core.state.is_open() {
1349                    return refuse(
1350                        "after the order ended the losing provider's messages are discarded (S/PRI 4.4 §5.5.1.2)",
1351                    );
1352                }
1353                self.core.pv = Some(if ruem_negative(r) {
1354                    PvLeg::Refused { antwortcode: r.abgebender_provider.antwortcode.clone() }
1355                } else {
1356                    PvLeg::Agreed
1357                });
1358            }
1359            Meldungsinhalt::AbmPv(a) => {
1360                if !matches!(leg, Some(PvLeg::Agreed | PvLeg::Confirmed { .. })) {
1361                    return refuse("an ABM-PV follows a positive RUEM-PV (Anl. 7 EPK V.13 p.7)");
1362                }
1363                if le && !self.core.abm_pv_owed {
1364                    return refuse("an ABM-PV is sent together with an ABM (S/PRI 4.4 §8.2.13)");
1365                }
1366                self.core.abm_pv_owed = false;
1367                let uebernahmedatum = a.aufnehmender_provider.uebernahmedatum_verbindlich;
1368                self.core.pv = Some(PvLeg::Confirmed { uebernahmedatum });
1369                if ekp_ab {
1370                    self.core.liefertermin = Some(uebernahmedatum);
1371                    self.core.state = State::Confirmed { liefertermin: uebernahmedatum };
1372                }
1373            }
1374            Meldungsinhalt::ErlmPv(e) => {
1375                if !matches!(leg, Some(PvLeg::Confirmed { .. })) {
1376                    return refuse("an ERLM-PV follows the ABM-PV (Anl. 7 EPK V.13 p.7)");
1377                }
1378                if le && !matches!(self.core.state, State::Completed { .. } | State::Closed) {
1379                    return refuse("an ERLM-PV is sent together with the ERLM (Anl. 7 EPK V.13 p.7)");
1380                }
1381                self.core.pv = Some(PvLeg::Completed);
1382                if ekp_ab {
1383                    self.core.state = State::Completed { erledigungstermin: e.erledigungstermin };
1384                }
1385            }
1386            Meldungsinhalt::EntmPv(_) => {
1387                if leg != Some(PvLeg::Completed) {
1388                    return refuse("an ENTM-PV follows the ERLM-PV (Anl. 7 EPK V.13 p.7)");
1389                }
1390                self.core.pv = Some(PvLeg::Closed);
1391                if ekp_ab {
1392                    self.core.state = State::Closed;
1393                }
1394            }
1395            Meldungsinhalt::AbbmPv(_) => {
1396                let Some(open) = leg.filter(PvLeg::is_open) else {
1397                    return refuse("an ABBM-PV ends an open provider-switch leg after the AKM-PV (S/PRI 4.4 §5.5.1.2)");
1398                };
1399                let answer = match &open {
1400                    PvLeg::Refused { .. } => PvAnswer::Negative,
1401                    PvLeg::AwaitRuem { .. } | PvLeg::Missed => PvAnswer::Missing,
1402                    _ => PvAnswer::Positive,
1403                };
1404                if le {
1405                    let ok = match &open {
1406                        PvLeg::Refused { .. } | PvLeg::Missed => true,
1407                        PvLeg::AwaitRuem { antwortfrist } => {
1408                            deadline::ruem_pv(*antwortfrist).is_overdue(at) || self.ended_without_switch()
1409                        }
1410                        PvLeg::Agreed | PvLeg::Confirmed { .. } => self.ended_without_switch(),
1411                        _ => false,
1412                    };
1413                    if !ok {
1414                        return refuse(
1415                            "an ABBM-PV follows the end of the order without switch: ABBM, Storno, negative or missing RUEM-PV (Anl. 7 EPK V.13 p.7)",
1416                        );
1417                    }
1418                }
1419                self.core.pv = Some(PvLeg::Aborted { answer });
1420                if ekp_ab {
1421                    let code = m.codes().first().map_or_else(|| Meldungscode::parse(""), |c| (*c).clone());
1422                    self.core.state = State::Aborted { code };
1423                }
1424            }
1425            _ => {}
1426        }
1427        Ok(())
1428    }
1429
1430    const fn ended_without_switch(&self) -> bool {
1431        matches!(self.core.state, State::Aborted { .. } | State::Cancelled)
1432    }
1433
1434    fn teq(&mut self, t: &Teq, direction: Direction) -> Result<Accepted, Refusal> {
1435        let role = self.role;
1436        let pos = match direction {
1437            Direction::Sent => self.awaiting.iter().position(|w| w.to == role),
1438            Direction::Received => self.awaiting.iter().position(|w| w.from == role),
1439        };
1440        let Some(pos) = pos else {
1441            return refuse("a TEQ acknowledges an order or message awaiting one (Anl. 7 EPK V.13 p.10)");
1442        };
1443        let Some(item) = self.awaiting.get(pos).cloned() else {
1444            return refuse("a TEQ acknowledges an order or message awaiting one (Anl. 7 EPK V.13 p.10)");
1445        };
1446        let leg = matches!(item.item, Item::Meldung(typ) if is_leg(typ));
1447        let expected = if leg { self.core.pv_ext.as_ref().unwrap_or(&self.ext) } else { &self.ext };
1448        if t.externe_auftragsnummer.as_ref().is_some_and(|e| e != expected) {
1449            return refuse("a TEQ refers to another order number");
1450        }
1451        if t.is_ok() && item.item == Item::Order && self.core.state == State::Sent {
1452            self.core.state = State::Received;
1453        }
1454        if t.is_ok() || item.from == Role::Leistungserbringer {
1455            // A negative receipt to a message of the network owner is only a hint: it counts as
1456            // delivered (S/PRI 4.4 §11.2.3.2; AH 2.9.5 §2.6).
1457            self.awaiting.remove(pos);
1458        } else {
1459            // Not delivered: undo it and everything after it (Anl. 7 EPK V.13 p.10).
1460            let code = t
1461                .positionen
1462                .iter()
1463                .find(|p| !p.code.is_ok())
1464                .map_or(Meldungscode::TECHNISCHER_FEHLER, |p| p.code.clone());
1465            self.core = *item.before;
1466            self.awaiting.truncate(pos);
1467            if item.item == Item::Order && matches!(self.core.state, State::Sent | State::Rejected { .. }) {
1468                self.core.state = State::Rejected { code: code.clone() };
1469            }
1470            self.core.undelivered = Some(Undelivered { from: item.from, code });
1471        }
1472        Ok(Accepted { sender: item.to, hop: None })
1473    }
1474
1475    /// What `role` may do next.
1476    #[must_use]
1477    #[allow(clippy::too_many_lines)] // one table per role
1478    pub fn next_actions(&self, role: Role) -> Vec<Action> {
1479        use GeschaeftsfallCode as G;
1480        use Meldungstyp as T;
1481        let mut out = Vec::new();
1482        if self.awaiting.iter().any(|w| w.to == role) {
1483            out.push(Action::Acknowledge);
1484        }
1485        if let Some(u) = &self.core.undelivered
1486            && u.from == role
1487        {
1488            out.push(if u.code == Meldungscode::UEBERLASTET { Action::Resend } else { Action::Correct });
1489        }
1490        let fall = self.fall;
1491        let state = &self.core.state;
1492        let pv = self.core.pv.as_ref();
1493        match role {
1494            Role::Auftraggeber => {
1495                if state.is_after_qeb() {
1496                    if has_storno(fall) && !self.has_pending(true) {
1497                        out.push(Action::Storno);
1498                    }
1499                    if has_tv(fall) && !self.has_pending(false) && (!self.core.konnektivitaet || self.core.abm_seen) {
1500                        out.push(Action::Terminverschiebung);
1501                    }
1502                    if matches!(fall, G::Neu | G::Est) {
1503                        out.push(Action::Send(T::ZwmAg));
1504                    }
1505                }
1506                match state {
1507                    State::TamOpen { .. } | State::MtamOpen { .. } if has_tam_loop(fall) => {
1508                        out.push(Action::Send(T::ErlmK));
1509                    }
1510                    State::Confirmed { .. } if fall == G::Pv => out.push(Action::Send(T::ErlmK)),
1511                    State::TamOpen { .. } if fall == G::Est => out.push(Action::Send(T::TbkAg)),
1512                    State::Completed { .. } | State::Closed if fall == G::Est => out.push(Action::Reklamation),
1513                    _ => {}
1514                }
1515            }
1516            Role::Leistungserbringer => {
1517                for p in &self.core.pending {
1518                    out.push(if p.is_storno() { Action::AnswerStorno } else { Action::AnswerTerminverschiebung });
1519                }
1520                match state {
1521                    State::Received if matches!(fall, G::Get | G::Set) => {
1522                        out.extend([Action::Send(T::Erlm), Action::Send(T::Abbm)]);
1523                    }
1524                    State::Received => out.extend([Action::Send(T::Qeb), Action::Send(T::Vzm), Action::Send(T::Abbm)]),
1525                    State::Accepted if fall == G::Est => out.extend([
1526                        Action::Send(T::Erlm),
1527                        Action::Send(T::Tam),
1528                        Action::Send(T::TbkLe),
1529                        Action::Send(T::ZwmLe),
1530                        Action::Send(T::Vzm),
1531                        Action::Send(T::Abbm),
1532                    ]),
1533                    State::Accepted if fall == G::Pv => match pv {
1534                        None => out.push(Action::Send(T::AkmPv)),
1535                        Some(PvLeg::Agreed) => out.extend([Action::Send(T::Abm), Action::Send(T::Abbm)]),
1536                        Some(PvLeg::Refused { .. }) => out.push(Action::Abort(Meldungscode::C0041)),
1537                        Some(PvLeg::Missed) => out.push(Action::Abort(Meldungscode::C0042)),
1538                        _ => {}
1539                    },
1540                    State::Accepted => out.extend([Action::Send(T::Abm), Action::Send(T::Vzm), Action::Send(T::Abbm)]),
1541                    State::Confirmed { .. } if fall == G::KueLe => out.push(Action::Send(T::Erlm)),
1542                    State::Confirmed { .. } | State::ErlmKCheck => {
1543                        if !self.core.konnektivitaet || self.core.activated {
1544                            out.push(Action::Send(T::Erlm));
1545                        }
1546                        if has_tam_loop(fall) {
1547                            out.push(Action::Send(T::Tam));
1548                        }
1549                        out.extend([Action::Send(T::Vzm), Action::Send(T::Abbm)]);
1550                    }
1551                    State::TamOpen { .. } if fall == G::Est => out.push(Action::Abort(Meldungscode::C7015)),
1552                    State::TamOpen { .. } => out.push(Action::Send(T::Mtam)),
1553                    State::MtamOpen { .. } => out.push(Action::Abort(Meldungscode::C1198)),
1554                    State::Completed { .. } | State::Cancelled => out.push(Action::Send(T::Entm)),
1555                    _ => {}
1556                }
1557                if self.core.abm_pv_owed {
1558                    out.push(Action::Send(T::AbmPv));
1559                }
1560                match pv {
1561                    Some(PvLeg::Confirmed { .. }) if matches!(state, State::Completed { .. } | State::Closed) => {
1562                        out.push(Action::Send(T::ErlmPv));
1563                    }
1564                    Some(PvLeg::Completed) => out.push(Action::Send(T::EntmPv)),
1565                    Some(PvLeg::Refused { .. } | PvLeg::Missed) => out.push(Action::Send(T::AbbmPv)),
1566                    Some(l) if l.is_open() && self.ended_without_switch() => out.push(Action::Send(T::AbbmPv)),
1567                    _ => {}
1568                }
1569            }
1570            Role::AbgebenderProvider => {
1571                if matches!(pv, Some(PvLeg::AwaitRuem { .. })) {
1572                    out.push(Action::Send(T::RuemPv));
1573                }
1574            }
1575        }
1576        out
1577    }
1578
1579    /// The deadlines running now: receipts, the Storno and TV windows, the TAM and MTAM
1580    /// answers and the losing provider's answer.
1581    #[must_use]
1582    pub fn deadlines(&self) -> Vec<Deadline> {
1583        let mut out: Vec<Deadline> =
1584            self.awaiting.iter().map(|w| deadline::teq_response(w.at, w.to, w.attachment)).collect();
1585        match &self.core.state {
1586            State::Confirmed { liefertermin } if self.role != Role::AbgebenderProvider => {
1587                if has_storno(self.fall) && !self.has_pending(true) {
1588                    out.push(deadline::storno_latest(*liefertermin));
1589                }
1590                if has_tv(self.fall) && !self.has_pending(false) {
1591                    out.push(deadline::terminverschiebung_latest(*liefertermin));
1592                }
1593            }
1594            State::TamOpen { since } if has_tam_loop(self.fall) => out.push(deadline::mtam_due(*since, &self.calendar)),
1595            State::MtamOpen { since } => out.push(deadline::abbm_1198_due(*since, &self.calendar)),
1596            _ => {}
1597        }
1598        if let Some(PvLeg::AwaitRuem { antwortfrist }) = &self.core.pv {
1599            out.push(deadline::ruem_pv(*antwortfrist));
1600        }
1601        out.sort_by_key(|d| d.due);
1602        out
1603    }
1604
1605    /// The obligations overdue at `now`; the Storno and TV windows are not obligations. An
1606    /// overdue [`deadline::DeadlineKind::RuemPv`] means the network owner owes ABBM `0042` and
1607    /// ABBM-PV `0040`.
1608    #[must_use]
1609    pub fn overdue(&self, now: Timestamp) -> Vec<Deadline> {
1610        self.deadlines().into_iter().filter(|d| !d.is_window() && d.is_overdue(now)).collect()
1611    }
1612}