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 /// CON001 — a period ends before it begins, or as it begins where it may
102 /// not be empty: `DTM+164` not after the `DTM+163` beside it (APERAK Z34
103 /// "Zeitintervall negativ oder Null"). `begin` and `end` are the two DTMs
104 /// (`DTM+163`); see [`crate::consistency`].
105 IntervalNotPositive { begin: String, end: String },
106 /// CON002 — a reference within a transaction names nothing in it: an
107 /// SG8 `RFF+Z19` (Messlokation) naming none of the transaction's
108 /// `LOC+Z17` (APERAK Z21 "Geschäftsvorfallinterne Referenzierung
109 /// fehlerhaft"). `reference` is the RFF (`RFF+Z19`), `value` the id it
110 /// names, `targets` what it may name (`LOC+Z17`); see
111 /// [`crate::consistency`].
112 ReferenceNotFound {
113 reference: String,
114 value: String,
115 targets: Vec<String>,
116 },
117 /// STR007 — UNT's declared segment count disagrees with the actual count.
118 UntSegmentCountMismatch { declared: usize, actual: usize },
119 /// STR007 — the input holds several messages, so the count is not checkable.
120 UntCountNotVerifiable { unh_count: usize },
121 /// STR003 / STR008 — a structure diagnostic raised during assembly.
122 ///
123 /// `detail` carries the diagnostic's own message verbatim: some
124 /// diagnostics (e.g. `mig_assembly::Assembler::assemble_with_diagnostics`'s
125 /// `"Assembly failed: {e}"` case) say something not derivable from
126 /// `(kind, segment_id, position)` alone.
127 StructureDiagnostic {
128 kind: StructureDiagnosticKind,
129 segment_id: String,
130 position: usize,
131 detail: String,
132 },
133}
134
135impl IssueKind {
136 /// The stable machine identifier, unchanged from the former `code` field.
137 pub fn code(&self) -> &'static str {
138 match self {
139 Self::MissingRequiredField { .. } => "AHB001",
140 Self::GroupNotAllowed { .. } | Self::SegmentNotAllowed { .. } => "AHB002",
141 Self::FieldConditionNotSatisfied { .. } => "AHB003",
142 Self::ConditionUnknown { .. } => "AHB005",
143 Self::PackageCardinality { .. } => "AHB006",
144 Self::RepeatedInTransaction { .. } => "AHB007",
145 Self::RepetitionCount { .. } => "AHB008",
146 Self::CodeNotAllowedForPid { .. } => "COD002",
147 Self::AnswerNotInList { .. } => "COD003",
148 Self::ValueTooLong { .. } => "FMT001",
149 Self::ValueNotNumeric { .. } => "FMT002",
150 Self::IntervalNotPositive { .. } => "CON001",
151 Self::ReferenceNotFound { .. } => "CON002",
152 Self::UntSegmentCountMismatch { .. } | Self::UntCountNotVerifiable { .. } => "STR007",
153 // One code per kind (#81). An orphaned group segment is a skipped
154 // segment too (its content is equally absent); the kind and
155 // message tell the missing entry segment apart. A segment whose
156 // qualifier no slot at its place accepts is unexpected there.
157 Self::StructureDiagnostic { kind, .. } => match kind {
158 StructureDiagnosticKind::MissingRequiredSegment => "STR001",
159 StructureDiagnosticKind::MaxRepetitionsExceeded => "STR002",
160 StructureDiagnosticKind::UnexpectedSegment
161 | StructureDiagnosticKind::UnrecognizedQualifier => "STR003",
162 StructureDiagnosticKind::MissingRequiredGroup => "STR005",
163 StructureDiagnosticKind::GroupMaxRepetitionsExceeded => "STR006",
164 StructureDiagnosticKind::SkippedUnknownSegment
165 | StructureDiagnosticKind::OrphanedGroupSegment => "STR008",
166 },
167 }
168 }
169
170 /// The issue's category. Derived, so it can never disagree with the kind.
171 pub fn category(&self) -> ValidationCategory {
172 match self {
173 Self::MissingRequiredField { .. }
174 | Self::GroupNotAllowed { .. }
175 | Self::SegmentNotAllowed { .. }
176 | Self::FieldConditionNotSatisfied { .. }
177 | Self::ConditionUnknown { .. }
178 | Self::PackageCardinality { .. }
179 | Self::RepeatedInTransaction { .. }
180 | Self::RepetitionCount { .. }
181 | Self::IntervalNotPositive { .. }
182 | Self::ReferenceNotFound { .. } => ValidationCategory::Ahb,
183 Self::CodeNotAllowedForPid { .. } | Self::AnswerNotInList { .. } => {
184 ValidationCategory::Code
185 }
186 Self::UntSegmentCountMismatch { .. }
187 | Self::UntCountNotVerifiable { .. }
188 | Self::StructureDiagnostic { .. } => ValidationCategory::Structure,
189 Self::ValueTooLong { .. } | Self::ValueNotNumeric { .. } => ValidationCategory::Format,
190 }
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197 use mig_assembly::StructureDiagnosticKind;
198
199 #[test]
200 fn code_matches_the_legacy_error_code_for_every_kind() {
201 let cases: Vec<(IssueKind, &str)> = vec![
202 (
203 IssueKind::MissingRequiredField {
204 field_name: "f".into(),
205 },
206 "AHB001",
207 ),
208 (
209 IssueKind::GroupNotAllowed {
210 group: "SG4/SG5".into(),
211 },
212 "AHB002",
213 ),
214 (
215 IssueKind::SegmentNotAllowed {
216 segment: "SG4/SG8/SG10/CAV".into(),
217 },
218 "AHB002",
219 ),
220 (
221 IssueKind::FieldConditionNotSatisfied {
222 field_name: "f".into(),
223 failed: vec![],
224 },
225 "AHB003",
226 ),
227 (
228 IssueKind::ConditionUnknown {
229 field_name: "f".into(),
230 unresolved: UnresolvedConditions::default(),
231 },
232 "AHB005",
233 ),
234 (
235 IssueKind::PackageCardinality {
236 package_id: "1P0..1".into(),
237 present: 2,
238 min: 0,
239 max: 1,
240 codes: vec![],
241 },
242 "AHB006",
243 ),
244 (
245 IssueKind::RepetitionCount {
246 path: "SG29/SG34".into(),
247 count: 2,
248 },
249 "AHB008",
250 ),
251 (
252 IssueKind::CodeNotAllowedForPid {
253 value: "X".into(),
254 allowed: vec![],
255 },
256 "COD002",
257 ),
258 (
259 IssueKind::AnswerNotInList {
260 answer: "ZB5".into(),
261 list: "G_0059".into(),
262 allowed: vec![],
263 },
264 "COD003",
265 ),
266 (
267 IssueKind::ValueTooLong {
268 field_name: "f".into(),
269 length: 600,
270 max: 512,
271 },
272 "FMT001",
273 ),
274 (
275 IssueKind::UntSegmentCountMismatch {
276 declared: 30,
277 actual: 31,
278 },
279 "STR007",
280 ),
281 (IssueKind::UntCountNotVerifiable { unh_count: 2 }, "STR007"),
282 (
283 IssueKind::StructureDiagnostic {
284 kind: StructureDiagnosticKind::SkippedUnknownSegment,
285 segment_id: "CCI".into(),
286 position: 15,
287 detail: "irrelevant to the code".into(),
288 },
289 "STR008",
290 ),
291 (
292 IssueKind::StructureDiagnostic {
293 kind: StructureDiagnosticKind::UnexpectedSegment,
294 segment_id: "CCI".into(),
295 position: 15,
296 detail: "irrelevant to the code".into(),
297 },
298 "STR003",
299 ),
300 ];
301 for (kind, expected) in cases {
302 assert_eq!(kind.code(), expected, "wrong code for {kind:?}");
303 }
304 }
305
306 /// Every structure diagnostic keeps its own code (#81): a repetition
307 /// overrun must not surface as "unexpected segment".
308 #[test]
309 fn each_structure_kind_has_its_own_code() {
310 use StructureDiagnosticKind as K;
311 for (kind, expected) in [
312 (K::MissingRequiredSegment, "STR001"),
313 (K::MaxRepetitionsExceeded, "STR002"),
314 (K::UnexpectedSegment, "STR003"),
315 (K::UnrecognizedQualifier, "STR003"),
316 (K::MissingRequiredGroup, "STR005"),
317 (K::GroupMaxRepetitionsExceeded, "STR006"),
318 (K::SkippedUnknownSegment, "STR008"),
319 (K::OrphanedGroupSegment, "STR008"),
320 ] {
321 let issue = IssueKind::StructureDiagnostic {
322 kind,
323 segment_id: "RFF".into(),
324 position: 1,
325 detail: String::new(),
326 };
327 assert_eq!(issue.code(), expected, "{kind:?}");
328 }
329 }
330
331 #[test]
332 fn category_is_derived_from_the_kind() {
333 assert_eq!(
334 IssueKind::MissingRequiredField {
335 field_name: "f".into()
336 }
337 .category(),
338 ValidationCategory::Ahb
339 );
340 assert_eq!(
341 IssueKind::CodeNotAllowedForPid {
342 value: "X".into(),
343 allowed: vec![]
344 }
345 .category(),
346 ValidationCategory::Code
347 );
348 assert_eq!(
349 IssueKind::UntSegmentCountMismatch {
350 declared: 1,
351 actual: 2
352 }
353 .category(),
354 ValidationCategory::Structure
355 );
356 }
357}