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