Skip to main content

automapper_validation/validator/
kind.rs

1//! The machine-readable description of what a validation issue *is*.
2//!
3//! Wording lives in [`crate::display`]. A kind carries every fact the wording
4//! needs, so a consumer can say something other than the sentence we ship.
5
6use mig_assembly::StructureDiagnosticKind;
7use serde::{Deserialize, Serialize};
8
9use super::issue::ValidationCategory;
10
11/// Why a condition could not be evaluated.
12///
13/// Any combination of these may be non-empty; each is a list of AHB condition ids.
14#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
15pub struct UnresolvedConditions {
16    /// Need an external provider to answer.
17    pub external: Vec<u32>,
18    /// Not determinable from the message data.
19    pub undetermined: Vec<u32>,
20    /// Not present in the rulebook at all.
21    pub missing: Vec<u32>,
22}
23
24impl UnresolvedConditions {
25    /// True when nothing at all could be attributed — the issue has no detail.
26    pub fn is_empty(&self) -> bool {
27        self.external.is_empty() && self.undetermined.is_empty() && self.missing.is_empty()
28    }
29}
30
31/// What kind of problem a [`ValidationIssue`](super::issue::ValidationIssue) reports.
32///
33/// One variant per problem the validator actually emits. `ErrorCodes` lists 22
34/// code strings, but only these are ever constructed; adding a new check means
35/// adding a variant, which the compiler then forces every narrator to handle.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(tag = "type", rename_all = "camelCase")]
38pub enum IssueKind {
39    /// AHB001 — a field the AHB marks mandatory for this PID is absent.
40    MissingRequiredField { field_name: String },
41    /// AHB002 — a segment group is present although its AHB condition does not
42    /// hold (`Muss [96]` without STS+7 ZAP). `group` is its path (`SG4/SG5`).
43    GroupNotAllowed { group: String },
44    /// AHB002 — a segment is present although its own AHB condition does not
45    /// hold (`CAV+Z56` Wärmenutzung, `Muss [239]`, without CAV+Z65 in its
46    /// SG10). `segment` is its path (`SG4/SG8/SG10/CAV`).
47    SegmentNotAllowed { segment: String },
48    /// AHB003 — the field is present but its AHB condition is not satisfied.
49    FieldConditionNotSatisfied { field_name: String },
50    /// AHB005 — the condition expression could not be fully evaluated.
51    ConditionUnknown {
52        field_name: String,
53        unresolved: UnresolvedConditions,
54    },
55    /// AHB006 — number of codes present in a package is outside `min..max`.
56    PackageCardinality {
57        package_id: String,
58        present: usize,
59        min: usize,
60        max: usize,
61        codes: Vec<String>,
62    },
63    /// COD002 — the value is a valid code but not allowed for this PID.
64    CodeNotAllowedForPid { value: String, allowed: Vec<String> },
65    /// COD003 — a response's answer (AJT 4465, STS C556/9013) is not one of the
66    /// codes of the EBD or Codeliste it names beside it (AJT 1082, C556/1131):
67    /// `AJT+ZB5+G_0059`. The AHB lists which lists may be named; the EBD
68    /// document says what they hold.
69    AnswerNotInList {
70        answer: String,
71        list: String,
72        allowed: Vec<String>,
73    },
74    /// STR007 — UNT's declared segment count disagrees with the actual count.
75    UntSegmentCountMismatch { declared: usize, actual: usize },
76    /// STR007 — the input holds several messages, so the count is not checkable.
77    UntCountNotVerifiable { unh_count: usize },
78    /// STR003 / STR008 — a structure diagnostic raised during assembly.
79    ///
80    /// `detail` carries the diagnostic's own message verbatim: some
81    /// diagnostics (e.g. `mig_assembly::Assembler::assemble_with_diagnostics`'s
82    /// `"Assembly failed: {e}"` case) say something not derivable from
83    /// `(kind, segment_id, position)` alone.
84    StructureDiagnostic {
85        kind: StructureDiagnosticKind,
86        segment_id: String,
87        position: usize,
88        detail: String,
89    },
90}
91
92impl IssueKind {
93    /// The stable machine identifier, unchanged from the former `code` field.
94    pub fn code(&self) -> &'static str {
95        match self {
96            Self::MissingRequiredField { .. } => "AHB001",
97            Self::GroupNotAllowed { .. } | Self::SegmentNotAllowed { .. } => "AHB002",
98            Self::FieldConditionNotSatisfied { .. } => "AHB003",
99            Self::ConditionUnknown { .. } => "AHB005",
100            Self::PackageCardinality { .. } => "AHB006",
101            Self::CodeNotAllowedForPid { .. } => "COD002",
102            Self::AnswerNotInList { .. } => "COD003",
103            Self::UntSegmentCountMismatch { .. } | Self::UntCountNotVerifiable { .. } => "STR007",
104            // One code per kind (#81). An orphaned group segment is a skipped
105            // segment too (its content is equally absent); the kind and
106            // message tell the missing entry segment apart. A segment whose
107            // qualifier no slot at its place accepts is unexpected there.
108            Self::StructureDiagnostic { kind, .. } => match kind {
109                StructureDiagnosticKind::MissingRequiredSegment => "STR001",
110                StructureDiagnosticKind::MaxRepetitionsExceeded => "STR002",
111                StructureDiagnosticKind::UnexpectedSegment
112                | StructureDiagnosticKind::UnrecognizedQualifier => "STR003",
113                StructureDiagnosticKind::MissingRequiredGroup => "STR005",
114                StructureDiagnosticKind::GroupMaxRepetitionsExceeded => "STR006",
115                StructureDiagnosticKind::SkippedUnknownSegment
116                | StructureDiagnosticKind::OrphanedGroupSegment => "STR008",
117            },
118        }
119    }
120
121    /// The issue's category. Derived, so it can never disagree with the kind.
122    pub fn category(&self) -> ValidationCategory {
123        match self {
124            Self::MissingRequiredField { .. }
125            | Self::GroupNotAllowed { .. }
126            | Self::SegmentNotAllowed { .. }
127            | Self::FieldConditionNotSatisfied { .. }
128            | Self::ConditionUnknown { .. }
129            | Self::PackageCardinality { .. } => ValidationCategory::Ahb,
130            Self::CodeNotAllowedForPid { .. } | Self::AnswerNotInList { .. } => {
131                ValidationCategory::Code
132            }
133            Self::UntSegmentCountMismatch { .. }
134            | Self::UntCountNotVerifiable { .. }
135            | Self::StructureDiagnostic { .. } => ValidationCategory::Structure,
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use mig_assembly::StructureDiagnosticKind;
144
145    #[test]
146    fn code_matches_the_legacy_error_code_for_every_kind() {
147        let cases: Vec<(IssueKind, &str)> = vec![
148            (
149                IssueKind::MissingRequiredField {
150                    field_name: "f".into(),
151                },
152                "AHB001",
153            ),
154            (
155                IssueKind::GroupNotAllowed {
156                    group: "SG4/SG5".into(),
157                },
158                "AHB002",
159            ),
160            (
161                IssueKind::SegmentNotAllowed {
162                    segment: "SG4/SG8/SG10/CAV".into(),
163                },
164                "AHB002",
165            ),
166            (
167                IssueKind::FieldConditionNotSatisfied {
168                    field_name: "f".into(),
169                },
170                "AHB003",
171            ),
172            (
173                IssueKind::ConditionUnknown {
174                    field_name: "f".into(),
175                    unresolved: UnresolvedConditions::default(),
176                },
177                "AHB005",
178            ),
179            (
180                IssueKind::PackageCardinality {
181                    package_id: "1P0..1".into(),
182                    present: 2,
183                    min: 0,
184                    max: 1,
185                    codes: vec![],
186                },
187                "AHB006",
188            ),
189            (
190                IssueKind::CodeNotAllowedForPid {
191                    value: "X".into(),
192                    allowed: vec![],
193                },
194                "COD002",
195            ),
196            (
197                IssueKind::AnswerNotInList {
198                    answer: "ZB5".into(),
199                    list: "G_0059".into(),
200                    allowed: vec![],
201                },
202                "COD003",
203            ),
204            (
205                IssueKind::UntSegmentCountMismatch {
206                    declared: 30,
207                    actual: 31,
208                },
209                "STR007",
210            ),
211            (IssueKind::UntCountNotVerifiable { unh_count: 2 }, "STR007"),
212            (
213                IssueKind::StructureDiagnostic {
214                    kind: StructureDiagnosticKind::SkippedUnknownSegment,
215                    segment_id: "CCI".into(),
216                    position: 15,
217                    detail: "irrelevant to the code".into(),
218                },
219                "STR008",
220            ),
221            (
222                IssueKind::StructureDiagnostic {
223                    kind: StructureDiagnosticKind::UnexpectedSegment,
224                    segment_id: "CCI".into(),
225                    position: 15,
226                    detail: "irrelevant to the code".into(),
227                },
228                "STR003",
229            ),
230        ];
231        for (kind, expected) in cases {
232            assert_eq!(kind.code(), expected, "wrong code for {kind:?}");
233        }
234    }
235
236    /// Every structure diagnostic keeps its own code (#81): a repetition
237    /// overrun must not surface as "unexpected segment".
238    #[test]
239    fn each_structure_kind_has_its_own_code() {
240        use StructureDiagnosticKind as K;
241        for (kind, expected) in [
242            (K::MissingRequiredSegment, "STR001"),
243            (K::MaxRepetitionsExceeded, "STR002"),
244            (K::UnexpectedSegment, "STR003"),
245            (K::UnrecognizedQualifier, "STR003"),
246            (K::MissingRequiredGroup, "STR005"),
247            (K::GroupMaxRepetitionsExceeded, "STR006"),
248            (K::SkippedUnknownSegment, "STR008"),
249            (K::OrphanedGroupSegment, "STR008"),
250        ] {
251            let issue = IssueKind::StructureDiagnostic {
252                kind,
253                segment_id: "RFF".into(),
254                position: 1,
255                detail: String::new(),
256            };
257            assert_eq!(issue.code(), expected, "{kind:?}");
258        }
259    }
260
261    #[test]
262    fn category_is_derived_from_the_kind() {
263        assert_eq!(
264            IssueKind::MissingRequiredField {
265                field_name: "f".into()
266            }
267            .category(),
268            ValidationCategory::Ahb
269        );
270        assert_eq!(
271            IssueKind::CodeNotAllowedForPid {
272                value: "X".into(),
273                allowed: vec![]
274            }
275            .category(),
276            ValidationCategory::Code
277        );
278        assert_eq!(
279            IssueKind::UntSegmentCountMismatch {
280                declared: 1,
281                actual: 2
282            }
283            .category(),
284            ValidationCategory::Structure
285        );
286    }
287}