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    /// AHB003 — the field is present but its AHB condition is not satisfied.
42    FieldConditionNotSatisfied { field_name: String },
43    /// AHB005 — the condition expression could not be fully evaluated.
44    ConditionUnknown {
45        field_name: String,
46        unresolved: UnresolvedConditions,
47    },
48    /// AHB006 — number of codes present in a package is outside `min..max`.
49    PackageCardinality {
50        package_id: String,
51        present: usize,
52        min: usize,
53        max: usize,
54        codes: Vec<String>,
55    },
56    /// COD002 — the value is a valid code but not allowed for this PID.
57    CodeNotAllowedForPid { value: String, allowed: Vec<String> },
58    /// STR007 — UNT's declared segment count disagrees with the actual count.
59    UntSegmentCountMismatch { declared: usize, actual: usize },
60    /// STR007 — the input holds several messages, so the count is not checkable.
61    UntCountNotVerifiable { unh_count: usize },
62    /// STR003 / STR008 — a structure diagnostic raised during assembly.
63    ///
64    /// `detail` carries the diagnostic's own message verbatim: some
65    /// diagnostics (e.g. `mig_assembly::Assembler::assemble_with_diagnostics`'s
66    /// `"Assembly failed: {e}"` case) say something not derivable from
67    /// `(kind, segment_id, position)` alone.
68    StructureDiagnostic {
69        kind: StructureDiagnosticKind,
70        segment_id: String,
71        position: usize,
72        detail: String,
73    },
74}
75
76impl IssueKind {
77    /// The stable machine identifier, unchanged from the former `code` field.
78    pub fn code(&self) -> &'static str {
79        match self {
80            Self::MissingRequiredField { .. } => "AHB001",
81            Self::FieldConditionNotSatisfied { .. } => "AHB003",
82            Self::ConditionUnknown { .. } => "AHB005",
83            Self::PackageCardinality { .. } => "AHB006",
84            Self::CodeNotAllowedForPid { .. } => "COD002",
85            Self::UntSegmentCountMismatch { .. } | Self::UntCountNotVerifiable { .. } => "STR007",
86            // Mirrors the mapping pipeline.rs applied before kinds existed:
87            // skipped segments get their own code, every other diagnostic is
88            // reported as an unexpected segment. An orphaned group segment is
89            // a skipped segment too (its content is equally absent); the kind
90            // and message tell the missing entry segment apart.
91            Self::StructureDiagnostic { kind, .. } => match kind {
92                StructureDiagnosticKind::SkippedUnknownSegment
93                | StructureDiagnosticKind::OrphanedGroupSegment => "STR008",
94                _ => "STR003",
95            },
96        }
97    }
98
99    /// The issue's category. Derived, so it can never disagree with the kind.
100    pub fn category(&self) -> ValidationCategory {
101        match self {
102            Self::MissingRequiredField { .. }
103            | Self::FieldConditionNotSatisfied { .. }
104            | Self::ConditionUnknown { .. }
105            | Self::PackageCardinality { .. } => ValidationCategory::Ahb,
106            Self::CodeNotAllowedForPid { .. } => ValidationCategory::Code,
107            Self::UntSegmentCountMismatch { .. }
108            | Self::UntCountNotVerifiable { .. }
109            | Self::StructureDiagnostic { .. } => ValidationCategory::Structure,
110        }
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use mig_assembly::StructureDiagnosticKind;
118
119    #[test]
120    fn code_matches_the_legacy_error_code_for_every_kind() {
121        let cases: Vec<(IssueKind, &str)> = vec![
122            (
123                IssueKind::MissingRequiredField {
124                    field_name: "f".into(),
125                },
126                "AHB001",
127            ),
128            (
129                IssueKind::FieldConditionNotSatisfied {
130                    field_name: "f".into(),
131                },
132                "AHB003",
133            ),
134            (
135                IssueKind::ConditionUnknown {
136                    field_name: "f".into(),
137                    unresolved: UnresolvedConditions::default(),
138                },
139                "AHB005",
140            ),
141            (
142                IssueKind::PackageCardinality {
143                    package_id: "1P0..1".into(),
144                    present: 2,
145                    min: 0,
146                    max: 1,
147                    codes: vec![],
148                },
149                "AHB006",
150            ),
151            (
152                IssueKind::CodeNotAllowedForPid {
153                    value: "X".into(),
154                    allowed: vec![],
155                },
156                "COD002",
157            ),
158            (
159                IssueKind::UntSegmentCountMismatch {
160                    declared: 30,
161                    actual: 31,
162                },
163                "STR007",
164            ),
165            (IssueKind::UntCountNotVerifiable { unh_count: 2 }, "STR007"),
166            (
167                IssueKind::StructureDiagnostic {
168                    kind: StructureDiagnosticKind::SkippedUnknownSegment,
169                    segment_id: "CCI".into(),
170                    position: 15,
171                    detail: "irrelevant to the code".into(),
172                },
173                "STR008",
174            ),
175            (
176                IssueKind::StructureDiagnostic {
177                    kind: StructureDiagnosticKind::UnexpectedSegment,
178                    segment_id: "CCI".into(),
179                    position: 15,
180                    detail: "irrelevant to the code".into(),
181                },
182                "STR003",
183            ),
184        ];
185        for (kind, expected) in cases {
186            assert_eq!(kind.code(), expected, "wrong code for {kind:?}");
187        }
188    }
189
190    #[test]
191    fn category_is_derived_from_the_kind() {
192        assert_eq!(
193            IssueKind::MissingRequiredField {
194                field_name: "f".into()
195            }
196            .category(),
197            ValidationCategory::Ahb
198        );
199        assert_eq!(
200            IssueKind::CodeNotAllowedForPid {
201                value: "X".into(),
202                allowed: vec![]
203            }
204            .category(),
205            ValidationCategory::Code
206        );
207        assert_eq!(
208            IssueKind::UntSegmentCountMismatch {
209                declared: 1,
210                actual: 2
211            }
212            .category(),
213            ValidationCategory::Structure
214        );
215    }
216}