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