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    /// `failed` are the conditions that make it false (see
50    /// `ConditionExprEvaluator::false_ids_with_ub`): what kind of error it is
51    /// depends on them.
52    FieldConditionNotSatisfied {
53        field_name: String,
54        #[serde(default, skip_serializing_if = "Vec::is_empty")]
55        failed: Vec<u32>,
56    },
57    /// AHB005 — the condition expression could not be fully evaluated.
58    ConditionUnknown {
59        field_name: String,
60        unresolved: UnresolvedConditions,
61    },
62    /// AHB006 — number of codes present in a package is outside `min..max`.
63    PackageCardinality {
64        package_id: String,
65        present: usize,
66        min: usize,
67        max: usize,
68        codes: Vec<String>,
69    },
70    /// AHB007 — a group or segment the AHB allows once per transaction
71    /// (`[2061]` "genau einmal je SG4 IDE (Vorgang)") is sent `count` times in
72    /// one. `path` is the group or segment (`SG4/SG8`, `SG4/STS`).
73    RepeatedInTransaction { path: String, count: usize },
74    /// AHB008 — a group or segment sent another number of times in its group
75    /// than a repetition condition allows there: too often (ORDERS `[2005]`
76    /// "Pro SG29 LIN ist die SG34 RFF+Z09 (Gerätenummer) genau einmal
77    /// anzugeben") or too rarely (UTILMD `[2317]` "mindestens zweimal").
78    /// `path` is the group or segment (`SG29/SG34`), `count` how often the
79    /// group instance holds it.
80    RepetitionCount { path: String, count: usize },
81    /// COD002 — the value is a valid code but not allowed for this PID.
82    CodeNotAllowedForPid { value: String, allowed: Vec<String> },
83    /// COD003 — a response's answer (AJT 4465, STS C556/9013) is not one of the
84    /// codes of the EBD or Codeliste it names beside it (AJT 1082, C556/1131):
85    /// `AJT+ZB5+G_0059`. The AHB lists which lists may be named; the EBD
86    /// document says what they hold.
87    AnswerNotInList {
88        answer: String,
89        list: String,
90        allowed: Vec<String>,
91    },
92    /// FMT001 — the value is longer than its MIG format allows (`an..512`).
93    ValueTooLong {
94        field_name: String,
95        length: usize,
96        max: usize,
97    },
98    /// FMT002 — a data element of numeric format (`n..10`) holds something
99    /// that is not a number (`O5D2DXBG1A`).
100    ValueNotNumeric { field_name: String },
101    /// STR007 — UNT's declared segment count disagrees with the actual count.
102    UntSegmentCountMismatch { declared: usize, actual: usize },
103    /// STR007 — the input holds several messages, so the count is not checkable.
104    UntCountNotVerifiable { unh_count: usize },
105    /// STR003 / STR008 — a structure diagnostic raised during assembly.
106    ///
107    /// `detail` carries the diagnostic's own message verbatim: some
108    /// diagnostics (e.g. `mig_assembly::Assembler::assemble_with_diagnostics`'s
109    /// `"Assembly failed: {e}"` case) say something not derivable from
110    /// `(kind, segment_id, position)` alone.
111    StructureDiagnostic {
112        kind: StructureDiagnosticKind,
113        segment_id: String,
114        position: usize,
115        detail: String,
116    },
117}
118
119impl IssueKind {
120    /// The stable machine identifier, unchanged from the former `code` field.
121    pub fn code(&self) -> &'static str {
122        match self {
123            Self::MissingRequiredField { .. } => "AHB001",
124            Self::GroupNotAllowed { .. } | Self::SegmentNotAllowed { .. } => "AHB002",
125            Self::FieldConditionNotSatisfied { .. } => "AHB003",
126            Self::ConditionUnknown { .. } => "AHB005",
127            Self::PackageCardinality { .. } => "AHB006",
128            Self::RepeatedInTransaction { .. } => "AHB007",
129            Self::RepetitionCount { .. } => "AHB008",
130            Self::CodeNotAllowedForPid { .. } => "COD002",
131            Self::AnswerNotInList { .. } => "COD003",
132            Self::ValueTooLong { .. } => "FMT001",
133            Self::ValueNotNumeric { .. } => "FMT002",
134            Self::UntSegmentCountMismatch { .. } | Self::UntCountNotVerifiable { .. } => "STR007",
135            // One code per kind (#81). An orphaned group segment is a skipped
136            // segment too (its content is equally absent); the kind and
137            // message tell the missing entry segment apart. A segment whose
138            // qualifier no slot at its place accepts is unexpected there.
139            Self::StructureDiagnostic { kind, .. } => match kind {
140                StructureDiagnosticKind::MissingRequiredSegment => "STR001",
141                StructureDiagnosticKind::MaxRepetitionsExceeded => "STR002",
142                StructureDiagnosticKind::UnexpectedSegment
143                | StructureDiagnosticKind::UnrecognizedQualifier => "STR003",
144                StructureDiagnosticKind::MissingRequiredGroup => "STR005",
145                StructureDiagnosticKind::GroupMaxRepetitionsExceeded => "STR006",
146                StructureDiagnosticKind::SkippedUnknownSegment
147                | StructureDiagnosticKind::OrphanedGroupSegment => "STR008",
148            },
149        }
150    }
151
152    /// The issue's category. Derived, so it can never disagree with the kind.
153    pub fn category(&self) -> ValidationCategory {
154        match self {
155            Self::MissingRequiredField { .. }
156            | Self::GroupNotAllowed { .. }
157            | Self::SegmentNotAllowed { .. }
158            | Self::FieldConditionNotSatisfied { .. }
159            | Self::ConditionUnknown { .. }
160            | Self::PackageCardinality { .. }
161            | Self::RepeatedInTransaction { .. }
162            | Self::RepetitionCount { .. } => ValidationCategory::Ahb,
163            Self::CodeNotAllowedForPid { .. } | Self::AnswerNotInList { .. } => {
164                ValidationCategory::Code
165            }
166            Self::UntSegmentCountMismatch { .. }
167            | Self::UntCountNotVerifiable { .. }
168            | Self::StructureDiagnostic { .. } => ValidationCategory::Structure,
169            Self::ValueTooLong { .. } | Self::ValueNotNumeric { .. } => ValidationCategory::Format,
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use mig_assembly::StructureDiagnosticKind;
178
179    #[test]
180    fn code_matches_the_legacy_error_code_for_every_kind() {
181        let cases: Vec<(IssueKind, &str)> = vec![
182            (
183                IssueKind::MissingRequiredField {
184                    field_name: "f".into(),
185                },
186                "AHB001",
187            ),
188            (
189                IssueKind::GroupNotAllowed {
190                    group: "SG4/SG5".into(),
191                },
192                "AHB002",
193            ),
194            (
195                IssueKind::SegmentNotAllowed {
196                    segment: "SG4/SG8/SG10/CAV".into(),
197                },
198                "AHB002",
199            ),
200            (
201                IssueKind::FieldConditionNotSatisfied {
202                    field_name: "f".into(),
203                    failed: vec![],
204                },
205                "AHB003",
206            ),
207            (
208                IssueKind::ConditionUnknown {
209                    field_name: "f".into(),
210                    unresolved: UnresolvedConditions::default(),
211                },
212                "AHB005",
213            ),
214            (
215                IssueKind::PackageCardinality {
216                    package_id: "1P0..1".into(),
217                    present: 2,
218                    min: 0,
219                    max: 1,
220                    codes: vec![],
221                },
222                "AHB006",
223            ),
224            (
225                IssueKind::RepetitionCount {
226                    path: "SG29/SG34".into(),
227                    count: 2,
228                },
229                "AHB008",
230            ),
231            (
232                IssueKind::CodeNotAllowedForPid {
233                    value: "X".into(),
234                    allowed: vec![],
235                },
236                "COD002",
237            ),
238            (
239                IssueKind::AnswerNotInList {
240                    answer: "ZB5".into(),
241                    list: "G_0059".into(),
242                    allowed: vec![],
243                },
244                "COD003",
245            ),
246            (
247                IssueKind::ValueTooLong {
248                    field_name: "f".into(),
249                    length: 600,
250                    max: 512,
251                },
252                "FMT001",
253            ),
254            (
255                IssueKind::UntSegmentCountMismatch {
256                    declared: 30,
257                    actual: 31,
258                },
259                "STR007",
260            ),
261            (IssueKind::UntCountNotVerifiable { unh_count: 2 }, "STR007"),
262            (
263                IssueKind::StructureDiagnostic {
264                    kind: StructureDiagnosticKind::SkippedUnknownSegment,
265                    segment_id: "CCI".into(),
266                    position: 15,
267                    detail: "irrelevant to the code".into(),
268                },
269                "STR008",
270            ),
271            (
272                IssueKind::StructureDiagnostic {
273                    kind: StructureDiagnosticKind::UnexpectedSegment,
274                    segment_id: "CCI".into(),
275                    position: 15,
276                    detail: "irrelevant to the code".into(),
277                },
278                "STR003",
279            ),
280        ];
281        for (kind, expected) in cases {
282            assert_eq!(kind.code(), expected, "wrong code for {kind:?}");
283        }
284    }
285
286    /// Every structure diagnostic keeps its own code (#81): a repetition
287    /// overrun must not surface as "unexpected segment".
288    #[test]
289    fn each_structure_kind_has_its_own_code() {
290        use StructureDiagnosticKind as K;
291        for (kind, expected) in [
292            (K::MissingRequiredSegment, "STR001"),
293            (K::MaxRepetitionsExceeded, "STR002"),
294            (K::UnexpectedSegment, "STR003"),
295            (K::UnrecognizedQualifier, "STR003"),
296            (K::MissingRequiredGroup, "STR005"),
297            (K::GroupMaxRepetitionsExceeded, "STR006"),
298            (K::SkippedUnknownSegment, "STR008"),
299            (K::OrphanedGroupSegment, "STR008"),
300        ] {
301            let issue = IssueKind::StructureDiagnostic {
302                kind,
303                segment_id: "RFF".into(),
304                position: 1,
305                detail: String::new(),
306            };
307            assert_eq!(issue.code(), expected, "{kind:?}");
308        }
309    }
310
311    #[test]
312    fn category_is_derived_from_the_kind() {
313        assert_eq!(
314            IssueKind::MissingRequiredField {
315                field_name: "f".into()
316            }
317            .category(),
318            ValidationCategory::Ahb
319        );
320        assert_eq!(
321            IssueKind::CodeNotAllowedForPid {
322                value: "X".into(),
323                allowed: vec![]
324            }
325            .category(),
326            ValidationCategory::Code
327        );
328        assert_eq!(
329            IssueKind::UntSegmentCountMismatch {
330                declared: 1,
331                actual: 2
332            }
333            .category(),
334            ValidationCategory::Structure
335        );
336    }
337}