Skip to main content

telco_interop/
sim.rs

1//! A sandbox: named scenarios that play a whole switch or order from both sides.
2//!
3//! Each [`Szenario`] plays the side you test — the gaining provider (WBCI EKPauf, S/PRI
4//! Auftraggeber), scripted: it sends its requests and orders at set moments and acknowledges
5//! every message it receives two seconds later — against the simulated peers of the other side:
6//! [`wbci::sim::Ekpabg`], [`spri::sim::Leistungserbringer`] and [`spri::sim::AbgebenderProvider`].
7//! The result is an [`Ablauf`]: every request, order, message and receipt of both sides, each a
8//! [`Nachricht`] with its time, interface, sender and receiver, ready to compare with your own
9//! system or to write as files (`telco-interop simulate`).
10//!
11//! The peers are driven by the process state machines, so every message is one the protocol
12//! allows, inside its deadline. A scenario reads no clock: it starts at the instant you give
13//! ([`START`] by default) and derives every date from it with the calendars, so the same start
14//! gives the same bytes. The data is synthetic.
15//!
16//! ```
17//! use telco_interop::sim;
18//!
19//! let szenario = sim::szenario("spri-neu").ok_or("no such scenario")?;
20//! let ablauf = szenario.play(sim::START);
21//! assert!(ablauf.abgelehnt.is_empty());
22//! let kinds: Vec<&str> = ablauf.nachrichten.iter().filter(|n| n.art() != "TEQ").map(|n| n.art()).collect();
23//! assert_eq!(kinds, ["NEU", "QEB", "ABM", "ERLM", "ENTM"]);
24//! println!("{}", ablauf.nachrichten[0]); // Mo 01.03.2027 09:00 S/PRI EKPauf → Netzbetreiber NEU
25//! # Ok::<(), Box<dyn std::error::Error>>(())
26//! ```
27//!
28//! ## The catalogue
29//!
30//! | Name | What it shows | Source |
31//! |---|---|---|
32//! | `wbci-agreed` | VA-KUE-MRN checked against the losing provider's record: TEQ, RUEM-VA 8001, AKM-TR | Anl. 1 V5.4.1 §2.2–§2.6; WBCI 2.0 §12.3 |
33//! | `wbci-refused-rng` | VA-KUE-MRN, the record has another number: ABBM 8103 (RNG) | Anl. 1 V5.4.1 §2.3, §2.4 |
34//! | `wbci-storno` | VA-KUE-ORN agreed, cancelled by the gaining provider (STR-AUF): ERLM 8004 | Anl. 1 V5.4.1 §2.9.1 |
35//! | `wbci-tvs` | VA-KUE-ORN agreed, postponed by the gaining provider (TVS-VA): ERLM 8003 | Anl. 1 V5.4.1 §2.11 |
36//! | `spri-neu` | NEU: TEQ, QEB, ABM, ERLM on the binding date, ENTM | Anl. 7 EPK V.13 p.1, p.10 |
37//! | `spri-neu-tam` | NEU, the appointment fails: TAM, MTAM, ABBM 1198 | Anl. 7 EPK V.13 p.1; AH 2.9.5 §3.6 |
38//! | `spri-storno` | NEU, Storno after the ABM: ERLM 0012, ENTM | Anl. 7 EPK V.13 p.11; AH 2.9.5 §3.5 |
39//! | `spri-storno-refused` | NEU, Storno refused with ABBM 1087; the order completes | Anl. 7 EPK V.13 p.11 |
40//! | `spri-tv` | NEU, Terminverschiebung after the ABM: a new ABM, ERLM on the new date, ENTM | Anl. 7 EPK V.13 p.12; AH 2.9.5 §3.4 |
41//! | `spri-pv` | PV: AKM-PV, RUEM-PV, ABM with ABM-PV, ERLM with ERLM-PV, ENTM with ENTM-PV | Anl. 7 EPK V.13 p.7; S/PRI 4.4 §5.5.1, §8.2.13 |
42//! | `spri-pv-refused` | PV, the losing provider refuses (KVE): ABBM 0041, ABBM-PV 0040 | Anl. 7 EPK V.13 p.7; S/PRI 4.4 §5.5.1.1, §5.5.1.2 |
43//! | `spri-pv-timeout` | PV, no RUEM-PV by the antwortfrist: ABBM 0042, ABBM-PV 0040 | S/PRI 4.4 §5.5.1.1; Anl. 7 EPK V.13 p.7 |
44//! | `wechsel` | the switch across both: VA, RUEM-VA with the LineID, AKM-TR, PV for the switch date, the PV leg, completion on the switch date | S/PRI 4.4 §5.5.1.1 (p. 27); Anl. 1 V5.4.1 §2.6.2; § 59 TKG |
45//!
46//! The S/PRI NEU scenarios carry a Vorabstimmungs-ID: they are the new line of a switching
47//! customer (S/PRI 4.4 §5.5: a switch with NEU, KUE-AG or PV carries it), so a replay finds them
48//! as one switch. [`Nachricht`]'s `Display` carries times, kinds and codes only.
49
50use core::fmt;
51use std::error::Error;
52
53use carrier_core::calendar::berlin;
54use carrier_core::count::{Day, day_of};
55use carrier_core::xml::WriteError;
56use wbci::Timestamp;
57use wbci::sim::SignedDuration;
58
59use crate::{Partei, Schnittstelle};
60
61use spri::process::Role as SRole;
62use spri::sim::{AbgebenderProvider, Leistungserbringer, Rueckmeldung};
63use wbci::sim::{Antwort, Ekpabg};
64
65/// The default start of every scenario: Monday 01.03.2027, 09:00 German time.
66pub const START: Timestamp = Timestamp::constant(1_803_888_000, 0);
67
68/// The most steps a scenario takes; a bound, never reached.
69const MAX_STEPS: usize = 10_000;
70
71/// The scripted side acknowledges a message after this long.
72const ACK: SignedDuration = SignedDuration::from_secs(2);
73
74/// The scripted side acts this long after the message it waited for.
75const PAUSE: SignedDuration = SignedDuration::from_hours(1);
76
77/// A named scenario of the catalogue.
78#[derive(Clone, Copy)]
79pub struct Szenario {
80    /// Its name, e.g. `spri-pv`.
81    pub name: &'static str,
82    /// What it shows, in one line.
83    pub beschreibung: &'static str,
84    /// The chart page or clause it follows.
85    pub quelle: &'static str,
86    play: fn(Timestamp) -> Result<Lauf, Box<dyn Error>>,
87}
88
89impl fmt::Debug for Szenario {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.debug_struct("Szenario").field("name", &self.name).finish_non_exhaustive()
92    }
93}
94
95impl Szenario {
96    /// Plays the scenario from `start`.
97    #[must_use]
98    pub fn play(&self, start: Timestamp) -> Ablauf {
99        match (self.play)(start) {
100            Ok(lauf) => lauf.ablauf(),
101            Err(e) => Ablauf { nachrichten: Vec::new(), abgelehnt: vec![format!("{}: {e}", self.name)] },
102        }
103    }
104}
105
106/// The catalogue, in the order of the table above.
107#[must_use]
108pub fn katalog() -> &'static [Szenario] {
109    KATALOG
110}
111
112/// The scenario called `name`.
113#[must_use]
114pub fn szenario(name: &str) -> Option<&'static Szenario> {
115    KATALOG.iter().find(|s| s.name == name)
116}
117
118/// The payload of a [`Nachricht`].
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum Inhalt {
121    /// A WBCI payload.
122    Wbci(Box<wbci::Payload>),
123    /// An S/PRI payload.
124    Spri(Box<spri::Payload>),
125}
126
127/// One message of a scenario.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Nachricht {
130    /// When it was sent (also its control timestamp).
131    pub at: Timestamp,
132    /// The interface.
133    pub schnittstelle: Schnittstelle,
134    /// Who sent it.
135    pub von: Partei,
136    /// Who received it.
137    pub an: Partei,
138    /// The payload.
139    pub inhalt: Inhalt,
140}
141
142impl Nachricht {
143    /// What it is: `VA-KUE-MRN`, `RUEM-VA`, `PV`, `Storno`, `ABM-PV`, `TEQ`, ….
144    #[must_use]
145    pub fn art(&self) -> &'static str {
146        match &self.inhalt {
147            Inhalt::Wbci(p) => p.kind(),
148            Inhalt::Spri(p) => p.kind(),
149        }
150    }
151
152    /// The codes of its positions, e.g. `8001`.
153    #[must_use]
154    pub fn codes(&self) -> Vec<String> {
155        match &self.inhalt {
156            Inhalt::Wbci(p) => match &**p {
157                wbci::Payload::MeldungRequest { meldung, .. } => {
158                    meldung.codes().map(|c| c.as_str().to_owned()).collect()
159                }
160                wbci::Payload::AnfrageResponse { quittung, .. } | wbci::Payload::MeldungResponse { quittung, .. } => {
161                    quittung.positionen.iter().map(|p| p.code.as_str().to_owned()).collect()
162                }
163                wbci::Payload::AnfrageRequest { .. } => Vec::new(),
164            },
165            Inhalt::Spri(p) => match &**p {
166                spri::Payload::MeldungRequest { meldung, .. } => {
167                    meldung.codes().iter().map(|c| c.as_str().to_owned()).collect()
168                }
169                spri::Payload::AuftragResponse { quittung, .. } | spri::Payload::MeldungResponse { quittung, .. } => {
170                    quittung.positionen.iter().map(|p| p.code.as_str().to_owned()).collect()
171                }
172                spri::Payload::AuftragRequest { .. } => Vec::new(),
173            },
174        }
175    }
176
177    /// The payload as XML.
178    ///
179    /// # Errors
180    ///
181    /// The payload exceeds a schema maximum (never for a scenario's payload).
182    pub fn to_xml(&self) -> Result<String, WriteError> {
183        match &self.inhalt {
184            Inhalt::Wbci(p) => p.to_xml(),
185            Inhalt::Spri(p) => p.to_xml(),
186        }
187    }
188
189    /// Its file name at `position` (1-based, in time order):
190    /// `NNN-<interface>-<sender>-<kind>.xml`, e.g. `001-wbci-ekpauf-va-kue-mrn.xml`.
191    #[must_use]
192    pub fn file_name(&self, position: usize) -> String {
193        let schnittstelle = match self.schnittstelle {
194            Schnittstelle::Wbci => "wbci",
195            Schnittstelle::Spri => "spri",
196        };
197        let art: String =
198            self.art().chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
199        format!("{position:03}-{schnittstelle}-{}-{art}.xml", self.von.to_string().to_ascii_lowercase())
200    }
201}
202
203impl fmt::Display for Nachricht {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        let z = self.at.to_zoned_datetime(berlin());
206        write!(
207            f,
208            "{} {:02}:{:02} {} {} → {} {}",
209            Day(z.date()),
210            z.hour(),
211            z.minute(),
212            self.schnittstelle,
213            self.von,
214            self.an,
215            self.art()
216        )?;
217        for c in self.codes() {
218            write!(f, " {c}")?;
219        }
220        Ok(())
221    }
222}
223
224/// A played scenario.
225#[derive(Debug, Clone, PartialEq, Eq, Default)]
226pub struct Ablauf {
227    /// Every message of both sides, in time order.
228    pub nachrichten: Vec<Nachricht>,
229    /// What a peer refused while playing, value-free; empty for every scenario of the catalogue.
230    pub abgelehnt: Vec<String>,
231}
232
233impl Ablauf {
234    /// Every message as `(file name, XML)`, in time order.
235    ///
236    /// # Errors
237    ///
238    /// A payload exceeds a schema maximum (never for a scenario's payload).
239    pub fn files(&self) -> Result<Vec<(String, String)>, WriteError> {
240        self.nachrichten.iter().enumerate().map(|(i, n)| Ok((n.file_name(i.saturating_add(1)), n.to_xml()?))).collect()
241    }
242}
243
244// -- the runner -------------------------------------------------------------------------------
245
246/// A message on its way.
247struct Item {
248    at: Timestamp,
249    seq: u64,
250    von: Partei,
251    an: Partei,
252    inhalt: Inhalt,
253}
254
255/// The peers, the scripted side's mailbox and what was sent.
256struct Lauf {
257    ekpabg: Option<Ekpabg>,
258    le: Option<Leistungserbringer>,
259    ab: Option<AbgebenderProvider>,
260    signatur: wbci::SignaturId,
261    ag: spri::Auftraggebernummer,
262    queue: Vec<Item>,
263    seq: u64,
264    sent: Vec<Item>,
265    abgelehnt: Vec<String>,
266}
267
268const fn partei(role: SRole) -> Partei {
269    match role {
270        SRole::Auftraggeber => Partei::EkpAuf,
271        SRole::Leistungserbringer => Partei::Netzbetreiber,
272        SRole::AbgebenderProvider => Partei::EkpAbg,
273    }
274}
275
276impl Lauf {
277    fn new(d: &Daten) -> Self {
278        Self {
279            ekpabg: None,
280            le: None,
281            ab: None,
282            signatur: d.signatur.clone(),
283            ag: d.ag.clone(),
284            queue: Vec::new(),
285            seq: 0,
286            sent: Vec::new(),
287            abgelehnt: Vec::new(),
288        }
289    }
290
291    fn push(&mut self, at: Timestamp, von: Partei, an: Partei, inhalt: Inhalt) {
292        self.seq = self.seq.saturating_add(1);
293        self.queue.push(Item { at, seq: self.seq, von, an, inhalt });
294    }
295
296    /// The scripted side sends a WBCI request.
297    fn wbci(&mut self, at: Timestamp, anfrage: impl Into<wbci::Anfrage>) {
298        let control = self.wbci_control(at);
299        let p = wbci::Payload::AnfrageRequest { control, anfrage: anfrage.into() };
300        self.push(at, Partei::EkpAuf, Partei::EkpAbg, Inhalt::Wbci(Box::new(p)));
301    }
302
303    /// The scripted side sends a WBCI message.
304    fn wbci_meldung(&mut self, at: Timestamp, meldung: impl Into<wbci::Meldung>) {
305        let control = self.wbci_control(at);
306        let p = wbci::Payload::MeldungRequest { control, meldung: meldung.into() };
307        self.push(at, Partei::EkpAuf, Partei::EkpAbg, Inhalt::Wbci(Box::new(p)));
308    }
309
310    /// The scripted side sends an S/PRI order.
311    fn spri(&mut self, at: Timestamp, auftrag: spri::Auftrag) {
312        let control = self.spri_control(at);
313        let p = spri::Payload::AuftragRequest { control, auftrag };
314        self.push(at, Partei::EkpAuf, Partei::Netzbetreiber, Inhalt::Spri(Box::new(p)));
315    }
316
317    fn wbci_control(&self, at: Timestamp) -> wbci::Control {
318        wbci::Control::new(at, self.signatur.clone())
319    }
320
321    fn spri_control(&self, at: Timestamp) -> spri::Control {
322        spri::Control::new(at, self.signatur.clone())
323    }
324
325    fn reject(&mut self, what: &str, why: impl fmt::Display) {
326        self.abgelehnt.push(format!("{what}: {why}"));
327    }
328
329    /// The scripted side receives `item`: it acknowledges every business message.
330    fn scripted(&mut self, item: &Item) {
331        let at = item.at.saturating_add(ACK).unwrap_or(item.at);
332        match &item.inhalt {
333            Inhalt::Wbci(p) => {
334                if let wbci::Payload::MeldungRequest { meldung, .. } = &**p {
335                    let quittung = wbci::Teq::for_meldung(meldung, wbci::Meldungscode::Ok);
336                    let control = self.wbci_control(at);
337                    let teq = wbci::Payload::MeldungResponse { control, quittung };
338                    self.push(at, Partei::EkpAuf, item.von, Inhalt::Wbci(Box::new(teq)));
339                }
340            }
341            Inhalt::Spri(p) => {
342                if let spri::Payload::MeldungRequest { meldung, .. } = &**p {
343                    let quittung = spri::Teq::new(
344                        spri::Meldungscode::Ok,
345                        Some(meldung.externe_auftragsnummer().clone()),
346                        Some(self.ag.clone()),
347                    );
348                    let control = self.spri_control(at);
349                    let teq = spri::Payload::MeldungResponse { control, quittung };
350                    self.push(at, Partei::EkpAuf, item.von, Inhalt::Spri(Box::new(teq)));
351                }
352            }
353        }
354    }
355
356    /// Delivers `item` to its receiver.
357    fn deliver(&mut self, item: &Item) {
358        let kind = match &item.inhalt {
359            Inhalt::Wbci(p) => p.kind(),
360            Inhalt::Spri(p) => p.kind(),
361        };
362        match (&item.inhalt, item.an) {
363            (_, Partei::EkpAuf) => self.scripted(item),
364            (Inhalt::Wbci(p), Partei::EkpAbg) => {
365                let Some(peer) = self.ekpabg.as_mut() else { return self.reject(kind, "no WBCI losing provider") };
366                let r = peer.receive(p, item.at);
367                if let Some(rej) = r.rejection {
368                    self.reject(kind, rej);
369                }
370                for o in r.outbound {
371                    self.push(o.at, Partei::EkpAbg, Partei::EkpAuf, Inhalt::Wbci(Box::new(o.payload)));
372                }
373            }
374            (Inhalt::Spri(p), Partei::EkpAbg) => {
375                let Some(peer) = self.ab.as_mut() else { return self.reject(kind, "no S/PRI losing provider") };
376                let r = peer.receive(p, item.at);
377                if let Some(rej) = r.rejection {
378                    self.reject(kind, rej);
379                }
380                for o in r.outbound {
381                    self.push(o.at, Partei::EkpAbg, partei(o.to), Inhalt::Spri(Box::new(o.payload)));
382                }
383            }
384            (Inhalt::Spri(p), Partei::Netzbetreiber) => {
385                let Some(peer) = self.le.as_mut() else { return self.reject(kind, "no network owner") };
386                let r = peer.receive(p, item.at);
387                if let Some(rej) = r.rejection {
388                    self.reject(kind, rej);
389                }
390                for o in r.outbound {
391                    self.push(o.at, Partei::Netzbetreiber, partei(o.to), Inhalt::Spri(Box::new(o.payload)));
392                }
393            }
394            (Inhalt::Wbci(_), Partei::Netzbetreiber) => self.reject(kind, "the network owner is no WBCI party"),
395        }
396    }
397
398    /// One step: the earliest delivery or peer act by `until`. `false` when nothing is left.
399    fn step(&mut self, until: Timestamp) -> bool {
400        let queued = self.queue.iter().map(|i| (i.at, i.seq)).min();
401        let w = self.ekpabg.as_ref().and_then(Ekpabg::next_due);
402        let le = self.le.as_ref().and_then(Leistungserbringer::next_due);
403        let ab = self.ab.as_ref().and_then(AbgebenderProvider::next_due);
404        let Some(t) = [queued.map(|q| q.0), w, le, ab].into_iter().flatten().min().filter(|t| *t <= until) else {
405            return false;
406        };
407        if let Some((at, seq)) = queued
408            && at == t
409        {
410            let Some(pos) = self.queue.iter().position(|i| i.seq == seq) else { return false };
411            let item = self.queue.remove(pos);
412            self.deliver(&item);
413            self.sent.push(item);
414        } else if w == Some(t) {
415            for o in self.ekpabg.as_mut().map(|p| p.advance(t)).unwrap_or_default() {
416                self.push(o.at, Partei::EkpAbg, Partei::EkpAuf, Inhalt::Wbci(Box::new(o.payload)));
417            }
418        } else if le == Some(t) {
419            for o in self.le.as_mut().map(|p| p.advance(t)).unwrap_or_default() {
420                self.push(o.at, Partei::Netzbetreiber, partei(o.to), Inhalt::Spri(Box::new(o.payload)));
421            }
422        } else {
423            for o in self.ab.as_mut().map(|p| p.advance(t)).unwrap_or_default() {
424                self.push(o.at, Partei::EkpAbg, partei(o.to), Inhalt::Spri(Box::new(o.payload)));
425            }
426        }
427        true
428    }
429
430    /// Plays everything due by `until`.
431    fn run(&mut self, until: Timestamp) {
432        for _ in 0..MAX_STEPS {
433            if !self.step(until) {
434                return;
435            }
436        }
437        self.abgelehnt.push("the scenario does not settle".to_owned());
438    }
439
440    /// Plays until a peer has sent a message of one of `kinds`, then its receipt; returns when
441    /// the scripted side acts next (one [`PAUSE`] after that message).
442    fn after(&mut self, kinds: &[&str]) -> Result<Timestamp, Box<dyn Error>> {
443        let mark = self.sent.len();
444        let horizon = Timestamp::MAX;
445        for _ in 0..MAX_STEPS {
446            let found = self.sent.get(mark..).and_then(|s| {
447                s.iter().find(|i| i.von != Partei::EkpAuf && kinds.contains(&kind_of(&i.inhalt))).map(|i| i.at)
448            });
449            if let Some(at) = found {
450                self.run(at.saturating_add(SignedDuration::from_mins(1)).unwrap_or(at));
451                return Ok(at.saturating_add(PAUSE).unwrap_or(at));
452            }
453            if !self.step(horizon) {
454                break;
455            }
456        }
457        Err(format!("no {} was sent", kinds.join(" or ")).into())
458    }
459
460    /// The last WBCI message of type `typ` the losing provider sent.
461    fn wbci_last(&self, typ: wbci::Meldungstyp) -> Option<wbci::Meldung> {
462        self.sent.iter().rev().find_map(|i| match &i.inhalt {
463            Inhalt::Wbci(p) => match &**p {
464                wbci::Payload::MeldungRequest { meldung, .. } if meldung.meldungstyp() == typ => Some(meldung.clone()),
465                _ => None,
466            },
467            Inhalt::Spri(_) => None,
468        })
469    }
470
471    fn ablauf(mut self) -> Ablauf {
472        self.run(Timestamp::MAX);
473        for (name, stopped) in [
474            ("WBCI losing provider", self.ekpabg.as_ref().and_then(|p| p.stopped().map(ToString::to_string))),
475            ("network owner", self.le.as_ref().and_then(|p| p.stopped().map(ToString::to_string))),
476            ("S/PRI losing provider", self.ab.as_ref().and_then(|p| p.stopped().map(ToString::to_string))),
477        ] {
478            if let Some(s) = stopped {
479                self.abgelehnt.push(format!("{name} stopped: {s}"));
480            }
481        }
482        let mut sent = self.sent;
483        sent.sort_by_key(|i| (i.at, i.seq));
484        let nachrichten = sent
485            .into_iter()
486            .map(|i| Nachricht {
487                at: i.at,
488                schnittstelle: match i.inhalt {
489                    Inhalt::Wbci(_) => Schnittstelle::Wbci,
490                    Inhalt::Spri(_) => Schnittstelle::Spri,
491                },
492                von: i.von,
493                an: i.an,
494                inhalt: i.inhalt,
495            })
496            .collect();
497        Ablauf { nachrichten, abgelehnt: self.abgelehnt }
498    }
499}
500
501fn kind_of(i: &Inhalt) -> &'static str {
502    match i {
503        Inhalt::Wbci(p) => p.kind(),
504        Inhalt::Spri(p) => p.kind(),
505    }
506}
507
508// -- synthetic data ---------------------------------------------------------------------------
509
510/// The scenarios' synthetic data. Every name, address and number is invented.
511struct Daten {
512    ekp: wbci::Ekp,
513    signatur: wbci::SignaturId,
514    ag: spri::Auftraggebernummer,
515}
516
517impl Daten {
518    fn new() -> Result<Self, Box<dyn Error>> {
519        Ok(Self {
520            ekp: wbci::Ekp { auf: "DEU.EKP1".parse()?, abg: "DEU.EKP2".parse()? },
521            signatur: wbci::SignaturId {
522                issuer: carrier_core::SignaturText::new("CN=Sandbox CA, O=telco-interop")?,
523                serial: carrier_core::SignaturText::new("1")?,
524            },
525            ag: spri::Auftraggebernummer::new("4711")?,
526        })
527    }
528
529    fn va_id(&self) -> Result<wbci::VorabstimmungsId, Box<dyn Error>> {
530        Ok(wbci::VorabstimmungsId::allocate(&self.ekp.auf, 1)?)
531    }
532
533    fn standort() -> Result<wbci::Standort, Box<dyn Error>> {
534        Ok(wbci::Standort {
535            strassenname: wbci::Strassenname::new("Musterweg")?,
536            hausnummer: wbci::Hausnummer::new("1")?,
537            hausnummern_zusatz: None,
538            postleitzahl: wbci::Postleitzahl::new("12345")?,
539            ort: wbci::Ortsname::new("Musterstadt")?,
540        })
541    }
542
543    fn kunde() -> Result<wbci::Kunde, Box<dyn Error>> {
544        Ok(wbci::Kunde::person(
545            wbci::Anrede::Frau,
546            Some(wbci::Vorname::new("Erika")?),
547            wbci::Nachname::new("Musterfrau")?,
548        ))
549    }
550
551    fn nummer(nr: &str) -> Result<wbci::OnkzRufnummer, Box<dyn Error>> {
552        Ok(wbci::OnkzRufnummer { onkz: wbci::Onkz::new("30")?, rufnummer: wbci::Rufnummer::new(nr)? })
553    }
554
555    /// A pre-agreement sent at `start`, for 5 working days after the earliest permitted date.
556    fn va(&self, start: Timestamp, mrn: bool) -> Result<wbci::Vorabstimmung, Box<dyn Error>> {
557        let cal = wbci::Calendar::wbci();
558        let fall = if mrn { wbci::Geschaeftsfall::VaKueMrn } else { wbci::Geschaeftsfall::VaKueOrn };
559        let earliest = wbci::deadline::earliest_kundenwunschtermin(fall, start, &cal).ok_or("no lead time")?;
560        let fall = if mrn {
561            wbci::VorabstimmungsFall::KueMrn {
562                standort: Self::standort()?,
563                rufnummernportierung: wbci::Rufnummernportierung {
564                    anschluss: wbci::Anschluss::Einzel {
565                        rufnummern: vec![Self::nummer("5550100")?],
566                        alle_rufnummern: false,
567                    },
568                    zeitfenster: wbci::Portierungszeitfenster::Zf2,
569                },
570            }
571        } else {
572            wbci::VorabstimmungsFall::KueOrn { standort: Self::standort()?, anschlussidentifikation: None }
573        };
574        Ok(wbci::Vorabstimmung {
575            ekp: self.ekp.clone(),
576            id: self.va_id()?,
577            kundenwunschtermin: cal.add_working_days(earliest.date, 5),
578            endkunde: Self::kunde()?,
579            weitere_anschlussinhaber: Vec::new(),
580            projekt: None,
581            fall,
582        })
583    }
584
585    /// The losing provider's record of the line: matching `va`, with `nummer` and the line.
586    fn bestand(nummer: &str, line: Option<&spri::LineId>) -> Result<wbci::pruefung::Bestand, Box<dyn Error>> {
587        let mut b = wbci::pruefung::Bestand::new(Self::kunde()?, wbci::Portierungskennung::new("D234")?);
588        b.standort = Some(Self::standort()?);
589        b.rufnummern = vec![Self::nummer(nummer)?];
590        if let Some(line) = line {
591            b.ressourcen = vec![wbci::TechnischeRessource { line_id: Some(line.clone()), ..Default::default() }];
592        }
593        Ok(b)
594    }
595
596    fn ansprechpartner() -> Result<spri::AnsprechpartnerAuftrag, Box<dyn Error>> {
597        Ok(spri::AnsprechpartnerAuftrag {
598            auftragsmanagement: spri::Ansprechpartner {
599                person: spri::Person {
600                    anrede: spri::Anrede::Herr,
601                    vorname: None,
602                    nachname: spri::Nachname::new("Auftragsmanagement")?,
603                },
604                telefonnummer: spri::Telefonnummer::new("030 5550200")?,
605                mobilfunknummer: None,
606                faxnummer: None,
607                emailadresse: None,
608            },
609            weitere: Vec::new(),
610        })
611    }
612
613    fn standort_a() -> Result<spri::StandortA, Box<dyn Error>> {
614        Ok(spri::StandortA {
615            inhaber: spri::Inhaber::Person(spri::Person {
616                anrede: spri::Anrede::Frau,
617                vorname: Some(spri::Vorname::new("Erika")?),
618                nachname: spri::Nachname::new("Musterfrau")?,
619            }),
620            telefonnummer: None,
621            mobilfunknummer: None,
622            strasse: spri::Strasse {
623                strassenname: spri::Strassenname::new("Musterweg")?,
624                hausnummer: spri::Hausnummer::new("1")?,
625                hausnummern_zusatz: None,
626            },
627            gebaeudeteil: None,
628            land: None,
629            postleitzahl: spri::Postleitzahl::new("12345")?,
630            ort: spri::Ort { ortsname: spri::Ortsname::new("Musterstadt")?, ortsteil: None },
631            lage_tae_ont: None,
632        })
633    }
634
635    fn auftrag(
636        &self,
637        geschaeftsfall: spri::Geschaeftsfall,
638        art: spri::GeschaeftsfallArt,
639    ) -> Result<spri::Auftrag, Box<dyn Error>> {
640        Ok(spri::Auftrag {
641            externe_auftragsnummer: spri::ExterneAuftragsnummer::new("SB-2027-0001")?,
642            auftraggeber: spri::Auftraggeber {
643                auftraggebernummer: self.ag.clone(),
644                leistungsnummer: spri::Leistungsnummer::new("RV-1")?,
645            },
646            besteller: None,
647            geschaeftsfall,
648            geschaeftsfall_art: art,
649            aenderungskennzeichen: spri::Aenderungskennzeichen::Standard,
650            termin_neu: None,
651            kenner: None,
652        })
653    }
654
655    /// A NEU for the line of a switching customer, 15 working days after `start`.
656    fn neu(&self, start: Timestamp) -> Result<spri::Auftrag, Box<dyn Error>> {
657        let datum = wbci::Calendar::wbci().add_working_days(day_of(start), 15);
658        let neu = spri::Bereitstellung {
659            vorabstimmungs_id: Some(self.va_id()?),
660            anlage: None,
661            ansprechpartner: Self::ansprechpartner()?,
662            wunschtermin: datum.into(),
663            produkt: spri::Produkt { bezeichner: spri::Produktbezeichner::new("FTTH 1000")? },
664            fttx: spri::FttxBereitstellung {
665                standort_a: Self::standort_a()?,
666                standort_versand: None,
667                vormieter: None,
668                montageleistung: None,
669                wita: spri::WitaExtendedInfos {
670                    wita: spri::WitaInfos { wita_vertragsnummer: None, technologie: None },
671                    bestandssuche: None,
672                    rufnummern_portierung: None,
673                    abgebender_ekp: None,
674                },
675            },
676            positionen: Vec::new(),
677        };
678        self.auftrag(spri::Geschaeftsfall::Neu(neu), spri::GeschaeftsfallArt::Bereitstellung)
679    }
680
681    /// A PV of `line` for `datum`.
682    fn pv(&self, datum: wbci::Date, line: spri::LineId) -> Result<spri::Auftrag, Box<dyn Error>> {
683        let pv = spri::Providerwechsel {
684            line_id: line,
685            vorabstimmungs_id: self.va_id()?,
686            anlage: None,
687            ansprechpartner: Self::ansprechpartner()?,
688            wunschtermin: datum.into(),
689            produkt: spri::Produkt { bezeichner: spri::Produktbezeichner::new("FTTH 1000")? },
690            fttx: spri::FttxProviderwechsel { standort_a: Self::standort_a()?, montageleistung: None },
691            positionen: Vec::new(),
692        };
693        self.auftrag(spri::Geschaeftsfall::Pv(pv), spri::GeschaeftsfallArt::Endkundenanbieterwechsel)
694    }
695
696    fn line() -> Result<spri::LineId, Box<dyn Error>> {
697        Ok("DEU.NB01.4200000042".parse()?)
698    }
699}
700
701fn hours(n: i64) -> SignedDuration {
702    SignedDuration::from_hours(n)
703}
704
705// -- the scenarios ----------------------------------------------------------------------------
706
707/// A WBCI switch answered by the losing provider with `antwort`; returns the runner after the
708/// answer and the pre-agreement.
709fn wbci_answered(
710    start: Timestamp,
711    mrn: bool,
712    antwort: impl FnOnce(&wbci::Vorabstimmung) -> Result<Antwort, Box<dyn Error>>,
713) -> Result<(Lauf, wbci::Vorabstimmung, Timestamp), Box<dyn Error>> {
714    let d = Daten::new()?;
715    let va = d.va(start, mrn)?;
716    let mut l = Lauf::new(&d);
717    l.ekpabg = Some(Ekpabg::new(antwort(&va)?, d.signatur.clone()));
718    l.wbci(start, va.clone());
719    let next = l.after(&["RUEM-VA", "ABBM"])?;
720    Ok((l, va, next))
721}
722
723fn wbci_agreed(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
724    let (mut l, _, next) =
725        wbci_answered(start, true, |_| Ok(Antwort::Pruefung(Box::new(Daten::bestand("5550100", None)?))))?;
726    let Some(wbci::Meldung::RuemVa(ruem)) = l.wbci_last(wbci::Meldungstyp::RuemVa) else {
727        return Err("no RUEM-VA".into());
728    };
729    l.wbci_meldung(next, wbci::AkmTr::uebernahme(&ruem, Vec::new(), false));
730    Ok(l)
731}
732
733fn wbci_refused_rng(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
734    let (l, _, _) = wbci_answered(start, true, |_| Ok(Antwort::Pruefung(Box::new(Daten::bestand("5550199", None)?))))?;
735    Ok(l)
736}
737
738fn wbci_storno(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
739    let (mut l, va, next) = wbci_answered(start, false, |_| Ok(Antwort::Zustimmung))?;
740    let storno = wbci::Storno {
741        ekp: va.ekp.clone(),
742        storno_id: wbci::StornoId::allocate(&va.ekp.auf, 1)?,
743        bezug: wbci::Bezug::Id(va.id.clone()),
744        art: wbci::StornoArt::AufhebungAuf,
745    };
746    l.wbci(next.saturating_add(hours(23))?, storno);
747    Ok(l)
748}
749
750fn wbci_tvs(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
751    let (mut l, va, next) = wbci_answered(start, false, |_| Ok(Antwort::Zustimmung))?;
752    let Some(wbci::Meldung::RuemVa(ruem)) = l.wbci_last(wbci::Meldungstyp::RuemVa) else {
753        return Err("no RUEM-VA".into());
754    };
755    let tvs = wbci::Terminverschiebung {
756        ekp: va.ekp.clone(),
757        aenderungs_id: wbci::AenderungsId::allocate(&va.ekp.auf, 1)?,
758        bezug: wbci::Bezug::Id(va.id.clone()),
759        name: None,
760        neuer_kundenwunschtermin: wbci::Calendar::wbci().add_working_days(ruem.wechseltermin, 5),
761    };
762    l.wbci(next.saturating_add(hours(23))?, tvs);
763    Ok(l)
764}
765
766/// A NEU sent at `start` to `le`; returns the runner after the ABM.
767fn neu_confirmed(start: Timestamp, le: Leistungserbringer) -> Result<(Lauf, spri::Auftrag, Timestamp), Box<dyn Error>> {
768    let d = Daten::new()?;
769    let neu = d.neu(start)?;
770    let mut l = Lauf::new(&d);
771    l.le = Some(le);
772    l.spri(start, neu.clone());
773    let next = l.after(&["ABM"])?;
774    Ok((l, neu, next))
775}
776
777fn le(d: &Daten) -> Leistungserbringer {
778    Leistungserbringer::new(d.signatur.clone())
779}
780
781fn spri_neu(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
782    let (l, _, _) = neu_confirmed(start, le(&Daten::new()?))?;
783    Ok(l)
784}
785
786fn spri_neu_tam(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
787    let (l, _, _) = neu_confirmed(start, le(&Daten::new()?).with_terminanforderung())?;
788    Ok(l)
789}
790
791fn storno(start: Timestamp, le: Leistungserbringer) -> Result<Lauf, Box<dyn Error>> {
792    let (mut l, mut neu, next) = neu_confirmed(start, le)?;
793    neu.aenderungskennzeichen = spri::Aenderungskennzeichen::Storno;
794    l.spri(next.saturating_add(hours(23))?, neu);
795    Ok(l)
796}
797
798fn spri_storno(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
799    storno(start, le(&Daten::new()?))
800}
801
802fn spri_storno_refused(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
803    storno(start, le(&Daten::new()?).with_storno_abgelehnt())
804}
805
806fn spri_tv(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
807    let (mut l, mut neu, next) = neu_confirmed(start, le(&Daten::new()?))?;
808    let spri::Geschaeftsfall::Neu(b) = &mut neu.geschaeftsfall else { return Err("not a NEU".into()) };
809    b.wunschtermin.datum = wbci::Calendar::wbci().add_working_days(b.wunschtermin.datum, 5);
810    neu.aenderungskennzeichen = spri::Aenderungskennzeichen::Terminverschiebung;
811    l.spri(next.saturating_add(hours(23))?, neu);
812    Ok(l)
813}
814
815fn pv(start: Timestamp, rueckmeldung: Rueckmeldung) -> Result<Lauf, Box<dyn Error>> {
816    let d = Daten::new()?;
817    let datum = wbci::Calendar::wbci().add_working_days(day_of(start), 15);
818    let mut l = Lauf::new(&d);
819    l.le = Some(le(&d));
820    l.ab = Some(AbgebenderProvider::new(rueckmeldung, d.signatur.clone()));
821    l.spri(start, d.pv(datum, Daten::line()?)?);
822    Ok(l)
823}
824
825fn spri_pv(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
826    pv(start, Rueckmeldung::Zustimmung)
827}
828
829fn spri_pv_refused(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
830    pv(start, Rueckmeldung::Ablehnung(spri::Antwortcode::new("KVE")?))
831}
832
833fn spri_pv_timeout(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
834    pv(start, Rueckmeldung::Keine)
835}
836
837fn wechsel(start: Timestamp) -> Result<Lauf, Box<dyn Error>> {
838    let d = Daten::new()?;
839    let line = Daten::line()?;
840    let (mut l, _, next) =
841        wbci_answered(start, true, |_| Ok(Antwort::Pruefung(Box::new(Daten::bestand("5550100", Some(&line))?))))?;
842    let Some(wbci::Meldung::RuemVa(ruem)) = l.wbci_last(wbci::Meldungstyp::RuemVa) else {
843        return Err("no RUEM-VA".into());
844    };
845    // The gaining provider takes over the line the losing provider named (Anl. 1 V5.4.1 §2.6.2) …
846    let lines: Vec<wbci::UebernahmeLeitung> =
847        ruem.ressourcen.iter().filter_map(|r| r.line_id.clone()).map(wbci::UebernahmeLeitung::LineId).collect();
848    l.wbci_meldung(next, wbci::AkmTr::uebernahme(&ruem, lines, false));
849    // … and orders it from the network owner for the agreed switch date (S/PRI 4.4 §5.5.1.1).
850    l.le = Some(le(&d));
851    l.ab = Some(AbgebenderProvider::new(Rueckmeldung::Zustimmung, d.signatur.clone()));
852    l.spri(next.saturating_add(PAUSE)?, d.pv(ruem.wechseltermin, line)?);
853    Ok(l)
854}
855
856const KATALOG: &[Szenario] = &[
857    Szenario {
858        name: "wbci-agreed",
859        beschreibung: "VA-KUE-MRN checked against the losing provider's record: TEQ, RUEM-VA 8001, AKM-TR",
860        quelle: "Anl. 1 V5.4.1 §2.2–§2.6; WBCI 2.0 §12.3",
861        play: wbci_agreed,
862    },
863    Szenario {
864        name: "wbci-refused-rng",
865        beschreibung: "VA-KUE-MRN, the record has another number: ABBM 8103 (RNG)",
866        quelle: "Anl. 1 V5.4.1 §2.3, §2.4",
867        play: wbci_refused_rng,
868    },
869    Szenario {
870        name: "wbci-storno",
871        beschreibung: "VA-KUE-ORN agreed, cancelled by the gaining provider (STR-AUF): ERLM 8004",
872        quelle: "Anl. 1 V5.4.1 §2.9.1",
873        play: wbci_storno,
874    },
875    Szenario {
876        name: "wbci-tvs",
877        beschreibung: "VA-KUE-ORN agreed, postponed by the gaining provider (TVS-VA): ERLM 8003",
878        quelle: "Anl. 1 V5.4.1 §2.11",
879        play: wbci_tvs,
880    },
881    Szenario {
882        name: "spri-neu",
883        beschreibung: "NEU: TEQ, QEB, ABM, ERLM on the binding date, ENTM",
884        quelle: "Anl. 7 EPK V.13 p.1, p.10",
885        play: spri_neu,
886    },
887    Szenario {
888        name: "spri-neu-tam",
889        beschreibung: "NEU, the appointment fails: TAM, MTAM, ABBM 1198",
890        quelle: "Anl. 7 EPK V.13 p.1; AH 2.9.5 §3.6",
891        play: spri_neu_tam,
892    },
893    Szenario {
894        name: "spri-storno",
895        beschreibung: "NEU, Storno after the ABM: ERLM 0012, ENTM",
896        quelle: "Anl. 7 EPK V.13 p.11; AH 2.9.5 §3.5",
897        play: spri_storno,
898    },
899    Szenario {
900        name: "spri-storno-refused",
901        beschreibung: "NEU, Storno refused with ABBM 1087; the order completes",
902        quelle: "Anl. 7 EPK V.13 p.11",
903        play: spri_storno_refused,
904    },
905    Szenario {
906        name: "spri-tv",
907        beschreibung: "NEU, Terminverschiebung after the ABM: a new ABM, ERLM on the new date, ENTM",
908        quelle: "Anl. 7 EPK V.13 p.12; AH 2.9.5 §3.4",
909        play: spri_tv,
910    },
911    Szenario {
912        name: "spri-pv",
913        beschreibung: "PV: AKM-PV, RUEM-PV, ABM with ABM-PV, ERLM with ERLM-PV, ENTM with ENTM-PV",
914        quelle: "Anl. 7 EPK V.13 p.7; S/PRI 4.4 §5.5.1, §8.2.13",
915        play: spri_pv,
916    },
917    Szenario {
918        name: "spri-pv-refused",
919        beschreibung: "PV, the losing provider refuses (KVE): ABBM 0041, ABBM-PV 0040",
920        quelle: "Anl. 7 EPK V.13 p.7; S/PRI 4.4 §5.5.1.1, §5.5.1.2",
921        play: spri_pv_refused,
922    },
923    Szenario {
924        name: "spri-pv-timeout",
925        beschreibung: "PV, no RUEM-PV by the antwortfrist: ABBM 0042, ABBM-PV 0040",
926        quelle: "S/PRI 4.4 §5.5.1.1; Anl. 7 EPK V.13 p.7",
927        play: spri_pv_timeout,
928    },
929    Szenario {
930        name: "wechsel",
931        beschreibung: "The switch across both: VA, RUEM-VA with the LineID, AKM-TR, PV for the switch date, the PV leg, completion on the switch date",
932        quelle: "S/PRI 4.4 §5.5.1.1 (p. 27); Anl. 1 V5.4.1 §2.6.2; § 59 TKG",
933        play: wechsel,
934    },
935];
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    #[test]
942    fn the_start_is_monday_nine_oclock() {
943        assert_eq!(START.to_string(), "2027-03-01T08:00:00Z");
944    }
945
946    #[test]
947    fn names_are_unique_and_found() {
948        for s in katalog() {
949            assert_eq!(szenario(s.name).map(|x| x.name), Some(s.name));
950            assert_eq!(katalog().iter().filter(|x| x.name == s.name).count(), 1);
951        }
952        assert!(szenario("nope").is_none());
953    }
954}