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