Skip to main content

automapper_validation/display/
narrator.rs

1//! Putting an issue into words.
2
3use crate::{IssueKind, UnresolvedConditions, ValidationIssue};
4
5use super::IssueNarrator;
6
7/// The wording this repo has always used: technical, English, AHB vocabulary.
8///
9/// When paired with [`EdifactView`](super::EdifactView), this was proven
10/// byte-identical to the former `ValidationIssue::message` across the fixture
11/// corpus before `message` was removed.
12pub struct TechnicalNarrator;
13
14/// `" at X"`, or nothing when the view has no location for this issue.
15fn at(location: Option<&str>) -> String {
16    location.map_or_else(String::new, |l| format!(" at {l}"))
17}
18
19fn ids(list: &[u32]) -> String {
20    list.iter()
21        .map(|id| format!("[{id}]"))
22        .collect::<Vec<_>>()
23        .join(", ")
24}
25
26fn unresolved_detail(u: &UnresolvedConditions) -> String {
27    if u.is_empty() {
28        return String::new();
29    }
30    let mut parts = Vec::new();
31    if !u.external.is_empty() {
32        parts.push(format!(
33            "external conditions require provider: {}",
34            ids(&u.external)
35        ));
36    }
37    if !u.undetermined.is_empty() {
38        parts.push(format!(
39            "conditions could not be determined from message data: {}",
40            ids(&u.undetermined)
41        ));
42    }
43    if !u.missing.is_empty() {
44        parts.push(format!("missing conditions: {}", ids(&u.missing)));
45    }
46    format!(" ({})", parts.join("; "))
47}
48
49impl IssueNarrator for TechnicalNarrator {
50    fn describe(&self, issue: &ValidationIssue, location: Option<&str>) -> String {
51        match &issue.kind {
52            IssueKind::MissingRequiredField { field_name } => {
53                format!("Required field '{field_name}'{} is missing", at(location))
54            }
55            IssueKind::GroupNotAllowed { group } => format!(
56                "Group '{group}' is present although its condition does not hold: {}",
57                issue.rule.as_deref().unwrap_or_default()
58            ),
59            IssueKind::SegmentNotAllowed { segment } => format!(
60                "Segment '{segment}' is present although its condition does not hold: {}",
61                issue.rule.as_deref().unwrap_or_default()
62            ),
63            IssueKind::FieldConditionNotSatisfied { field_name, .. } => format!(
64                "Field '{field_name}'{} is present but does not satisfy condition: {}",
65                at(location),
66                issue.rule.as_deref().unwrap_or_default()
67            ),
68            IssueKind::ConditionUnknown { field_name, unresolved } => format!(
69                "Condition for field '{field_name}' could not be fully evaluated{}",
70                unresolved_detail(unresolved)
71            ),
72            IssueKind::PackageCardinality { package_id, present, min, max, codes } => format!(
73                "Package [{package_id}P{min}..{max}]{}: {present} code(s) present (allowed {min}..{max}). \
74                 Codes in package: [{}]",
75                at(location),
76                codes.join(", ")
77            ),
78            IssueKind::RepeatedInTransaction { path, count } => format!(
79                "'{path}' is sent {count} times in one transaction; its condition allows it once: {}",
80                issue.rule.as_deref().unwrap_or_default()
81            ),
82            IssueKind::RepetitionCount { path, count } => format!(
83                "'{path}' is sent {count} times in one group; its condition allows another number: {}",
84                issue.rule.as_deref().unwrap_or_default()
85            ),
86            IssueKind::CodeNotAllowedForPid { value, allowed } => format!(
87                "Code '{value}' is not allowed for this PID. Allowed: [{}]",
88                allowed.join(", ")
89            ),
90            IssueKind::AnswerNotInList { answer, list, allowed } => format!(
91                "Answer '{answer}'{} is not a code of {list}. Its codes: [{}]",
92                at(location),
93                allowed.join(", ")
94            ),
95            IssueKind::ValueNotNumeric { field_name } => format!(
96                "Field '{field_name}'{} is not a number; its format is {}",
97                at(location),
98                issue.expected_value.as_deref().unwrap_or_default()
99            ),
100            IssueKind::ValueTooLong { field_name, length, max } => format!(
101                "Field '{field_name}'{} has {length} characters; its format allows {max}",
102                at(location)
103            ),
104            IssueKind::IntervalNotPositive { begin, end } => format!(
105                "Period '{begin}'..'{end}' ends at {}, not after it begins ({})",
106                issue.actual_value.as_deref().unwrap_or_default(),
107                issue
108                    .expected_value
109                    .as_deref()
110                    .unwrap_or_default()
111                    .trim_start_matches("> ")
112            ),
113            IssueKind::ReferenceNotFound { reference, value, targets } => format!(
114                "'{reference}' names '{value}', which is no {} of its transaction",
115                targets.join(" / ")
116            ),
117            IssueKind::UntSegmentCountMismatch { declared, actual } => {
118                format!("UNT segment count mismatch: declared {declared}, actual {actual}")
119            }
120            IssueKind::UntCountNotVerifiable { unh_count } => format!(
121                "UNT validation requires per-message segments, found {unh_count} UNH segments"
122            ),
123            IssueKind::StructureDiagnostic { detail, .. } => detail.clone(),
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use crate::display::{Bo4eView, EdifactView, IssueNarrator, IssueView, TechnicalNarrator};
131    use crate::{IssueKind, Severity, UnresolvedConditions, ValidationIssue};
132    use mig_assembly::StructureDiagnosticKind;
133
134    fn missing_field_issue() -> ValidationIssue {
135        ValidationIssue::new(
136            Severity::Error,
137            IssueKind::MissingRequiredField {
138                field_name: "Merkmal, Code".into(),
139            },
140        )
141        .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
142        .with_bo4e_path("stammdaten.Marktlokation.haushaltskunde")
143    }
144
145    #[test]
146    fn edifact_view_narrates_with_the_edifact_path() {
147        let issue = missing_field_issue();
148        let loc = EdifactView.location(&issue);
149        assert_eq!(loc.as_deref(), Some("SG4/SG8/SG10/CCI/C240/7037"));
150        assert_eq!(
151            TechnicalNarrator.describe(&issue, loc.as_deref()),
152            "Required field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is missing"
153        );
154    }
155
156    #[test]
157    fn bo4e_view_narrates_with_the_bo4e_path() {
158        let issue = missing_field_issue();
159        let loc = Bo4eView.location(&issue);
160        assert_eq!(
161            loc.as_deref(),
162            Some("stammdaten.Marktlokation.haushaltskunde")
163        );
164        assert_eq!(
165            TechnicalNarrator.describe(&issue, loc.as_deref()),
166            "Required field 'Merkmal, Code' at stammdaten.Marktlokation.haushaltskunde is missing"
167        );
168    }
169
170    #[test]
171    fn bo4e_view_has_no_location_for_envelope_issues() {
172        let issue = ValidationIssue::new(
173            Severity::Error,
174            IssueKind::UntSegmentCountMismatch {
175                declared: 30,
176                actual: 31,
177            },
178        )
179        .with_field_path("UNT/0074");
180
181        assert_eq!(Bo4eView.location(&issue), None);
182        assert_eq!(
183            TechnicalNarrator.describe(&issue, None),
184            "UNT segment count mismatch: declared 30, actual 31"
185        );
186    }
187
188    // Each expectation below is transcribed verbatim from the `format!` call
189    // that built the equivalent legacy `message` in
190    // `git show 423f59255:crates/automapper-validation/src/validator/validate.rs`.
191
192    #[test]
193    fn field_condition_not_satisfied_matches_the_legacy_message() {
194        let issue = ValidationIssue::new(
195            Severity::Error,
196            IssueKind::FieldConditionNotSatisfied {
197                field_name: "Merkmal, Code".into(),
198                failed: vec![],
199            },
200        )
201        .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
202        .with_rule("Muss [182]");
203        let loc = EdifactView.location(&issue);
204
205        // validate.rs:379 — format!("Field '{}' at {} is present but does not
206        // satisfy condition: {}", field.name, field.segment_path, field.ahb_status)
207        assert_eq!(
208            TechnicalNarrator.describe(&issue, loc.as_deref()),
209            "Field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is present but does not satisfy condition: Muss [182]"
210        );
211    }
212
213    #[test]
214    fn condition_unknown_joins_multiple_id_groups_with_semicolons() {
215        let issue = ValidationIssue::new(
216            Severity::Info,
217            IssueKind::ConditionUnknown {
218                field_name: "Merkmal, Code".into(),
219                unresolved: UnresolvedConditions {
220                    external: vec![182],
221                    undetermined: vec![6],
222                    missing: vec![570],
223                },
224            },
225        )
226        .with_field_path("SG4/SG8/SG10/CCI/C240/7037");
227        let loc = EdifactView.location(&issue);
228
229        // validate.rs:444 — format!("Condition for field '{}' could not be
230        // fully evaluated{}", field.name, detail), where `detail` joins
231        // "external conditions require provider: ...", "conditions could not
232        // be determined from message data: ...", and "missing conditions:
233        // ..." with "; ", wrapped in " (...)".
234        assert_eq!(
235            TechnicalNarrator.describe(&issue, loc.as_deref()),
236            "Condition for field 'Merkmal, Code' could not be fully evaluated (external conditions require provider: [182]; conditions could not be determined from message data: [6]; missing conditions: [570])"
237        );
238    }
239
240    #[test]
241    fn package_cardinality_matches_the_legacy_message() {
242        let issue = ValidationIssue::new(
243            Severity::Error,
244            IssueKind::PackageCardinality {
245                package_id: "1".into(),
246                present: 2,
247                min: 0,
248                max: 1,
249                codes: vec!["A".into(), "B".into()],
250            },
251        )
252        .with_field_path("SG4/SG8/SG10");
253        let loc = EdifactView.location(&issue);
254
255        // validate.rs:643 — format!("Package [{}P{}..{}] at {}: {} code(s)
256        // present (allowed {}..{}). Codes in package: [{}]", pkg_id,
257        // group.min, group.max, seg_path, present_count, group.min,
258        // group.max, code_list)
259        assert_eq!(
260            TechnicalNarrator.describe(&issue, loc.as_deref()),
261            "Package [1P0..1] at SG4/SG8/SG10: 2 code(s) present (allowed 0..1). Codes in package: [A, B]"
262        );
263    }
264
265    #[test]
266    fn code_not_allowed_for_pid_matches_the_legacy_message() {
267        let issue = ValidationIssue::new(
268            Severity::Warning,
269            IssueKind::CodeNotAllowedForPid {
270                value: "Z99".into(),
271                allowed: vec!["Z01".into(), "Z02".into(), "Z98".into()],
272            },
273        );
274
275        // validate.rs:895 — format!("Code '{}' is not allowed for this PID.
276        // Allowed: [{}]", value, allowed.join(", "))
277        assert_eq!(
278            TechnicalNarrator.describe(&issue, None),
279            "Code 'Z99' is not allowed for this PID. Allowed: [Z01, Z02, Z98]"
280        );
281    }
282
283    #[test]
284    fn unt_count_not_verifiable_matches_the_legacy_message() {
285        let issue = ValidationIssue::new(
286            Severity::Warning,
287            IssueKind::UntCountNotVerifiable { unh_count: 3 },
288        );
289
290        // validate.rs:1605 — format!("UNT validation requires per-message
291        // segments, found {unh_count} UNH segments")
292        assert_eq!(
293            TechnicalNarrator.describe(&issue, None),
294            "UNT validation requires per-message segments, found 3 UNH segments"
295        );
296    }
297
298    #[test]
299    fn structure_diagnostic_passes_its_detail_through_verbatim() {
300        // Unlike the other seven kinds, `StructureDiagnostic` was never built
301        // from a `format!` in validate.rs — it carries `mig_assembly`'s own
302        // diagnostic message (see `IssueKind::StructureDiagnostic`'s doc
303        // comment), so the narrator must reproduce it byte-for-byte with no
304        // added wording.
305        let detail = "Segment 'FTX' at position 15 is not defined in the PID-filtered MIG; \
306                       the assembler advanced past it";
307        let issue = ValidationIssue::new(
308            Severity::Warning,
309            IssueKind::StructureDiagnostic {
310                kind: StructureDiagnosticKind::UnexpectedSegment,
311                segment_id: "FTX".into(),
312                position: 15,
313                detail: detail.into(),
314            },
315        );
316
317        assert_eq!(TechnicalNarrator.describe(&issue, None), detail);
318    }
319}