Skip to main content

spri/
validate.rs

1//! Validation that predicts the network owner's refusal.
2//!
3//! Values are valid by construction (their types check the schema's facets); these rules cover
4//! what types cannot: which business case allows a Storno or a Terminverschiebung, an
5//! Auftragsklammer's size, a Zeitfenster against the weekday, a follow-up order against its
6//! original, a code against the message type and business case, the attributes a code needs.
7//! Every [`Issue`] names the element path, the rule, its source and, where the sources give one,
8//! the code of the ABBM the network owner answers with. Issues never contain personal data.
9//!
10//! ```
11//! use spri::*;
12//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
13//! # let xml = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/auftrag-aen-lmae.xml"))?;
14//! # let Payload::AuftragRequest { mut auftrag, .. } = Payload::from_xml(xml.as_bytes())? else { unreachable!() };
15//! // A feature change has no Terminverschiebung (S/PRI 4.4 §5.3.1.3).
16//! auftrag.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
17//! let issues = auftrag.issues();
18//! assert_eq!(issues[0].rule, "spri.aekz.terminverschiebung");
19//! assert_eq!(issues[0].code, Some(Meldungscode::C1007));
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! ## The rules
25//!
26//! Severity *error*: the text says the network owner refuses, or uses „must"/„not allowed";
27//! *warning*: advised against or likely a problem. Messages are not answered with an ABBM, so
28//! their issues carry no code. (I) marks an interpretation.
29//!
30//! | Rule | Checks | Source | Code |
31//! |---|---|---|---|
32//! | `spri.aekz.storno` | no Storno in GET and SET (messages: nor KUE-LE) | S/PRI 4.4 §6.2.1.2, §6.2.2.2; Anl. 7 EPK V.13 p.4 | 1007 |
33//! | `spri.aekz.terminverschiebung` | Terminverschiebung only in NEU, KUE-AG, LAE, PV | S/PRI 4.4 §5.3.1.3, §6.1.3, §6.2.1.3, §6.2.2.3 | 1007 |
34//! | `spri.termin-neu.only-tv` | `terminNeu` only with Terminverschiebung (warning) | XSD 4.00.03 `AuftragType` | |
35//! | `spri.geschaeftsfallart.match` | the Geschäftsfallart belongs to the business case; PV also `Bereitstellung` (I) | S/PRI 4.4 §4.1 | |
36//! | `spri.auftragsklammer.count` | an Auftragsklammer holds 1 to 20 orders | S/PRI 4.4 §4.3.3; AH 2.9.5 §3.7 | |
37//! | `spri.auftragsklammer.case` | only NEU, AEN-LMAE, LAE and PV are bracketed | AH 2.9.5 §3.7; S/PRI 4.4 §4.3.3 | |
38//! | `spri.zeitfenster.weekday` | the Zeitfenster fits the weekday of the date; „Werktags" = Monday to Saturday (I) | AH 2.9.5 §3.3; XSD 4.00.03 `ZeitfensterType` | 1032 |
39//! | `spri.kue-ag.wita-vertragsnummer` | a KUE-AG with Vorabstimmungs-ID names the WITA contract number (warning, I) | S/PRI 4.4 §5.2.1.4 | |
40//! | `spri.line-id.va-id` | the LineID is not the Vorabstimmungs-ID (I: the network owner keeps the two ranges apart, so it answers „LineID ist nicht bekannt") | LineID V1.4 §3.1.3 | 8144 |
41//! | `spri.termin.past` | the date is not in the past (`issues_at`); 1003 outside EST (I) | AH 2.9.5 §6.4 (7014, 1003) | 7014, 1003 |
42//! | `spri.termin.horizon` | the date is at most 180 days ahead (warning, `issues_at`) | S/PRI 4.4 §2, §5.1.4 | 1003 |
43//! | `spri.termin.working-day` | the date is a working day (warning, `issues_at`) | AH 2.9.5 §6.4 (0002) | 0002 |
44//! | `spri.bezug.order-number` | a Storno, TV or Reklamation repeats the original's order number | S/PRI 4.4 §5.1.3, §5.1.4, §6.1.5 | |
45//! | `spri.bezug.case` | … and its business case | S/PRI 4.4 §5.1.3, §5.1.4 | |
46//! | `spri.bezug.original` | … and refers to a standard order | AH 2.9.5 §3.4, §3.5 | |
47//! | `spri.bezug.repeated` | a new standard order does not reuse an order number | AH 2.9.5 §3.9 | 1013 |
48//! | `spri.storno.identical` | a Storno is identical to the original but for the Änderungskennzeichen (warning) | S/PRI 4.4 §5.1.3, §5.3.1.2, §6.1.2 | |
49//! | `spri.tv.identical` | a TV changes only date, `terminNeu`, Anlage, Montageleistung, Seriennummer ONT, Vorabstimmungs-ID (warning) | S/PRI 4.4 §5.1.4 | |
50//! | `spri.tv.new-date` | a TV names a date other than the original's | S/PRI 4.4 §5.1.4 | 1085 |
51//! | `spri.tv.earlier` | a PV is not moved earlier | AH 2.9.5 §3.4 | 1085 |
52//! | `spri.tv.zeitfenster` | a TV keeps the Zeitfenster | AH 2.9.5 §3.4 | 1085 |
53//! | `spri.reklamation.identical` | a Reklamation changes only Anlage, contacts, date, Störungsbeschreibung (warning) | S/PRI 4.4 §6.1.5 | |
54//! | `spri.code.unknown` | the code is in the published list (warning: the online list grows) | AH 2.9.5 §6.3; S/PRI 4.4 §11.2.4 | |
55//! | `spri.code.applicability` | the code belongs to the message type and the business case | AH 2.9.5 §6.4 | |
56//! | `spri.code.1312` | `1312` only together with `1310` or `1311` | AH 2.9.5 §6.4 (1312) | |
57//! | `spri.code.freitext` | `1312`, `8600`, `8601` carry a text of their own (warning) | AH 2.9.5 §6.4 (1312, 8600, 8601) | |
58//! | `spri.vzm.verzoegerungstermin` | a VZM with `1576`, `1580` or `1581` names the Verzögerungstermin | AH 2.9.5 §6.4 | |
59//! | `spri.abbm.erledigungstermin` | an ABBM `1006`/`1012` gives the open order's date in `wiedervorlagetermin` (warning, I) | AH 2.9.5 §6.4 (1006, 1012) | |
60//! | `spri.abbm.abgebender-provider` | an ABBM `0041`/`0042` names the losing provider | AH 2.9.5 §6.4 (0041, 0042) | |
61//! | `spri.ruem-pv.antwortcode-missing` | a refusing RUEM-PV gives a reason | S/PRI 4.4 §5.5.1.1 | |
62//! | `spri.ruem-pv.antwortcode-known` | the reason is `LnB`, `KVE`, `TAV`, `VnB` or `Vnv`, ignoring case (I) | S/PRI 4.4 §5.5.1.1; AH 2.9.5 §6.5 | |
63//! | `spri.ruem-pv.contradiction` | a consenting RUEM-PV carries no refusal reason (I) | S/PRI 4.4 §5.5.1.1 | |
64//! | `spri.teq.code` | a receipt carries only `OK`, `0990`, `0991`, `0993`, `0995`, `0999` | AH 2.9.5 §6.4 | |
65//! | `spri.teq.mixed` | a receipt is either `OK` or an error, not both (I) | S/PRI 4.4 §11.2.3.1 | |
66//!
67//! The rules shared with [`crate::process::Process`] (Storno and Terminverschiebung per
68//! business case, a TV with a new date, PV not earlier, the refusal reasons) use the same
69//! predicates and codes. Ordering rules — a Storno before the QEB, a second open TV, the 36-hour
70//! window — need the order's history and are the process's job.
71
72use core::fmt;
73
74use carrier_core::Calendar;
75use carrier_core::count::day_of;
76use jiff::civil::{Date, Weekday};
77use jiff::{Timestamp, ToSpan};
78
79use crate::process::{has_storno, has_tv, is_refusal_code};
80use crate::{
81    Abbm, Aenderungskennzeichen, Auftrag, Auftragstyp, Geschaeftsfall, GeschaeftsfallArt, GeschaeftsfallCode, JaNein,
82    Meldung, Meldungscode, Meldungsinhalt, Meldungstyp, Position, RuemPv, Teq, Vzm, Wunschtermin, Zeitfenster,
83};
84
85/// How serious an issue is.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub enum Severity {
88    /// Advised against or likely a problem; the peer will probably still accept it.
89    Warning,
90    /// The peer refuses it, or the specification says it must not be sent so.
91    Error,
92}
93
94/// One finding.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Issue {
97    /// Error or warning.
98    pub severity: Severity,
99    /// Element path in XML names, e.g. `auftrag/aenderungskennzeichen`.
100    pub path: String,
101    /// Stable rule identifier, e.g. `spri.aekz.terminverschiebung`.
102    pub rule: &'static str,
103    /// What is wrong, in one sentence; codes, dates and counts only.
104    pub message: String,
105    /// Where the rule is written: document, version, clause.
106    pub source: &'static str,
107    /// The code of the ABBM the network owner answers with, where the sources give one.
108    pub code: Option<Meldungscode>,
109}
110
111impl fmt::Display for Issue {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        let sev = match self.severity {
114            Severity::Error => "error",
115            Severity::Warning => "warning",
116        };
117        write!(f, "{sev} [{}] {}: {} ({})", self.rule, self.path, self.message, self.source)?;
118        if let Some(code) = &self.code {
119            write!(f, " → {}", code.as_str())?;
120        }
121        Ok(())
122    }
123}
124
125#[derive(Default)]
126struct Report(Vec<Issue>);
127
128impl Report {
129    fn add(
130        &mut self,
131        severity: Severity,
132        path: impl Into<String>,
133        rule: &'static str,
134        message: impl Into<String>,
135        source: &'static str,
136        code: Option<Meldungscode>,
137    ) {
138        self.0.push(Issue { severity, path: path.into(), rule, message: message.into(), source, code });
139    }
140
141    fn error(
142        &mut self,
143        path: impl Into<String>,
144        rule: &'static str,
145        message: impl Into<String>,
146        source: &'static str,
147        code: Option<Meldungscode>,
148    ) {
149        self.add(Severity::Error, path, rule, message, source, code);
150    }
151
152    fn warn(
153        &mut self,
154        path: impl Into<String>,
155        rule: &'static str,
156        message: impl Into<String>,
157        source: &'static str,
158        code: Option<Meldungscode>,
159    ) {
160        self.add(Severity::Warning, path, rule, message, source, code);
161    }
162}
163
164const WUNSCH: &str = "auftrag/geschaeftsfall/termine/auftraggeberWunschtermin";
165const SRC_STORNO: &str = "S/PRI 4.4 §6.2.1.2, §6.2.2.2; Anl. 7 EPK V.13 p.4";
166const SRC_TV: &str = "S/PRI 4.4 §5.3.1.3, §6.1.3, §6.2.1.3, §6.2.2.3";
167const SRC_ART: &str = "S/PRI 4.4 §4.1";
168const SRC_FACTS: &str = "AH 2.9.5 §6.4";
169
170fn wunschtermin(g: &Geschaeftsfall) -> Option<&Wunschtermin> {
171    match g {
172        Geschaeftsfall::Neu(x) => Some(&x.wunschtermin),
173        Geschaeftsfall::KueAg(x) => Some(&x.wunschtermin),
174        Geschaeftsfall::Lae(x) => Some(&x.wunschtermin),
175        Geschaeftsfall::AenLmae(x) => Some(&x.wunschtermin),
176        Geschaeftsfall::Est(x) => Some(&x.wunschtermin),
177        Geschaeftsfall::Pv(x) => Some(&x.wunschtermin),
178        Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => None,
179    }
180}
181
182/// The Geschäftsfallarten a business case is filed under (S/PRI 4.4 §4.1). PV also as
183/// `Bereitstellung`: the contract treats it as a provisioning (§5.5.1.1, interpretation).
184const fn art_fits(fall: GeschaeftsfallCode, art: GeschaeftsfallArt) -> bool {
185    use GeschaeftsfallArt as A;
186    use GeschaeftsfallCode as G;
187    matches!(
188        (fall, art),
189        (G::Neu, A::Bereitstellung)
190            | (G::KueAg | G::KueLe, A::Kuendigung)
191            | (G::Lae | G::AenLmae, A::Aenderung)
192            | (G::Est, A::Entstoerung)
193            | (G::Pv, A::Endkundenanbieterwechsel | A::Bereitstellung)
194            | (G::Get | G::Set, A::Diagnose)
195    )
196}
197
198/// Änderungskennzeichen and Geschäftsfallart against the business case, for orders and messages.
199fn auftragstyp(
200    r: &mut Report,
201    root: &str,
202    fall: GeschaeftsfallCode,
203    aekz: Aenderungskennzeichen,
204    art: GeschaeftsfallArt,
205    order: bool,
206) {
207    let aekz_path = if order { "auftrag/aenderungskennzeichen" } else { "meldung/auftragstyp/aenderungsKennzeichen" };
208    let code = |c: Meldungscode| if order { Some(c) } else { None };
209    match aekz {
210        Aenderungskennzeichen::Storno if !has_storno(fall) => r.error(
211            aekz_path,
212            "spri.aekz.storno",
213            format!("{fall} has no Storno"),
214            SRC_STORNO,
215            code(Meldungscode::C1007),
216        ),
217        Aenderungskennzeichen::Terminverschiebung if !has_tv(fall) => r.error(
218            aekz_path,
219            "spri.aekz.terminverschiebung",
220            format!("{fall} has no Terminverschiebung; only NEU, KUE-AG, LAE and PV have one"),
221            SRC_TV,
222            code(Meldungscode::C1007),
223        ),
224        _ => {}
225    }
226    if !art_fits(fall, art) {
227        let path =
228            if order { format!("{root}/geschaeftsfallArt") } else { format!("{root}/auftragstyp/geschaeftsfallart") };
229        r.error(path, "spri.geschaeftsfallart.match", format!("{fall} is not filed under {art}"), SRC_ART, None);
230    }
231}
232
233/// The weekdays a Zeitfenster may be used on: AH 2.9.5 §3.3 (windows 20–41) and the XSD
234/// annotations of windows 1–3; „Werktags" read as Monday to Saturday (interpretation). `None`
235/// for windows the documents assign no weekday.
236fn weekdays(z: Zeitfenster) -> Option<(&'static [Weekday], &'static str)> {
237    use Weekday::{Friday as Fr, Monday as Mo, Saturday as Sa, Thursday as Th, Tuesday as Tu, Wednesday as We};
238    const MO_FR: &[Weekday] = &[Mo, Tu, We, Th, Fr];
239    const MO_SA: &[Weekday] = &[Mo, Tu, We, Th, Fr, Sa];
240    let n: u8 = z.to_string().parse().ok()?;
241    Some(match n {
242        1 | 2 => (MO_SA, "Monday to Saturday"),
243        3 | 24 | 40 | 41 => (&[Sa], "Saturday"),
244        22 => (&[Tu], "Tuesday"),
245        23 => (&[Fr], "Friday"),
246        25 => (&[We], "Wednesday"),
247        20 | 21 | 26..=39 => (MO_FR, "Monday to Friday"),
248        _ => return None,
249    })
250}
251
252fn zeitfenster(r: &mut Report, t: Wunschtermin, datum: Date) {
253    if let Some(z) = t.zeitfenster
254        && let Some((days, name)) = weekdays(z)
255        && !days.contains(&datum.weekday())
256    {
257        r.error(
258            format!("{WUNSCH}/zeitfenster"),
259            "spri.zeitfenster.weekday",
260            format!("Zeitfenster {z} is for {name}; {datum} is a {:?}", datum.weekday()),
261            "AH 2.9.5 §3.3; XSD 4.00.03 ZeitfensterType",
262            Some(Meldungscode::C1032),
263        );
264    }
265}
266
267/// The date the order asks for: the wish date of a standard order, the new date of a
268/// Terminverschiebung (`terminNeu`, else the wish date); none for a Storno or a diagnosis.
269fn requested(a: &Auftrag) -> Option<(Date, &'static str)> {
270    let t = wunschtermin(&a.geschaeftsfall)?;
271    match a.aenderungskennzeichen {
272        Aenderungskennzeichen::Standard => {
273            Some((t.datum, "auftrag/geschaeftsfall/termine/auftraggeberWunschtermin/datum"))
274        }
275        Aenderungskennzeichen::Terminverschiebung => Some(match a.termin_neu {
276            Some(d) => (d, "auftrag/terminNeu"),
277            None => (t.datum, "auftrag/geschaeftsfall/termine/auftraggeberWunschtermin/datum"),
278        }),
279        Aenderungskennzeichen::Storno => None,
280    }
281}
282
283impl Auftrag {
284    /// Checks the order on its own: Änderungskennzeichen, Geschäftsfallart, Auftragsklammer,
285    /// Zeitfenster and identifiers (see the [module rules](crate::validate)).
286    #[must_use]
287    pub fn issues(&self) -> Vec<Issue> {
288        let mut r = Report::default();
289        let fall = self.geschaeftsfall.code();
290        auftragstyp(&mut r, "auftrag", fall, self.aenderungskennzeichen, self.geschaeftsfall_art, true);
291        if self.termin_neu.is_some() && self.aenderungskennzeichen != Aenderungskennzeichen::Terminverschiebung {
292            r.warn(
293                "auftrag/terminNeu",
294                "spri.termin-neu.only-tv",
295                format!("terminNeu is given only with a Terminverschiebung, not with {}", self.aenderungskennzeichen),
296                "XSD 4.00.03 AuftragType",
297                None,
298            );
299        }
300        if let Some(k) = self.kenner.as_ref().and_then(|k| k.auftragskenner.as_ref()) {
301            if !(1..=20).contains(&k.anzahl_auftraege) {
302                r.error(
303                    "auftrag/kenner/auftragskenner/anzahlAuftraege",
304                    "spri.auftragsklammer.count",
305                    format!("an Auftragsklammer holds 1 to 20 orders, not {}", k.anzahl_auftraege),
306                    "S/PRI 4.4 §4.3.3; AH 2.9.5 §3.7",
307                    None,
308                );
309            }
310            if !matches!(
311                fall,
312                GeschaeftsfallCode::Neu
313                    | GeschaeftsfallCode::AenLmae
314                    | GeschaeftsfallCode::Lae
315                    | GeschaeftsfallCode::Pv
316            ) {
317                r.error(
318                    "auftrag/kenner/auftragskenner",
319                    "spri.auftragsklammer.case",
320                    format!("{fall} orders are not bracketed; only NEU, AEN-LMAE, LAE and PV"),
321                    "AH 2.9.5 §3.7; S/PRI 4.4 §4.3.3",
322                    None,
323                );
324            }
325        }
326        if let (Some(t), Some((datum, _))) = (wunschtermin(&self.geschaeftsfall), requested(self)) {
327            zeitfenster(&mut r, *t, datum);
328        }
329        if let Geschaeftsfall::KueAg(k) = &self.geschaeftsfall
330            && k.vorabstimmungs_id.is_some()
331            && k.fttx.as_ref().and_then(|w| w.wita_vertragsnummer.as_ref()).is_none()
332        {
333            r.warn(
334                "auftrag/geschaeftsfall/auftragsposition/geschaeftsfallProdukt/witaVertragsnummer",
335                "spri.kue-ag.wita-vertragsnummer",
336                "a KUE-AG for a provider switch names the Vorabstimmungs-ID and the WITA contract number",
337                "S/PRI 4.4 §5.2.1.4",
338                None,
339            );
340        }
341        if let (Some(line), Some(va)) = (self.geschaeftsfall.line_id(), self.geschaeftsfall.vorabstimmungs_id())
342            && line.as_str() == va.as_str()
343        {
344            r.error(
345                "auftrag/geschaeftsfall/lineId",
346                "spri.line-id.va-id",
347                "the LineID repeats the Vorabstimmungs-ID; line codes and pre-agreement ids are distinct ranges",
348                "LineID V1.4 §3.1.3",
349                Some(Meldungscode::C8144),
350            );
351        }
352        r.0
353    }
354
355    /// Checks the order as sent at `now`: [`Auftrag::issues`] plus the rules on the requested
356    /// date (of a standard order, or the new date of a Terminverschiebung): not in the past,
357    /// at most 180 days ahead, on a working day of `calendar`.
358    #[must_use]
359    pub fn issues_at(&self, now: Timestamp, calendar: &Calendar) -> Vec<Issue> {
360        let mut r = Report(self.issues());
361        let Some((datum, path)) = requested(self) else { return r.0 };
362        let fall = self.geschaeftsfall.code();
363        let today = day_of(now);
364        if datum < today {
365            let (code, source) = if fall == GeschaeftsfallCode::Est {
366                (Meldungscode::C7014, "AH 2.9.5 §6.4 (7014)")
367            } else {
368                (Meldungscode::C1003, "AH 2.9.5 §6.4 (1003)")
369            };
370            r.error(
371                path,
372                "spri.termin.past",
373                format!("the date {datum} is before the day of sending, {today}"),
374                source,
375                Some(code),
376            );
377        }
378        if let Ok(limit) = today.checked_add(180.days())
379            && datum > limit
380        {
381            r.warn(
382                path,
383                "spri.termin.horizon",
384                format!("the date {datum} is more than 180 days ahead (after {limit}); only Konnektivität orders with a pre-agreement may"),
385                "S/PRI 4.4 §2, §5.1.4",
386                Some(Meldungscode::C1003),
387            );
388        }
389        if fall != GeschaeftsfallCode::Est
390            && let Some(why) = calendar.closed(datum)
391        {
392            r.warn(
393                path,
394                "spri.termin.working-day",
395                format!("the date {datum} is not a working day ({why}); the network owner moves it"),
396                "AH 2.9.5 §6.4 (0002)",
397                Some(Meldungscode::C0002),
398            );
399        }
400        r.0
401    }
402
403    /// Checks a follow-up order against the `original` it refers to: [`Auftrag::issues`] plus,
404    /// for a Storno, a Terminverschiebung or an EST Reklamation, the same order number and
405    /// business case, what may change and the new date; for any other standard order, that it
406    /// does not reuse the original's order number.
407    #[must_use]
408    pub fn issues_against(&self, original: &Self) -> Vec<Issue> {
409        let mut r = Report(self.issues());
410        let reklamation = matches!(&self.geschaeftsfall, Geschaeftsfall::Est(e) if e.reklamation.is_some());
411        let follow_up = self.aenderungskennzeichen != Aenderungskennzeichen::Standard || reklamation;
412        let same_number = self.externe_auftragsnummer == original.externe_auftragsnummer;
413        if !follow_up {
414            if same_number {
415                r.error(
416                    "auftrag/externeAuftragsnummer",
417                    "spri.bezug.repeated",
418                    "a new standard order carries an order number of its own",
419                    "AH 2.9.5 §3.9",
420                    Some(Meldungscode::C1013),
421                );
422            }
423            return r.0;
424        }
425        if !same_number {
426            r.error(
427                "auftrag/externeAuftragsnummer",
428                "spri.bezug.order-number",
429                format!("a {} repeats the order number of the order it refers to", kind(self, reklamation)),
430                "S/PRI 4.4 §5.1.3, §5.1.4, §6.1.5",
431                None,
432            );
433        }
434        let fall = self.geschaeftsfall.code();
435        if fall != original.geschaeftsfall.code() {
436            r.error(
437                "auftrag/geschaeftsfall",
438                "spri.bezug.case",
439                format!(
440                    "a {} keeps the business case: {fall}, original {}",
441                    kind(self, reklamation),
442                    original.geschaeftsfall.code()
443                ),
444                "S/PRI 4.4 §5.1.3, §5.1.4",
445                None,
446            );
447            return r.0;
448        }
449        if original.aenderungskennzeichen != Aenderungskennzeichen::Standard {
450            r.error(
451                "auftrag/aenderungskennzeichen",
452                "spri.bezug.original",
453                format!("the original is a {}, not a standard order", original.aenderungskennzeichen),
454                "AH 2.9.5 §3.4, §3.5",
455                None,
456            );
457        }
458        match self.aenderungskennzeichen {
459            Aenderungskennzeichen::Storno => {
460                let mut mine = self.clone();
461                mine.aenderungskennzeichen = original.aenderungskennzeichen;
462                mine.externe_auftragsnummer.clone_from(&original.externe_auftragsnummer);
463                if mine != *original {
464                    r.warn(
465                        "auftrag",
466                        "spri.storno.identical",
467                        "a Storno is identical to the original order but for the Änderungskennzeichen",
468                        "S/PRI 4.4 §5.1.3, §5.3.1.2, §6.1.2",
469                        None,
470                    );
471                }
472            }
473            Aenderungskennzeichen::Terminverschiebung => tv(&mut r, self, original),
474            Aenderungskennzeichen::Standard => {
475                if with_reklamation_fields_of(self, original) != *original {
476                    r.warn(
477                        "auftrag",
478                        "spri.reklamation.identical",
479                        "a Reklamation is identical to the repair order but for Anlage, contacts, date, Störungsbeschreibung and the Reklamation",
480                        "S/PRI 4.4 §6.1.5",
481                        None,
482                    );
483                }
484            }
485        }
486        r.0
487    }
488}
489
490fn kind(a: &Auftrag, reklamation: bool) -> &'static str {
491    match a.aenderungskennzeichen {
492        Aenderungskennzeichen::Storno => "Storno",
493        Aenderungskennzeichen::Terminverschiebung => "Terminverschiebung",
494        Aenderungskennzeichen::Standard if reklamation => "Reklamation",
495        Aenderungskennzeichen::Standard => "standard order",
496    }
497}
498
499fn tv(r: &mut Report, a: &Auftrag, original: &Auftrag) {
500    let (Some(new), Some(old)) = (wunschtermin(&a.geschaeftsfall), wunschtermin(&original.geschaeftsfall)) else {
501        return;
502    };
503    let datum = a.termin_neu.unwrap_or(new.datum);
504    let path = if a.termin_neu.is_some() {
505        "auftrag/terminNeu"
506    } else {
507        "auftrag/geschaeftsfall/termine/auftraggeberWunschtermin/datum"
508    };
509    if datum == old.datum {
510        r.error(
511            path,
512            "spri.tv.new-date",
513            format!("a Terminverschiebung names a date other than the original {}", old.datum),
514            "S/PRI 4.4 §5.1.4",
515            Some(Meldungscode::C1085),
516        );
517    }
518    if a.geschaeftsfall.code() == GeschaeftsfallCode::Pv && datum < old.datum {
519        r.error(
520            path,
521            "spri.tv.earlier",
522            format!("a PV cannot move earlier than {} after the positive pre-agreement", old.datum),
523            "AH 2.9.5 §3.4",
524            Some(Meldungscode::C1085),
525        );
526    }
527    if new.zeitfenster != old.zeitfenster {
528        r.error(
529            format!("{WUNSCH}/zeitfenster"),
530            "spri.tv.zeitfenster",
531            "a Terminverschiebung keeps the Zeitfenster; another window needs a Storno and a new order",
532            "AH 2.9.5 §3.4",
533            Some(Meldungscode::C1085),
534        );
535    }
536    if with_tv_fields_of(a, original) != *original {
537        r.warn(
538            "auftrag",
539            "spri.tv.identical",
540            "a Terminverschiebung is identical to the original but for date, terminNeu, Anlage, Montageleistung, Seriennummer ONT and Vorabstimmungs-ID",
541            "S/PRI 4.4 §5.1.4",
542            None,
543        );
544    }
545}
546
547/// `a` with the fields a Terminverschiebung may change taken from `original` (S/PRI 4.4
548/// §5.1.4: date, Anlage, Montageleistung; the Seriennummer ONT for the automatic line
549/// identification; the Vorabstimmungs-ID of a Konnektivität order). The Zeitfenster is taken
550/// too: it has its own rule.
551fn with_tv_fields_of(a: &Auftrag, original: &Auftrag) -> Auftrag {
552    let mut a = a.clone();
553    a.aenderungskennzeichen = original.aenderungskennzeichen;
554    a.externe_auftragsnummer.clone_from(&original.externe_auftragsnummer);
555    a.termin_neu = original.termin_neu;
556    match (&mut a.geschaeftsfall, &original.geschaeftsfall) {
557        (Geschaeftsfall::Neu(x), Geschaeftsfall::Neu(o)) => {
558            x.wunschtermin = o.wunschtermin;
559            x.anlage.clone_from(&o.anlage);
560            x.vorabstimmungs_id.clone_from(&o.vorabstimmungs_id);
561            x.fttx.montageleistung.clone_from(&o.fttx.montageleistung);
562            if let (Some(v), Some(ov)) = (&mut x.fttx.vormieter, &o.fttx.vormieter) {
563                v.seriennummer_ont.clone_from(&ov.seriennummer_ont);
564            }
565        }
566        (Geschaeftsfall::KueAg(x), Geschaeftsfall::KueAg(o)) => {
567            x.wunschtermin = o.wunschtermin;
568            x.anlage.clone_from(&o.anlage);
569        }
570        (Geschaeftsfall::Lae(x), Geschaeftsfall::Lae(o)) => {
571            x.wunschtermin = o.wunschtermin;
572            x.anlage.clone_from(&o.anlage);
573        }
574        (Geschaeftsfall::AenLmae(x), Geschaeftsfall::AenLmae(o)) => {
575            x.wunschtermin = o.wunschtermin;
576            x.anlage.clone_from(&o.anlage);
577        }
578        (Geschaeftsfall::Est(x), Geschaeftsfall::Est(o)) => {
579            x.wunschtermin = o.wunschtermin;
580            x.anlage.clone_from(&o.anlage);
581        }
582        (Geschaeftsfall::Pv(x), Geschaeftsfall::Pv(o)) => {
583            x.wunschtermin = o.wunschtermin;
584            x.anlage.clone_from(&o.anlage);
585            x.fttx.montageleistung.clone_from(&o.fttx.montageleistung);
586        }
587        _ => {}
588    }
589    a
590}
591
592/// `a` with the fields a Reklamation may change taken from the repair order `original`
593/// (S/PRI 4.4 §6.1.5: Anlagen, Ansprechpartner, Kontakt Endkunde, Termin,
594/// Störungsbeschreibung; and the Reklamation itself).
595fn with_reklamation_fields_of(a: &Auftrag, original: &Auftrag) -> Auftrag {
596    let mut a = a.clone();
597    a.externe_auftragsnummer.clone_from(&original.externe_auftragsnummer);
598    if let (Geschaeftsfall::Est(x), Geschaeftsfall::Est(o)) = (&mut a.geschaeftsfall, &original.geschaeftsfall) {
599        x.anlage.clone_from(&o.anlage);
600        x.ansprechpartner.clone_from(&o.ansprechpartner);
601        x.kontakt_endkunde.clone_from(&o.kontakt_endkunde);
602        x.wunschtermin = o.wunschtermin;
603        x.stoerungsbeschreibung.clone_from(&o.stoerungsbeschreibung);
604        x.reklamation.clone_from(&o.reklamation);
605    }
606    a
607}
608
609// -- messages --------------------------------------------------------------------------------
610
611/// The codes whose text is a free text of the network owner (AH 2.9.5 §6.4).
612const FREITEXT: [&str; 3] = ["1312", "8600", "8601"];
613
614fn position_path(i: usize) -> String {
615    format!("meldung/meldungstyp/meldungspositionen/position[{}]", i.saturating_add(1))
616}
617
618impl Meldung {
619    /// Checks the message: each code against the code table (AH 2.9.5 §6.4) for this message
620    /// type and business case, the Änderungskennzeichen and Geschäftsfallart, and the
621    /// attributes a code requires (see the [module rules](crate::validate)).
622    #[must_use]
623    pub fn issues(&self) -> Vec<Issue> {
624        let mut r = Report::default();
625        let Auftragstyp { geschaeftsfall: fall, aenderungskennzeichen, geschaeftsfallart } = self.auftragstyp;
626        auftragstyp(&mut r, "meldung", fall, aenderungskennzeichen, geschaeftsfallart, false);
627        let typ = self.typ();
628        let positions = positions(&self.inhalt);
629        for (i, p) in positions.iter().enumerate() {
630            let path = format!("{}/meldungscode", position_path(i));
631            let code = &p.code;
632            if code.text().is_none() {
633                r.warn(
634                    path,
635                    "spri.code.unknown",
636                    "the code is not in the published list (AH 2.9.5 §6.3); later codes come from the online list",
637                    "AH 2.9.5 §6.3; S/PRI 4.4 §11.2.4",
638                    None,
639                );
640            } else if !code.applies(typ, fall) {
641                r.error(
642                    path,
643                    "spri.code.applicability",
644                    format!("{} is not used in a {typ} of {fall}", code.as_str()),
645                    SRC_FACTS,
646                    None,
647                );
648            }
649            if FREITEXT.contains(&code.as_str()) {
650                let text = p.text.as_str().trim();
651                if text.is_empty() || code.text().is_some_and(|official| official == text) {
652                    r.warn(
653                        format!("{}/meldungstext", position_path(i)),
654                        "spri.code.freitext",
655                        format!("{} carries the network owner's own text, not the placeholder", code.as_str()),
656                        "AH 2.9.5 §6.4 (1312, 8600, 8601)",
657                        None,
658                    );
659                }
660            }
661        }
662        if let Some(i) = positions.iter().position(|p| p.code == Meldungscode::C1312)
663            && !positions.iter().any(|p| matches!(p.code, Meldungscode::C1310 | Meldungscode::C1311))
664        {
665            r.error(
666                format!("{}/meldungscode", position_path(i)),
667                "spri.code.1312",
668                "1312 only adds to 1310 or 1311 in the same message",
669                "AH 2.9.5 §6.4 (1312)",
670                None,
671            );
672        }
673        match &self.inhalt {
674            Meldungsinhalt::Vzm(v) => vzm(&mut r, v),
675            Meldungsinhalt::Abbm(a) => abbm(&mut r, a),
676            Meldungsinhalt::RuemPv(m) => ruem_pv(&mut r, m),
677            _ => {}
678        }
679        r.0
680    }
681}
682
683fn positions(m: &Meldungsinhalt) -> Vec<&Position> {
684    fn plain(p: &[Position]) -> Vec<&Position> {
685        p.iter().collect()
686    }
687    fn wita(p: &[crate::PositionWita]) -> Vec<&Position> {
688        p.iter().map(|p| &p.position).collect()
689    }
690    match m {
691        Meldungsinhalt::Qeb(x) => x.positionen.iter().map(|p| &p.position).collect(),
692        Meldungsinhalt::Abm(x) => x.positionen.iter().map(|p| &p.position.position).collect(),
693        Meldungsinhalt::Abbm(x) => wita(&x.positionen),
694        Meldungsinhalt::Erlm(x) => wita(&x.positionen),
695        Meldungsinhalt::Vzm(x) => wita(&x.positionen),
696        Meldungsinhalt::Tam(x) | Meldungsinhalt::Mtam(x) => wita(&x.positionen),
697        Meldungsinhalt::Entm(x) => plain(&x.positionen),
698        Meldungsinhalt::Kdle(x) => plain(&x.positionen),
699        Meldungsinhalt::ZwmLe(x) => plain(&x.positionen),
700        Meldungsinhalt::ZwmAg(x) => plain(&x.positionen),
701        Meldungsinhalt::TbkLe(x) | Meldungsinhalt::TbkAg(x) => plain(&x.positionen),
702        Meldungsinhalt::AkmPv(x) => plain(&x.positionen),
703        Meldungsinhalt::RuemPv(x) => plain(&x.positionen),
704        Meldungsinhalt::AbmPv(x) => plain(&x.positionen),
705        Meldungsinhalt::ErlmPv(x) => plain(&x.positionen),
706        Meldungsinhalt::EntmPv(x) => plain(&x.positionen),
707        Meldungsinhalt::AbbmPv(x) => plain(&x.positionen),
708        Meldungsinhalt::ErlmK(x) => plain(&x.positionen),
709    }
710}
711
712/// The first of `codes` among the positions, as written (only known codes are passed).
713fn has<'a>(p: &'a [crate::PositionWita], codes: &[Meldungscode]) -> Option<&'a str> {
714    p.iter().find(|p| codes.contains(&p.position.code)).map(|p| p.position.code.as_str())
715}
716
717fn vzm(r: &mut Report, v: &Vzm) {
718    if v.verzoegerungstermin.is_none()
719        && let Some(code) = has(&v.positionen, &[Meldungscode::C1576, Meldungscode::C1580, Meldungscode::C1581])
720    {
721        r.error(
722            "meldung/meldungstyp/meldungsattribute/verzoegerungstermin",
723            "spri.vzm.verzoegerungstermin",
724            format!("a VZM with {code} names the appointment in verzoegerungstermin"),
725            "AH 2.9.5 §6.4 (1576, 1580, 1581)",
726            None,
727        );
728    }
729}
730
731fn abbm(r: &mut Report, a: &Abbm) {
732    if a.wiedervorlagetermin.is_none()
733        && let Some(code) = has(&a.positionen, &[Meldungscode::C1006, Meldungscode::C1012])
734    {
735        r.warn(
736            "meldung/meldungstyp/meldungsattribute/wiedervorlagetermin",
737            "spri.abbm.erledigungstermin",
738            format!("an ABBM {code} gives the completion date of the open order (in wiedervorlagetermin)"),
739            "AH 2.9.5 §6.4 (1006, 1012)",
740            None,
741        );
742    }
743    if a.abgebender_provider.as_ref().and_then(|p| p.providername.as_ref()).is_none()
744        && let Some(code) = has(&a.positionen, &[Meldungscode::C0041, Meldungscode::C0042])
745    {
746        r.error(
747            "meldung/meldungstyp/meldungsattribute/abgebenderProvider/providername",
748            "spri.abbm.abgebender-provider",
749            format!("an ABBM {code} names the losing provider"),
750            "AH 2.9.5 §6.4 (0041, 0042)",
751            None,
752        );
753    }
754}
755
756fn ruem_pv(r: &mut Report, m: &RuemPv) {
757    const PATH: &str = "meldung/meldungstyp/meldungsattribute/abgebenderProvider/antwortcode";
758    const SRC: &str = "S/PRI 4.4 §5.5.1.1; AH 2.9.5 §6.5";
759    let p = &m.abgebender_provider;
760    match (p.zustimmung, &p.antwortcode) {
761        (JaNein::Nein, None) => r.error(
762            PATH,
763            "spri.ruem-pv.antwortcode-missing",
764            "a refusing RUEM-PV gives its reason (LnB, KVE, TAV, VnB or Vnv)",
765            "S/PRI 4.4 §5.5.1.1",
766            None,
767        ),
768        (JaNein::Nein, Some(c)) if !is_refusal_code(c) => r.error(
769            PATH,
770            "spri.ruem-pv.antwortcode-known",
771            "a RUEM-PV refuses only for LnB, KVE, TAV, VnB or Vnv",
772            SRC,
773            None,
774        ),
775        (JaNein::Ja, Some(c)) if is_refusal_code(c) => r.error(
776            PATH,
777            "spri.ruem-pv.contradiction",
778            "a consenting RUEM-PV carries no refusal reason; the network owner reads it as a refusal",
779            SRC,
780            None,
781        ),
782        _ => {}
783    }
784}
785
786impl Teq {
787    /// Checks a receipt: only receipt codes (`OK`, `0990`, `0991`, `0993`, `0995`, `0999`), and
788    /// `OK` never together with an error code.
789    #[must_use]
790    pub fn issues(&self) -> Vec<Issue> {
791        let mut r = Report::default();
792        for (i, p) in self.positionen.iter().enumerate() {
793            if !p.code.meldungstypen().any(|t| t == Meldungstyp::Teq) {
794                r.error(
795                    format!("quittung/meldungspositionen/position[{}]/meldungscode", i.saturating_add(1)),
796                    "spri.teq.code",
797                    // An unknown code comes from the peer: it is not echoed.
798                    match p.code.text() {
799                        Some(_) => {
800                            format!("{} is not a receipt code (OK, 0990, 0991, 0993, 0995, 0999)", p.code.as_str())
801                        }
802                        None => "the code is not a receipt code (OK, 0990, 0991, 0993, 0995, 0999)".to_owned(),
803                    },
804                    SRC_FACTS,
805                    None,
806                );
807            }
808        }
809        if self.positionen.iter().any(|p| p.code.is_ok()) && self.positionen.iter().any(|p| !p.code.is_ok()) {
810            r.error(
811                "quittung/meldungspositionen",
812                "spri.teq.mixed",
813                "a receipt is either OK or an error, not both",
814                "S/PRI 4.4 §11.2.3.1",
815                None,
816            );
817        }
818        r.0
819    }
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use crate::{Antwortcode, Kenner, Meldungstext, Payload, Vertragsnummer, Wunschtermin, Zeitfenster};
826
827    fn payload(name: &str) -> Payload {
828        let path = format!("{}/tests/fixtures/{name}.xml", env!("CARGO_MANIFEST_DIR"));
829        Payload::from_xml(&std::fs::read(path).unwrap()).unwrap()
830    }
831
832    fn order(name: &str) -> Auftrag {
833        let Payload::AuftragRequest { auftrag, .. } = payload(name) else { panic!("{name}") };
834        auftrag
835    }
836
837    fn message(name: &str) -> Meldung {
838        let Payload::MeldungRequest { meldung, .. } = payload(name) else { panic!("{name}") };
839        meldung
840    }
841
842    fn date(s: &str) -> Date {
843        s.parse().unwrap()
844    }
845
846    fn at(s: &str) -> Timestamp {
847        s.parse().unwrap()
848    }
849
850    /// The issues `after` adds to `before`, by rule.
851    fn added(before: &[Issue], after: &[Issue]) -> Vec<Issue> {
852        after.iter().filter(|i| !before.iter().any(|b| b.rule == i.rule && b.path == i.path)).cloned().collect()
853    }
854
855    /// Exactly one new issue: `rule` with `severity` and `code`.
856    #[track_caller]
857    fn only(before: &[Issue], after: &[Issue], rule: &str, severity: Severity, code: Option<&str>) -> Issue {
858        let new = added(before, after);
859        assert_eq!(new.len(), 1, "expected only {rule}: {new:#?}");
860        let i = new.into_iter().next().unwrap();
861        assert_eq!((i.rule, i.severity), (rule, severity), "{i}");
862        assert_eq!(i.code.as_ref().map(Meldungscode::as_str), code, "{i}");
863        assert!(i.source.contains('§') || i.source.starts_with("XSD"), "source names a clause: {i}");
864        i
865    }
866
867    fn set_termin(a: &mut Auftrag, t: Wunschtermin) {
868        match &mut a.geschaeftsfall {
869            Geschaeftsfall::Neu(x) => x.wunschtermin = t,
870            Geschaeftsfall::KueAg(x) => x.wunschtermin = t,
871            Geschaeftsfall::Lae(x) => x.wunschtermin = t,
872            Geschaeftsfall::AenLmae(x) => x.wunschtermin = t,
873            Geschaeftsfall::Est(x) => x.wunschtermin = t,
874            Geschaeftsfall::Pv(x) => x.wunschtermin = t,
875            Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => panic!("no date"),
876        }
877    }
878
879    // -- orders on their own --------------------------------------------------------------
880
881    #[test]
882    fn order_fixtures_have_no_error() {
883        for name in ["neu", "kue-ag", "lae", "aen-lmae", "est", "pv", "get", "set"] {
884            let a = order(&format!("auftrag-{name}"));
885            assert!(a.issues().iter().all(|i| i.severity == Severity::Warning), "{name}: {:#?}", a.issues());
886        }
887    }
888
889    #[test]
890    fn storno_only_where_the_case_has_one() {
891        for name in ["auftrag-get", "auftrag-set"] {
892            let mut a = order(name);
893            let before = a.issues();
894            a.aenderungskennzeichen = Aenderungskennzeichen::Storno;
895            let i = only(&before, &a.issues(), "spri.aekz.storno", Severity::Error, Some("1007"));
896            assert_eq!(i.path, "auftrag/aenderungskennzeichen");
897        }
898        for name in ["auftrag-neu", "auftrag-kue-ag", "auftrag-lae", "auftrag-aen-lmae", "auftrag-pv"] {
899            let mut a = order(name);
900            let before = a.issues();
901            a.aenderungskennzeichen = Aenderungskennzeichen::Storno;
902            assert!(added(&before, &a.issues()).iter().all(|i| i.rule != "spri.aekz.storno"), "{name}");
903        }
904    }
905
906    #[test]
907    fn terminverschiebung_only_in_neu_kue_ag_lae_pv() {
908        for name in ["auftrag-aen-lmae", "auftrag-est", "auftrag-get", "auftrag-set"] {
909            let mut a = order(name);
910            let before = a.issues();
911            a.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
912            only(&before, &a.issues(), "spri.aekz.terminverschiebung", Severity::Error, Some("1007"));
913        }
914        let mut a = order("auftrag-lae");
915        a.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
916        assert!(a.issues().is_empty(), "{:#?}", a.issues());
917    }
918
919    #[test]
920    fn termin_neu_only_with_terminverschiebung() {
921        let mut a = order("auftrag-lae");
922        let before = a.issues();
923        a.termin_neu = Some(date("2027-01-20"));
924        only(&before, &a.issues(), "spri.termin-neu.only-tv", Severity::Warning, None);
925        a.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
926        assert!(a.issues().is_empty());
927    }
928
929    #[test]
930    fn geschaeftsfallart_belongs_to_the_case() {
931        let mut a = order("auftrag-pv");
932        let before = a.issues();
933        a.geschaeftsfall_art = GeschaeftsfallArt::Diagnose;
934        only(&before, &a.issues(), "spri.geschaeftsfallart.match", Severity::Error, None);
935        a.geschaeftsfall_art = GeschaeftsfallArt::Bereitstellung;
936        assert!(a.issues().is_empty());
937    }
938
939    #[test]
940    fn auftragsklammer_size_and_cases() {
941        let mut a = order("auftrag-neu");
942        let before = a.issues();
943        for n in [0, 21, -1] {
944            if let Some(k) = a.kenner.as_mut().and_then(|k| k.auftragskenner.as_mut()) {
945                k.anzahl_auftraege = n;
946            }
947            only(&before, &a.issues(), "spri.auftragsklammer.count", Severity::Error, None);
948        }
949        let mut k = order("auftrag-kue-ag");
950        let before = k.issues();
951        k.kenner = order("auftrag-neu").kenner;
952        only(&before, &k.issues(), "spri.auftragsklammer.case", Severity::Error, None);
953        k.kenner = Some(Kenner::default());
954        assert_eq!(k.issues(), before);
955    }
956
957    #[test]
958    fn zeitfenster_fits_the_weekday() {
959        let mut a = order("auftrag-pv");
960        let before = a.issues();
961        // 2027-01-15 is a Friday.
962        set_termin(&mut a, Wunschtermin { datum: date("2027-01-15"), zeitfenster: Some(Zeitfenster::SAMSTAGS) });
963        let i = only(&before, &a.issues(), "spri.zeitfenster.weekday", Severity::Error, Some("1032"));
964        assert!(i.path.ends_with("auftraggeberWunschtermin/zeitfenster"), "{i}");
965        for (z, d, ok) in [
966            ("22", "2027-01-19", true),
967            ("22", "2027-01-15", false),
968            ("1", "2027-01-16", true),
969            ("1", "2027-01-17", false),
970            ("30", "2027-01-16", false),
971            ("50", "2027-01-17", true),
972        ] {
973            set_termin(&mut a, Wunschtermin { datum: date(d), zeitfenster: Some(Zeitfenster::new(z).unwrap()) });
974            assert_eq!(a.issues().is_empty(), ok, "ZF {z} on {d}");
975        }
976    }
977
978    #[test]
979    fn kue_ag_for_a_switch_names_the_wita_contract() {
980        let mut a = order("auftrag-kue-ag");
981        let before = a.issues();
982        if let Geschaeftsfall::KueAg(k) = &mut a.geschaeftsfall {
983            k.fttx = None;
984        }
985        only(&before, &a.issues(), "spri.kue-ag.wita-vertragsnummer", Severity::Warning, None);
986    }
987
988    #[test]
989    fn line_id_is_not_the_vorabstimmungs_id() {
990        let mut a = order("auftrag-pv");
991        let before = a.issues();
992        if let Geschaeftsfall::Pv(p) = &mut a.geschaeftsfall {
993            p.line_id = p.vorabstimmungs_id.as_str().parse().unwrap();
994        }
995        only(&before, &a.issues(), "spri.line-id.va-id", Severity::Error, Some("8144"));
996    }
997
998    // -- dates ------------------------------------------------------------------------------
999
1000    #[test]
1001    fn date_in_the_past() {
1002        let cal = Calendar::werktage();
1003        let a = order("auftrag-pv");
1004        let before = a.issues_at(at("2027-01-14T12:00:00Z"), &cal);
1005        assert!(before.is_empty(), "{before:#?}");
1006        only(
1007            &before,
1008            &a.issues_at(at("2027-01-16T12:00:00Z"), &cal),
1009            "spri.termin.past",
1010            Severity::Error,
1011            Some("1003"),
1012        );
1013        // The day counts in Berlin: 22:30 UTC is still the 15th, 23:30 UTC already the 16th.
1014        assert!(a.issues_at(at("2027-01-15T22:30:00Z"), &cal).is_empty());
1015        assert!(a.issues_at(at("2027-01-15T23:30:00Z"), &cal).iter().any(|i| i.rule == "spri.termin.past"));
1016        let est = order("auftrag-est");
1017        let before = est.issues_at(at("2026-11-23T08:00:00Z"), &cal);
1018        only(
1019            &before,
1020            &est.issues_at(at("2026-11-25T08:00:00Z"), &cal),
1021            "spri.termin.past",
1022            Severity::Error,
1023            Some("7014"),
1024        );
1025    }
1026
1027    #[test]
1028    fn past_date_of_a_terminverschiebung_is_its_new_date() {
1029        let cal = Calendar::werktage();
1030        let mut a = order("auftrag-pv");
1031        a.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
1032        a.termin_neu = Some(date("2027-01-20"));
1033        let now = at("2027-01-18T08:00:00Z");
1034        assert!(a.issues_at(now, &cal).is_empty(), "{:#?}", a.issues_at(now, &cal));
1035        a.termin_neu = Some(date("2027-01-16"));
1036        let i = only(&[], &a.issues_at(now, &cal), "spri.termin.past", Severity::Error, Some("1003"));
1037        assert_eq!(i.path, "auftrag/terminNeu");
1038        // A Storno asks for no date.
1039        a.aenderungskennzeichen = Aenderungskennzeichen::Storno;
1040        a.termin_neu = None;
1041        assert!(a.issues_at(at("2028-01-01T08:00:00Z"), &cal).iter().all(|i| !i.rule.starts_with("spri.termin.")));
1042    }
1043
1044    #[test]
1045    fn date_at_most_180_days_ahead() {
1046        let cal = Calendar::werktage();
1047        let a = order("auftrag-pv");
1048        // 2027-01-15 is 181 days after 2026-07-18, 180 after 2026-07-19.
1049        assert!(a.issues_at(at("2026-07-19T08:00:00Z"), &cal).is_empty());
1050        only(
1051            &[],
1052            &a.issues_at(at("2026-07-18T08:00:00Z"), &cal),
1053            "spri.termin.horizon",
1054            Severity::Warning,
1055            Some("1003"),
1056        );
1057    }
1058
1059    #[test]
1060    fn date_on_a_working_day() {
1061        let cal = Calendar::werktage();
1062        let mut a = order("auftrag-pv");
1063        set_termin(&mut a, Wunschtermin::from(date("2027-01-17"))); // a Sunday
1064        let i = only(
1065            &[],
1066            &a.issues_at(at("2027-01-04T08:00:00Z"), &cal),
1067            "spri.termin.working-day",
1068            Severity::Warning,
1069            Some("0002"),
1070        );
1071        assert!(!i.message.contains("Mustermann"));
1072    }
1073
1074    // -- follow-up orders --------------------------------------------------------------------
1075
1076    fn follow(a: &Auftrag, aekz: Aenderungskennzeichen) -> Auftrag {
1077        Auftrag { aenderungskennzeichen: aekz, ..a.clone() }
1078    }
1079
1080    #[test]
1081    fn storno_against_its_original() {
1082        let pv = order("auftrag-pv");
1083        let s = follow(&pv, Aenderungskennzeichen::Storno);
1084        assert!(s.issues_against(&pv).is_empty(), "{:#?}", s.issues_against(&pv));
1085        let mut other = s.clone();
1086        set_termin(
1087            &mut other,
1088            Wunschtermin { datum: date("2027-01-22"), zeitfenster: Some(Zeitfenster::WERKTAGS_VORMITTAG) },
1089        );
1090        only(&[], &other.issues_against(&pv), "spri.storno.identical", Severity::Warning, None);
1091        let mut number = s.clone();
1092        number.externe_auftragsnummer = crate::ExterneAuftragsnummer::new("A-2026-0002").unwrap();
1093        only(&[], &number.issues_against(&pv), "spri.bezug.order-number", Severity::Error, None);
1094        let lae = follow(&order("auftrag-lae"), Aenderungskennzeichen::Storno);
1095        only(&lae.issues(), &lae.issues_against(&pv), "spri.bezug.case", Severity::Error, None);
1096        let original_tv = follow(&pv, Aenderungskennzeichen::Terminverschiebung);
1097        only(&[], &s.issues_against(&original_tv), "spri.bezug.original", Severity::Error, None);
1098    }
1099
1100    #[test]
1101    fn a_new_order_does_not_reuse_an_order_number() {
1102        let pv = order("auftrag-pv");
1103        let lae = order("auftrag-lae");
1104        only(&[], &lae.issues_against(&pv), "spri.bezug.repeated", Severity::Error, Some("1013"));
1105        let mut fresh = lae;
1106        fresh.externe_auftragsnummer = crate::ExterneAuftragsnummer::new("A-2026-0002").unwrap();
1107        assert!(fresh.issues_against(&pv).is_empty());
1108    }
1109
1110    #[test]
1111    fn terminverschiebung_against_its_original() {
1112        let pv = order("auftrag-pv");
1113        let mut tv = follow(&pv, Aenderungskennzeichen::Terminverschiebung);
1114        only(&[], &tv.issues_against(&pv), "spri.tv.new-date", Severity::Error, Some("1085"));
1115        tv.termin_neu = Some(date("2027-01-22"));
1116        assert!(tv.issues_against(&pv).is_empty(), "{:#?}", tv.issues_against(&pv));
1117        tv.termin_neu = Some(date("2027-01-13"));
1118        only(&[], &tv.issues_against(&pv), "spri.tv.earlier", Severity::Error, Some("1085"));
1119        // Earlier is allowed outside PV.
1120        let lae = order("auftrag-lae");
1121        let mut tv_lae = follow(&lae, Aenderungskennzeichen::Terminverschiebung);
1122        tv_lae.termin_neu = Some(date("2027-01-13"));
1123        assert!(tv_lae.issues_against(&lae).is_empty());
1124        // The date in the wish date instead of terminNeu.
1125        let mut tv2 = follow(&pv, Aenderungskennzeichen::Terminverschiebung);
1126        set_termin(
1127            &mut tv2,
1128            Wunschtermin { datum: date("2027-01-22"), zeitfenster: Some(Zeitfenster::WERKTAGS_VORMITTAG) },
1129        );
1130        assert!(tv2.issues_against(&pv).is_empty());
1131        set_termin(
1132            &mut tv2,
1133            Wunschtermin { datum: date("2027-01-22"), zeitfenster: Some(Zeitfenster::WERKTAGS_NACHMITTAG) },
1134        );
1135        only(&[], &tv2.issues_against(&pv), "spri.tv.zeitfenster", Severity::Error, Some("1085"));
1136    }
1137
1138    #[test]
1139    fn terminverschiebung_changes_only_the_allowed_fields() {
1140        let neu = order("auftrag-neu");
1141        let mut tv = follow(&neu, Aenderungskennzeichen::Terminverschiebung);
1142        tv.termin_neu = Some(date("2027-01-27"));
1143        if let Geschaeftsfall::Neu(n) = &mut tv.geschaeftsfall {
1144            n.anlage = None;
1145            n.fttx.montageleistung = None;
1146            n.vorabstimmungs_id = None;
1147        }
1148        let base = tv.issues_against(&neu);
1149        assert!(base.iter().all(|i| i.rule != "spri.tv.identical"), "{base:#?}");
1150        if let Geschaeftsfall::Neu(n) = &mut tv.geschaeftsfall {
1151            n.positionen.clear();
1152        }
1153        only(&base, &tv.issues_against(&neu), "spri.tv.identical", Severity::Warning, None);
1154    }
1155
1156    #[test]
1157    fn reklamation_against_its_repair_order() {
1158        let rek = order("auftrag-est");
1159        let mut original = rek.clone();
1160        if let Geschaeftsfall::Est(e) = &mut original.geschaeftsfall {
1161            e.reklamation = None;
1162            e.wunschtermin = Wunschtermin::from(date("2026-11-10"));
1163            e.anlage = None;
1164        }
1165        assert!(rek.issues_against(&original).is_empty(), "{:#?}", rek.issues_against(&original));
1166        let mut other = rek.clone();
1167        if let Geschaeftsfall::Est(e) = &mut other.geschaeftsfall {
1168            e.vertragsnummer = Vertragsnummer::new("V999").unwrap();
1169        }
1170        only(&[], &other.issues_against(&original), "spri.reklamation.identical", Severity::Warning, None);
1171    }
1172
1173    // -- messages -----------------------------------------------------------------------------
1174
1175    fn with_codes(m: &mut Meldung, codes: &[&str]) {
1176        let ps: Vec<Position> = codes.iter().map(|c| Position::new(Meldungscode::parse(c))).collect();
1177        match &mut m.inhalt {
1178            Meldungsinhalt::Abbm(a) => a.positionen = ps.into_iter().map(Into::into).collect(),
1179            Meldungsinhalt::Vzm(v) => v.positionen = ps.into_iter().map(Into::into).collect(),
1180            Meldungsinhalt::Abm(a) => a.positionen = ps.into_iter().map(Into::into).collect(),
1181            other => panic!("{:?}", other.typ()),
1182        }
1183    }
1184
1185    #[test]
1186    fn message_fixtures_have_no_issue() {
1187        for name in [
1188            "abbm", "abbm-pv", "abm", "abm-pv", "akm-pv", "entm", "entm-pv", "erlm", "erlm-k", "erlm-pv", "kdle",
1189            "mtam", "qeb", "ruem-pv", "tam", "tbk-ag", "tbk-le", "vzm", "zwm-ag", "zwm-le",
1190        ] {
1191            let m = message(&format!("meldung-{name}"));
1192            assert!(m.issues().is_empty(), "{name}: {:#?}", m.issues());
1193        }
1194    }
1195
1196    #[test]
1197    fn a_code_belongs_to_message_type_and_case() {
1198        let mut m = message("meldung-abm");
1199        with_codes(&mut m, &["0041"]);
1200        let i = only(&[], &m.issues(), "spri.code.applicability", Severity::Error, None);
1201        assert_eq!(i.path, "meldung/meldungstyp/meldungspositionen/position[1]/meldungscode");
1202        assert!(i.message.contains("0041") && i.message.contains("ABM") && i.message.contains("PV"), "{i}");
1203        let mut m = message("meldung-abbm");
1204        m.auftragstyp.geschaeftsfall = GeschaeftsfallCode::Pv;
1205        m.auftragstyp.geschaeftsfallart = GeschaeftsfallArt::Endkundenanbieterwechsel;
1206        with_codes(&mut m, &["1001"]); // NEU only
1207        only(&[], &m.issues(), "spri.code.applicability", Severity::Error, None);
1208    }
1209
1210    #[test]
1211    fn an_unknown_code_is_a_warning_and_not_echoed() {
1212        let mut m = message("meldung-abbm");
1213        with_codes(&mut m, &["47\u{1b}11"]);
1214        let i = only(&[], &m.issues(), "spri.code.unknown", Severity::Warning, None);
1215        assert!(!i.to_string().contains('\u{1b}'), "{i}");
1216    }
1217
1218    #[test]
1219    fn code_1312_only_with_1310_or_1311() {
1220        let mut m = message("meldung-abbm");
1221        with_codes(&mut m, &["1312"]);
1222        if let Meldungsinhalt::Abbm(a) = &mut m.inhalt {
1223            a.positionen[0].position.text = Meldungstext::new("Hinterhaus").unwrap();
1224        }
1225        only(&[], &m.issues(), "spri.code.1312", Severity::Error, None);
1226        if let Meldungsinhalt::Abbm(a) = &mut m.inhalt {
1227            a.positionen.insert(0, Position::new(Meldungscode::C1311).into());
1228        }
1229        assert!(m.issues().is_empty(), "{:#?}", m.issues());
1230    }
1231
1232    #[test]
1233    fn free_text_codes_carry_a_text() {
1234        let mut m = message("meldung-abbm");
1235        with_codes(&mut m, &["8600"]);
1236        let i = only(&[], &m.issues(), "spri.code.freitext", Severity::Warning, None);
1237        assert!(i.path.ends_with("position[1]/meldungstext"));
1238        if let Meldungsinhalt::Abbm(a) = &mut m.inhalt {
1239            a.positionen[0].position.text = Meldungstext::new("Hausnummer fehlt").unwrap();
1240        }
1241        assert!(m.issues().is_empty());
1242        let mut m = message("meldung-abbm");
1243        with_codes(&mut m, &["8601"]);
1244        if let Meldungsinhalt::Abbm(a) = &mut m.inhalt {
1245            a.positionen[0].position.text = Meldungstext::empty();
1246        }
1247        only(&[], &m.issues(), "spri.code.freitext", Severity::Warning, None);
1248    }
1249
1250    #[test]
1251    fn vzm_codes_with_an_appointment_name_it() {
1252        for code in ["1576", "1580", "1581"] {
1253            let mut m = message("meldung-vzm");
1254            with_codes(&mut m, &[code]);
1255            assert!(m.issues().is_empty(), "{code}");
1256            if let Meldungsinhalt::Vzm(v) = &mut m.inhalt {
1257                v.verzoegerungstermin = None;
1258            }
1259            only(&[], &m.issues(), "spri.vzm.verzoegerungstermin", Severity::Error, None);
1260        }
1261    }
1262
1263    #[test]
1264    fn abbm_for_an_open_order_gives_its_date() {
1265        for code in ["1006", "1012"] {
1266            let mut m = message("meldung-abbm");
1267            with_codes(&mut m, &[code]);
1268            assert!(m.issues().is_empty(), "{code}");
1269            if let Meldungsinhalt::Abbm(a) = &mut m.inhalt {
1270                a.wiedervorlagetermin = None;
1271            }
1272            only(&[], &m.issues(), "spri.abbm.erledigungstermin", Severity::Warning, None);
1273        }
1274    }
1275
1276    #[test]
1277    fn abbm_after_the_losing_provider_names_it() {
1278        let abm = message("meldung-abm");
1279        let Meldungsinhalt::Abm(a) = &abm.inhalt else { panic!() };
1280        for code in ["0041", "0042"] {
1281            let mut m = message("meldung-abbm");
1282            m.auftragstyp = abm.auftragstyp;
1283            with_codes(&mut m, &[code]);
1284            only(&[], &m.issues(), "spri.abbm.abgebender-provider", Severity::Error, None);
1285            if let Meldungsinhalt::Abbm(b) = &mut m.inhalt {
1286                b.abgebender_provider.clone_from(&a.abgebender_provider);
1287            }
1288            assert!(m.issues().is_empty(), "{code}: {:#?}", m.issues());
1289        }
1290    }
1291
1292    #[test]
1293    fn ruem_pv_refusal_reasons() {
1294        let base = message("meldung-ruem-pv");
1295        let case = |zustimmung: JaNein, code: Option<&str>| {
1296            let mut m = base.clone();
1297            if let Meldungsinhalt::RuemPv(r) = &mut m.inhalt {
1298                r.abgebender_provider.zustimmung = zustimmung;
1299                r.abgebender_provider.antwortcode = code.map(|c| Antwortcode::new(c).unwrap());
1300            }
1301            m.issues()
1302        };
1303        assert!(case(JaNein::Ja, None).is_empty());
1304        assert!(case(JaNein::Nein, Some("KVE")).is_empty());
1305        assert!(case(JaNein::Nein, Some("LNB")).is_empty());
1306        only(&[], &case(JaNein::Nein, None), "spri.ruem-pv.antwortcode-missing", Severity::Error, None);
1307        only(&[], &case(JaNein::Nein, Some("XYZ")), "spri.ruem-pv.antwortcode-known", Severity::Error, None);
1308        only(&[], &case(JaNein::Ja, Some("tav")), "spri.ruem-pv.contradiction", Severity::Error, None);
1309    }
1310
1311    #[test]
1312    fn message_aekz_and_art_follow_the_case() {
1313        let mut m = message("meldung-kdle");
1314        m.auftragstyp.aenderungskennzeichen = Aenderungskennzeichen::Storno;
1315        let i = only(&[], &m.issues(), "spri.aekz.storno", Severity::Error, None);
1316        assert_eq!(i.path, "meldung/auftragstyp/aenderungsKennzeichen");
1317        let mut m = message("meldung-kdle");
1318        m.auftragstyp.aenderungskennzeichen = Aenderungskennzeichen::Terminverschiebung;
1319        only(&[], &m.issues(), "spri.aekz.terminverschiebung", Severity::Error, None);
1320        let mut m = message("meldung-kdle");
1321        m.auftragstyp.geschaeftsfallart = GeschaeftsfallArt::Bereitstellung;
1322        only(&[], &m.issues(), "spri.geschaeftsfallart.match", Severity::Error, None);
1323    }
1324
1325    // -- receipts -----------------------------------------------------------------------------
1326
1327    #[test]
1328    fn receipts() {
1329        let ok = Teq::new(Meldungscode::Ok, None, None);
1330        assert!(ok.issues().is_empty());
1331        assert!(Teq::new(Meldungscode::C0995, None, None).issues().is_empty());
1332        let wrong = Teq::new(Meldungscode::C1001, None, None);
1333        let i = only(&[], &wrong.issues(), "spri.teq.code", Severity::Error, None);
1334        assert_eq!(i.path, "quittung/meldungspositionen/position[1]/meldungscode");
1335        let mut mixed = ok;
1336        mixed.positionen.push(Position::new(Meldungscode::C0995));
1337        only(&[], &mixed.issues(), "spri.teq.mixed", Severity::Error, None);
1338    }
1339
1340    #[test]
1341    fn display_names_rule_path_source_and_code() {
1342        let mut a = order("auftrag-get");
1343        a.aenderungskennzeichen = Aenderungskennzeichen::Storno;
1344        assert_eq!(
1345            a.issues()[0].to_string(),
1346            "error [spri.aekz.storno] auftrag/aenderungskennzeichen: GET has no Storno (S/PRI 4.4 §6.2.1.2, §6.2.2.2; Anl. 7 EPK V.13 p.4) → 1007"
1347        );
1348    }
1349}