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::CodeNotAllowedForPid { value, allowed } => format!(
79                "Code '{value}' is not allowed for this PID. Allowed: [{}]",
80                allowed.join(", ")
81            ),
82            IssueKind::UntSegmentCountMismatch { declared, actual } => {
83                format!("UNT segment count mismatch: declared {declared}, actual {actual}")
84            }
85            IssueKind::UntCountNotVerifiable { unh_count } => format!(
86                "UNT validation requires per-message segments, found {unh_count} UNH segments"
87            ),
88            IssueKind::StructureDiagnostic { detail, .. } => detail.clone(),
89        }
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use crate::display::{Bo4eView, EdifactView, IssueNarrator, IssueView, TechnicalNarrator};
96    use crate::{IssueKind, Severity, UnresolvedConditions, ValidationIssue};
97    use mig_assembly::StructureDiagnosticKind;
98
99    fn missing_field_issue() -> ValidationIssue {
100        ValidationIssue::new(
101            Severity::Error,
102            IssueKind::MissingRequiredField {
103                field_name: "Merkmal, Code".into(),
104            },
105        )
106        .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
107        .with_bo4e_path("stammdaten.Marktlokation.haushaltskunde")
108    }
109
110    #[test]
111    fn edifact_view_narrates_with_the_edifact_path() {
112        let issue = missing_field_issue();
113        let loc = EdifactView.location(&issue);
114        assert_eq!(loc.as_deref(), Some("SG4/SG8/SG10/CCI/C240/7037"));
115        assert_eq!(
116            TechnicalNarrator.describe(&issue, loc.as_deref()),
117            "Required field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is missing"
118        );
119    }
120
121    #[test]
122    fn bo4e_view_narrates_with_the_bo4e_path() {
123        let issue = missing_field_issue();
124        let loc = Bo4eView.location(&issue);
125        assert_eq!(
126            loc.as_deref(),
127            Some("stammdaten.Marktlokation.haushaltskunde")
128        );
129        assert_eq!(
130            TechnicalNarrator.describe(&issue, loc.as_deref()),
131            "Required field 'Merkmal, Code' at stammdaten.Marktlokation.haushaltskunde is missing"
132        );
133    }
134
135    #[test]
136    fn bo4e_view_has_no_location_for_envelope_issues() {
137        let issue = ValidationIssue::new(
138            Severity::Error,
139            IssueKind::UntSegmentCountMismatch {
140                declared: 30,
141                actual: 31,
142            },
143        )
144        .with_field_path("UNT/0074");
145
146        assert_eq!(Bo4eView.location(&issue), None);
147        assert_eq!(
148            TechnicalNarrator.describe(&issue, None),
149            "UNT segment count mismatch: declared 30, actual 31"
150        );
151    }
152
153    // Each expectation below is transcribed verbatim from the `format!` call
154    // that built the equivalent legacy `message` in
155    // `git show 423f59255:crates/automapper-validation/src/validator/validate.rs`.
156
157    #[test]
158    fn field_condition_not_satisfied_matches_the_legacy_message() {
159        let issue = ValidationIssue::new(
160            Severity::Error,
161            IssueKind::FieldConditionNotSatisfied {
162                field_name: "Merkmal, Code".into(),
163            },
164        )
165        .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
166        .with_rule("Muss [182]");
167        let loc = EdifactView.location(&issue);
168
169        // validate.rs:379 — format!("Field '{}' at {} is present but does not
170        // satisfy condition: {}", field.name, field.segment_path, field.ahb_status)
171        assert_eq!(
172            TechnicalNarrator.describe(&issue, loc.as_deref()),
173            "Field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is present but does not satisfy condition: Muss [182]"
174        );
175    }
176
177    #[test]
178    fn condition_unknown_joins_multiple_id_groups_with_semicolons() {
179        let issue = ValidationIssue::new(
180            Severity::Info,
181            IssueKind::ConditionUnknown {
182                field_name: "Merkmal, Code".into(),
183                unresolved: UnresolvedConditions {
184                    external: vec![182],
185                    undetermined: vec![6],
186                    missing: vec![570],
187                },
188            },
189        )
190        .with_field_path("SG4/SG8/SG10/CCI/C240/7037");
191        let loc = EdifactView.location(&issue);
192
193        // validate.rs:444 — format!("Condition for field '{}' could not be
194        // fully evaluated{}", field.name, detail), where `detail` joins
195        // "external conditions require provider: ...", "conditions could not
196        // be determined from message data: ...", and "missing conditions:
197        // ..." with "; ", wrapped in " (...)".
198        assert_eq!(
199            TechnicalNarrator.describe(&issue, loc.as_deref()),
200            "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])"
201        );
202    }
203
204    #[test]
205    fn package_cardinality_matches_the_legacy_message() {
206        let issue = ValidationIssue::new(
207            Severity::Error,
208            IssueKind::PackageCardinality {
209                package_id: "1".into(),
210                present: 2,
211                min: 0,
212                max: 1,
213                codes: vec!["A".into(), "B".into()],
214            },
215        )
216        .with_field_path("SG4/SG8/SG10");
217        let loc = EdifactView.location(&issue);
218
219        // validate.rs:643 — format!("Package [{}P{}..{}] at {}: {} code(s)
220        // present (allowed {}..{}). Codes in package: [{}]", pkg_id,
221        // group.min, group.max, seg_path, present_count, group.min,
222        // group.max, code_list)
223        assert_eq!(
224            TechnicalNarrator.describe(&issue, loc.as_deref()),
225            "Package [1P0..1] at SG4/SG8/SG10: 2 code(s) present (allowed 0..1). Codes in package: [A, B]"
226        );
227    }
228
229    #[test]
230    fn code_not_allowed_for_pid_matches_the_legacy_message() {
231        let issue = ValidationIssue::new(
232            Severity::Warning,
233            IssueKind::CodeNotAllowedForPid {
234                value: "Z99".into(),
235                allowed: vec!["Z01".into(), "Z02".into(), "Z98".into()],
236            },
237        );
238
239        // validate.rs:895 — format!("Code '{}' is not allowed for this PID.
240        // Allowed: [{}]", value, allowed.join(", "))
241        assert_eq!(
242            TechnicalNarrator.describe(&issue, None),
243            "Code 'Z99' is not allowed for this PID. Allowed: [Z01, Z02, Z98]"
244        );
245    }
246
247    #[test]
248    fn unt_count_not_verifiable_matches_the_legacy_message() {
249        let issue = ValidationIssue::new(
250            Severity::Warning,
251            IssueKind::UntCountNotVerifiable { unh_count: 3 },
252        );
253
254        // validate.rs:1605 — format!("UNT validation requires per-message
255        // segments, found {unh_count} UNH segments")
256        assert_eq!(
257            TechnicalNarrator.describe(&issue, None),
258            "UNT validation requires per-message segments, found 3 UNH segments"
259        );
260    }
261
262    #[test]
263    fn structure_diagnostic_passes_its_detail_through_verbatim() {
264        // Unlike the other seven kinds, `StructureDiagnostic` was never built
265        // from a `format!` in validate.rs — it carries `mig_assembly`'s own
266        // diagnostic message (see `IssueKind::StructureDiagnostic`'s doc
267        // comment), so the narrator must reproduce it byte-for-byte with no
268        // added wording.
269        let detail = "Segment 'FTX' at position 15 is not defined in the PID-filtered MIG; \
270                       the assembler advanced past it";
271        let issue = ValidationIssue::new(
272            Severity::Warning,
273            IssueKind::StructureDiagnostic {
274                kind: StructureDiagnosticKind::UnexpectedSegment,
275                segment_id: "FTX".into(),
276                position: 15,
277                detail: detail.into(),
278            },
279        );
280
281        assert_eq!(TechnicalNarrator.describe(&issue, None), detail);
282    }
283}