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