1use std::fmt;
25
26use crate::{spri, wbci};
27
28const NS_WBCI: &[u8] = b"http://www.vatm.de/wbci/v1/envelope";
30const NS_SPRI: &[u8] = b"http://spri.telekom.de/oss/v4/envelope";
31
32#[must_use]
35pub fn sanitize(s: &str) -> String {
36 s.chars().map(|c| if c.is_control() { '\u{FFFD}' } else { c }).collect()
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub struct Output {
47 pub lines: Vec<String>,
49 pub ok: bool,
51}
52
53impl Output {
54 fn push(&mut self, line: impl fmt::Display) {
55 self.lines.push(sanitize(&line.to_string()));
56 }
57}
58
59impl fmt::Display for Output {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 for (i, line) in self.lines.iter().enumerate() {
62 if i > 0 {
63 f.write_str("\n")?;
64 }
65 f.write_str(line)?;
66 }
67 Ok(())
68 }
69}
70
71#[derive(Debug, Clone, PartialEq)]
73pub enum Payload {
74 Wbci(Box<wbci::Payload>),
76 Spri(Box<spri::Payload>),
78}
79
80impl Payload {
81 pub fn parse(bytes: &[u8]) -> Result<Self, Unreadable> {
89 let wbci_err = match wbci::Payload::from_xml(bytes) {
90 Ok(p) => return Ok(Self::Wbci(Box::new(p))),
91 Err(e) => e,
92 };
93 let spri_err = match spri::Payload::from_xml(bytes) {
94 Ok(p) => return Ok(Self::Spri(Box::new(p))),
95 Err(e) => e,
96 };
97 let names = |ns: &[u8]| bytes.windows(ns.len()).any(|w| w == ns);
98 Err(if names(NS_WBCI) {
99 Unreadable { interface: Some("WBCI"), reason: wbci_err.to_string(), teq: wbci_err.teq_code().to_string() }
100 } else if names(NS_SPRI) {
101 Unreadable { interface: Some("S/PRI"), reason: spri_err.to_string(), teq: spri_err.teq_code().to_string() }
102 } else {
103 Unreadable { interface: None, reason: wbci_err.to_string(), teq: wbci_err.teq_code().to_string() }
104 })
105 }
106
107 #[must_use]
109 pub fn sent_at(&self) -> wbci::Timestamp {
110 match self {
111 Self::Wbci(p) => p.control().zeitstempel.timestamp,
112 Self::Spri(p) => p.control().zeitstempel.timestamp,
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Unreadable {
122 interface: Option<&'static str>,
123 reason: String,
124 teq: String,
125}
126
127impl Unreadable {
128 #[must_use]
131 pub const fn interface(&self) -> Option<&'static str> {
132 self.interface
133 }
134
135 #[must_use]
137 pub fn teq(&self) -> &str {
138 &self.teq
139 }
140}
141
142impl fmt::Display for Unreadable {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 match self.interface {
145 Some(i) => write!(f, "{i}: {} — answer with TEQ {}", self.reason, self.teq),
146 None => write!(f, "neither a WBCI nor an S/PRI payload: {} — answer with TEQ {}", self.reason, self.teq),
147 }
148 }
149}
150
151impl std::error::Error for Unreadable {}
152
153#[must_use]
156pub fn read(bytes: &[u8]) -> Output {
157 let mut out = Output { lines: Vec::new(), ok: true };
158 match Payload::parse(bytes) {
159 Ok(p) => {
160 for (label, value) in summary(&p) {
161 out.push(format_args!("{label}: {value}"));
162 }
163 }
164 Err(e) => {
165 out.ok = false;
166 out.push(format_args!("unreadable: {e}"));
167 }
168 }
169 out
170}
171
172#[must_use]
175pub fn check(bytes: &[u8]) -> Output {
176 let mut out = Output { lines: Vec::new(), ok: true };
177 let payload = match Payload::parse(bytes) {
178 Ok(p) => p,
179 Err(e) => {
180 out.ok = false;
181 out.push(format_args!("unreadable: {e}"));
182 return out;
183 }
184 };
185 let sent_at = payload.sent_at();
187 let (interface, issues): (&str, Vec<(bool, String)>) = match &payload {
188 Payload::Wbci(p) => (
189 "WBCI",
190 match &**p {
191 wbci::Payload::AnfrageRequest { anfrage, .. } => {
192 anfrage.issues_at(sent_at, &wbci::Calendar::wbci()).iter().map(wbci_line).collect()
193 }
194 wbci::Payload::MeldungRequest { meldung, .. } => meldung.issues(None).iter().map(wbci_line).collect(),
195 wbci::Payload::AnfrageResponse { quittung, .. } | wbci::Payload::MeldungResponse { quittung, .. } => {
196 quittung.issues().iter().map(wbci_line).collect()
197 }
198 },
199 ),
200 Payload::Spri(p) => (
201 "S/PRI",
202 match &**p {
203 spri::Payload::AuftragRequest { auftrag, .. } => {
204 auftrag.issues_at(sent_at, &spri::Calendar::werktage()).iter().map(spri_line).collect()
205 }
206 spri::Payload::MeldungRequest { meldung, .. } => meldung.issues().iter().map(spri_line).collect(),
207 spri::Payload::AuftragResponse { quittung, .. } | spri::Payload::MeldungResponse { quittung, .. } => {
208 quittung.issues().iter().map(spri_line).collect()
209 }
210 },
211 ),
212 };
213 if issues.is_empty() {
214 out.push(format_args!("{interface}: no issues"));
215 }
216 for (error, line) in issues {
217 if error {
218 out.ok = false;
219 }
220 out.push(line);
221 }
222 out
223}
224
225fn wbci_line(i: &wbci::Issue) -> (bool, String) {
227 (i.severity == wbci::Severity::Error, i.to_string())
228}
229
230fn spri_line(i: &spri::Issue) -> (bool, String) {
232 (i.severity == spri::Severity::Error, i.to_string())
233}
234
235#[must_use]
239pub fn code(code: &str, in_wbci: bool, in_spri: bool) -> Output {
240 let mut out = Output { lines: Vec::new(), ok: false };
241 if in_wbci {
242 let c = wbci::Meldungscode::parse(code);
243 if c.text().is_some() {
244 out.ok = true;
245 out.push(format_args!("WBCI {c}"));
246 if let Some(short) = c.short() {
247 out.push(format_args!(" short name: {short}"));
248 }
249 let mut typen: Vec<wbci::Meldungstyp> = Vec::new();
250 for t in c.meldungstypen() {
251 if !typen.contains(&t) {
252 typen.push(t);
253 }
254 }
255 for t in typen {
256 let cases: Vec<&str> =
257 wbci::Geschaeftsfall::ALL.iter().filter(|g| c.applies(t, **g)).map(|g| g.as_str()).collect();
258 out.push(format_args!(" {t} in {}", cases.join(", ")));
259 }
260 } else {
261 out.push(format_args!("WBCI: {code} is not a WBCI code"));
262 }
263 }
264 if in_spri {
265 let c = spri::Meldungscode::parse(code);
266 if c.text().is_some() {
267 out.ok = true;
268 out.push(format_args!("S/PRI {c}"));
269 let typen: Vec<&str> = c.meldungstypen().map(spri::Meldungstyp::as_str).collect();
270 if !typen.is_empty() {
271 out.push(format_args!(" message types: {}", typen.join(", ")));
272 }
273 let cases: Vec<&str> = c.geschaeftsfaelle().map(spri::GeschaeftsfallCode::as_str).collect();
274 if !cases.is_empty() {
275 out.push(format_args!(" business cases: {}", cases.join(", ")));
276 }
277 } else {
278 out.push(format_args!("S/PRI: {code} is not an S/PRI code"));
279 }
280 }
281 out
282}
283
284type Lines = Vec<(&'static str, String)>;
288
289fn summary(p: &Payload) -> Lines {
290 match p {
291 Payload::Wbci(p) => wbci_summary(p),
292 Payload::Spri(p) => spri_summary(p),
293 }
294}
295
296fn wbci_summary(p: &wbci::Payload) -> Lines {
297 let mut l: Lines = vec![("interface", "WBCI".to_owned())];
298 match p {
299 wbci::Payload::AnfrageRequest { anfrage, .. } => {
300 l.push(("payload", "request (annehmenAnfrageRequest)".to_owned()));
301 l.push(("kind", anfrage.geschaeftsfall().to_string()));
302 l.push(("sent", p.control().zeitstempel.to_string()));
303 l.push(("sender", format!("{} ({})", anfrage.absender(), anfrage.sender())));
304 ekp(&mut l, anfrage.ekp());
305 l.push(("Vorabstimmungs-ID", anfrage.vorabstimmungs_id().to_string()));
306 match anfrage {
307 wbci::Anfrage::Vorabstimmung(va) => {
308 l.push(("Kundenwunschtermin", va.kundenwunschtermin.to_string()));
309 if !va.weitere_anschlussinhaber.is_empty() {
310 l.push(("further line holders", va.weitere_anschlussinhaber.len().to_string()));
311 }
312 }
313 wbci::Anfrage::Storno(s) => l.push(("Storno-ID", s.storno_id.to_string())),
314 wbci::Anfrage::Terminverschiebung(t) => {
315 l.push(("Änderungs-ID", t.aenderungs_id.to_string()));
316 l.push(("neuer Kundenwunschtermin", t.neuer_kundenwunschtermin.to_string()));
317 }
318 }
319 }
320 wbci::Payload::MeldungRequest { meldung, .. } => {
321 let kopf = meldung.kopf();
322 l.push(("payload", "message (annehmenMeldungRequest)".to_owned()));
323 l.push(("kind", meldung.meldungstyp().to_string()));
324 l.push(("business case", kopf.geschaeftsfall.to_string()));
325 l.push(("sent", p.control().zeitstempel.to_string()));
326 l.push(("sender", sender(&kopf.absender, &kopf.ekp)));
327 ekp(&mut l, &kopf.ekp);
328 l.push(("Vorabstimmungs-ID", kopf.vorabstimmungs_id.to_string()));
329 if let Some(d) = meldung.wechseltermin() {
330 l.push(("Wechseltermin", d.to_string()));
331 }
332 if let Some(id) = meldung.storno_id() {
333 l.push(("Storno-ID", id.to_string()));
334 }
335 if let Some(id) = meldung.aenderungs_id() {
336 l.push(("Änderungs-ID", id.to_string()));
337 }
338 match meldung {
339 wbci::Meldung::AkmTr(t) => {
340 l.push(("Ressourcenübernahme", yes_no(t.ressourcenuebernahme)));
341 l.push(("sicherer Hafen", yes_no(t.sicherer_hafen)));
342 for u in &t.uebernahme_leitung {
343 if let wbci::UebernahmeLeitung::LineId(id) = u {
344 l.push(("LineID taken over", id.to_string()));
345 }
346 }
347 }
348 wbci::Meldung::RuemVa(r) => {
349 for id in r.ressourcen.iter().filter_map(|r| r.line_id.as_ref()) {
350 l.push(("LineID", id.to_string()));
351 }
352 }
353 _ => {}
354 }
355 for c in meldung.codes() {
356 l.push(("code", c.to_string()));
357 }
358 }
359 wbci::Payload::AnfrageResponse { quittung, .. } | wbci::Payload::MeldungResponse { quittung, .. } => {
360 let what = if matches!(p, wbci::Payload::AnfrageResponse { .. }) {
361 "receipt for a request (annehmenAnfrageResponse)"
362 } else {
363 "receipt for a message (annehmenMeldungResponse)"
364 };
365 l.push(("payload", what.to_owned()));
366 l.push(("kind", "TEQ".to_owned()));
367 l.push(("sent", p.control().zeitstempel.to_string()));
368 l.push(("sender", quittung.absender.to_string()));
369 l.push(("Vorabstimmungs-ID", quittung.vorabstimmungs_id.to_string()));
370 if let Some(id) = &quittung.storno_id {
371 l.push(("Storno-ID", id.to_string()));
372 }
373 if let Some(id) = &quittung.aenderungs_id {
374 l.push(("Änderungs-ID", id.to_string()));
375 }
376 for pos in &quittung.positionen {
377 l.push(("code", pos.code.to_string()));
378 }
379 }
380 }
381 l
382}
383
384fn ekp(l: &mut Lines, ekp: &wbci::Ekp) {
385 l.push(("EKPauf", ekp.auf.to_string()));
386 l.push(("EKPabg", ekp.abg.to_string()));
387}
388
389fn sender(absender: &wbci::CarrierCode, ekp: &wbci::Ekp) -> String {
390 match ekp.role_of(absender) {
391 Some(role) => format!("{absender} ({role})"),
392 None => format!("{absender} (neither EKP)"),
393 }
394}
395
396fn yes_no(b: bool) -> String {
397 (if b { "yes" } else { "no" }).to_owned()
398}
399
400fn spri_summary(p: &spri::Payload) -> Lines {
401 let mut l: Lines = vec![("interface", "S/PRI".to_owned())];
402 let sent = p.control().zeitstempel.to_string();
403 match p {
404 spri::Payload::AuftragRequest { auftrag, .. } => {
405 l.push(("payload", "order (annehmenAuftragRequest)".to_owned()));
406 l.push(("kind", auftrag.geschaeftsfall.code().to_string()));
407 l.push(("Änderungskennzeichen", auftrag.aenderungskennzeichen.to_string()));
408 l.push(("sent", sent));
409 l.push(("externe Auftragsnummer", auftrag.externe_auftragsnummer.to_string()));
410 if let Some(id) = auftrag.geschaeftsfall.vorabstimmungs_id() {
411 l.push(("Vorabstimmungs-ID", id.to_string()));
412 }
413 if let Some(id) = auftrag.geschaeftsfall.line_id() {
414 l.push(("LineID", id.to_string()));
415 }
416 if let Some(d) = wunschtermin(&auftrag.geschaeftsfall) {
417 l.push(("Wunschtermin", d.to_string()));
418 }
419 if let Some(d) = auftrag.termin_neu {
420 l.push(("Termin neu", d.to_string()));
421 }
422 }
423 spri::Payload::MeldungRequest { meldung, .. } => {
424 l.push(("payload", "message (annehmenMeldungRequest)".to_owned()));
425 l.push(("kind", meldung.typ().to_string()));
426 let t = meldung.auftragstyp;
427 l.push(("business case", format!("{} ({})", t.geschaeftsfall, t.aenderungskennzeichen)));
428 l.push(("sent", sent));
429 l.push(("externe Auftragsnummer", meldung.externe_auftragsnummer().to_string()));
430 if let Some(id) = meldung.vorabstimmungs_id() {
431 l.push(("Vorabstimmungs-ID", id.to_string()));
432 }
433 if let Some(id) = meldung_line(meldung) {
434 l.push(("LineID", id.to_string()));
435 }
436 for (label, d) in meldung_dates(meldung) {
437 l.push((label, d.to_string()));
438 }
439 for c in meldung.codes() {
440 l.push(("code", c.to_string()));
441 }
442 }
443 spri::Payload::AuftragResponse { quittung, .. } | spri::Payload::MeldungResponse { quittung, .. } => {
444 let what = if matches!(p, spri::Payload::AuftragResponse { .. }) {
445 "receipt for an order (annehmenAuftragResponse)"
446 } else {
447 "receipt for a message (annehmenMeldungResponse)"
448 };
449 l.push(("payload", what.to_owned()));
450 l.push(("kind", "TEQ".to_owned()));
451 l.push(("sent", sent));
452 if let Some(ext) = &quittung.externe_auftragsnummer {
453 l.push(("externe Auftragsnummer", ext.to_string()));
454 }
455 for pos in &quittung.positionen {
456 l.push(("code", pos.code.to_string()));
457 }
458 }
459 }
460 l
461}
462
463const fn wunschtermin(g: &spri::Geschaeftsfall) -> Option<spri::Date> {
465 match g {
466 spri::Geschaeftsfall::Neu(x) => Some(x.wunschtermin.datum),
467 spri::Geschaeftsfall::KueAg(x) => Some(x.wunschtermin.datum),
468 spri::Geschaeftsfall::Lae(x) => Some(x.wunschtermin.datum),
469 spri::Geschaeftsfall::AenLmae(x) => Some(x.wunschtermin.datum),
470 spri::Geschaeftsfall::Est(x) => Some(x.wunschtermin.datum),
471 spri::Geschaeftsfall::Pv(x) => Some(x.wunschtermin.datum),
472 spri::Geschaeftsfall::Get(_) | spri::Geschaeftsfall::Set(_) => None,
473 }
474}
475
476const fn meldung_line(m: &spri::Meldung) -> Option<&spri::LineId> {
477 use spri::Meldungsinhalt as I;
478 match &m.inhalt {
479 I::Abm(x) => Some(&x.anschluss.line_id),
480 I::AkmPv(x) => Some(&x.line_id),
481 I::RuemPv(x) => Some(&x.line_id),
482 I::AbmPv(x) => Some(&x.line_id),
483 _ => None,
484 }
485}
486
487fn meldung_dates(m: &spri::Meldung) -> Vec<(&'static str, spri::Date)> {
488 use spri::Meldungsinhalt as I;
489 match &m.inhalt {
490 I::Abm(x) => vec![("verbindlicher Liefertermin", x.verbindlicher_liefertermin.datum)],
491 I::Abbm(x) => x.wiedervorlagetermin.map(|d| ("Wiedervorlagetermin", d)).into_iter().collect(),
492 I::Erlm(x) => vec![("Erledigungstermin", x.erledigungstermin)],
493 I::Entm(x) => vec![("Entgelttermin", x.entgelttermin)],
494 I::Vzm(x) => x.verzoegerungstermin.map(|d| ("Verzögerungstermin", d)).into_iter().collect(),
495 I::Kdle(x) => vec![("Abschaltungstermin", x.abschaltungstermin)],
496 I::TbkLe(x) | I::TbkAg(x) => vec![("Termin", x.termin.datum)],
497 I::AkmPv(x) => vec![
498 ("Übernahmedatum geplant", x.aufnehmender_provider.uebernahmedatum_geplant),
499 ("Antwortfrist", x.aufnehmender_provider.antwortfrist),
500 ],
501 I::AbmPv(x) => vec![("Übernahmedatum verbindlich", x.aufnehmender_provider.uebernahmedatum_verbindlich)],
502 I::ErlmPv(x) => vec![("Erledigungstermin", x.erledigungstermin)],
503 I::EntmPv(x) => vec![("Entgelttermin", x.entgelttermin)],
504 _ => Vec::new(),
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 fn fixture(interface: &str, name: &str) -> Vec<u8> {
513 let path = format!("{}/../{interface}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
514 std::fs::read(path).unwrap()
515 }
516
517 #[test]
518 fn read_summarises_a_wbci_message() {
519 let out = read(&fixture("wbci", "abbm.xml"));
520 assert!(out.ok);
521 for line in [
522 "interface: WBCI",
523 "kind: ABBM",
524 "business case: VA-KUE-MRN",
525 "Vorabstimmungs-ID: DEU.EKP1.V000000013",
526 "code: 8103 Rufnummer nicht geschaltet (RNG)",
527 ] {
528 assert!(out.lines.iter().any(|l| l == line), "{line} in {out}");
529 }
530 }
531
532 #[test]
533 fn check_of_a_clean_order() {
534 let out = check(&fixture("spri", "auftrag-pv.xml"));
535 assert!(out.ok);
536 assert_eq!(out.lines, ["S/PRI: no issues"]);
537 }
538
539 #[test]
540 fn code_in_both_interfaces() {
541 let out = code("8103", true, true);
542 assert!(out.ok);
543 assert_eq!(out.lines[0], "WBCI 8103 Rufnummer nicht geschaltet (RNG)");
544 assert!(out.lines.contains(&"S/PRI: 8103 is not an S/PRI code".to_owned()), "{out}");
545 assert!(!code("0021", true, false).ok);
546 }
547
548 #[test]
549 fn a_doctype_is_unreadable_with_teq_0995() {
550 let mut xml = b"<!DOCTYPE x [<!ENTITY a \"b\">]>\n".to_vec();
551 xml.extend(fixture("wbci", "abbm.xml"));
552 for out in [read(&xml), check(&xml)] {
553 assert!(!out.ok);
554 assert_eq!(out.lines.len(), 1);
555 assert!(out.lines[0].starts_with("unreadable: WBCI: DOCTYPE"), "{out}");
556 assert!(out.lines[0].contains("answer with TEQ 0995"), "{out}");
557 }
558 assert!(Payload::parse(&xml).unwrap_err().teq().starts_with("0995 "));
559 }
560
561 #[test]
562 fn control_characters_are_replaced() {
563 let xml = String::from_utf8(fixture("wbci", "abbm.xml")).unwrap();
565 let evil = xml.replace("<Meldungscode>8103</Meldungscode>", "<Meldungscode>\u{1b}[2J</Meldungscode>");
566 for out in [read(evil.as_bytes()), check(evil.as_bytes()), code("\u{1b}[2J", true, true)] {
567 let text = out.to_string();
568 assert!(!text.contains('\u{1b}') && text.contains('\u{FFFD}'), "{text:?}");
569 }
570 assert_eq!(sanitize("a\u{0}b\u{7f}c\u{9b}"), "a\u{FFFD}b\u{FFFD}c\u{FFFD}");
571 }
572}