1use crate::{IssueKind, UnresolvedConditions, ValidationIssue};
4
5use super::IssueNarrator;
6
7pub struct TechnicalNarrator;
13
14fn 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::ExclusiveAlternatives {
83 first,
84 second,
85 conditions,
86 } => format!(
87 "'{first}' and '{second}' are both sent, but each is required only where the other is absent: {}",
88 conditions
89 .iter()
90 .map(|c| format!("[{c}]"))
91 .collect::<Vec<_>>()
92 .join(", ")
93 ),
94 IssueKind::RepetitionCount { path, count } => format!(
95 "'{path}' is sent {count} times; its condition allows another number: {}",
96 issue.rule.as_deref().unwrap_or_default()
97 ),
98 IssueKind::CodeNotAllowedForPid { value, allowed } => format!(
99 "Code '{value}' is not allowed for this PID. Allowed: [{}]",
100 allowed.join(", ")
101 ),
102 IssueKind::AnswerNotInList { answer, list, allowed } => format!(
103 "Answer '{answer}'{} is not a code of {list}. Its codes: [{}]",
104 at(location),
105 allowed.join(", ")
106 ),
107 IssueKind::ValueNotNumeric { field_name } => format!(
108 "Field '{field_name}'{} is not a number; its format is {}",
109 at(location),
110 issue.expected_value.as_deref().unwrap_or_default()
111 ),
112 IssueKind::DateNotInFormat { field_name, format } => format!(
113 "Field '{field_name}'{} does not fit its date format {format}",
114 at(location)
115 ),
116 IssueKind::ValueTooLong { field_name, length, max } => format!(
117 "Field '{field_name}'{} has {length} characters; its format allows {max}",
118 at(location)
119 ),
120 IssueKind::IntervalNotPositive { begin, end } => format!(
121 "Period '{begin}'..'{end}' ends at {}, not after it begins ({})",
122 issue.actual_value.as_deref().unwrap_or_default(),
123 issue
124 .expected_value
125 .as_deref()
126 .unwrap_or_default()
127 .trim_start_matches("> ")
128 ),
129 IssueKind::ReferenceNotFound { reference, value, targets } => format!(
130 "'{reference}' names '{value}', which is no {} of its transaction",
131 targets.join(" / ")
132 ),
133 IssueKind::UntSegmentCountMismatch { declared, actual } => {
134 format!("UNT segment count mismatch: declared {declared}, actual {actual}")
135 }
136 IssueKind::UntCountNotVerifiable { unh_count } => format!(
137 "UNT validation requires per-message segments, found {unh_count} UNH segments"
138 ),
139 IssueKind::Bo4eFieldDropped { path } => format!(
140 "BO4E field '{path}' is not in the message: no mapping of this PID writes it"
141 ),
142 IssueKind::StructureDiagnostic { detail, .. } => detail.clone(),
143 }
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use crate::display::{Bo4eView, EdifactView, IssueNarrator, IssueView, TechnicalNarrator};
150 use crate::{IssueKind, Severity, UnresolvedConditions, ValidationIssue};
151 use mig_assembly::StructureDiagnosticKind;
152
153 fn missing_field_issue() -> ValidationIssue {
154 ValidationIssue::new(
155 Severity::Error,
156 IssueKind::MissingRequiredField {
157 field_name: "Merkmal, Code".into(),
158 },
159 )
160 .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
161 .with_bo4e_path("stammdaten.Marktlokation.haushaltskunde")
162 }
163
164 #[test]
165 fn edifact_view_narrates_with_the_edifact_path() {
166 let issue = missing_field_issue();
167 let loc = EdifactView.location(&issue);
168 assert_eq!(loc.as_deref(), Some("SG4/SG8/SG10/CCI/C240/7037"));
169 assert_eq!(
170 TechnicalNarrator.describe(&issue, loc.as_deref()),
171 "Required field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is missing"
172 );
173 }
174
175 #[test]
176 fn bo4e_view_narrates_with_the_bo4e_path() {
177 let issue = missing_field_issue();
178 let loc = Bo4eView.location(&issue);
179 assert_eq!(
180 loc.as_deref(),
181 Some("stammdaten.Marktlokation.haushaltskunde")
182 );
183 assert_eq!(
184 TechnicalNarrator.describe(&issue, loc.as_deref()),
185 "Required field 'Merkmal, Code' at stammdaten.Marktlokation.haushaltskunde is missing"
186 );
187 }
188
189 #[test]
190 fn bo4e_view_has_no_location_for_envelope_issues() {
191 let issue = ValidationIssue::new(
192 Severity::Error,
193 IssueKind::UntSegmentCountMismatch {
194 declared: 30,
195 actual: 31,
196 },
197 )
198 .with_field_path("UNT/0074");
199
200 assert_eq!(Bo4eView.location(&issue), None);
201 assert_eq!(
202 TechnicalNarrator.describe(&issue, None),
203 "UNT segment count mismatch: declared 30, actual 31"
204 );
205 }
206
207 #[test]
212 fn field_condition_not_satisfied_matches_the_legacy_message() {
213 let issue = ValidationIssue::new(
214 Severity::Error,
215 IssueKind::FieldConditionNotSatisfied {
216 field_name: "Merkmal, Code".into(),
217 failed: vec![],
218 },
219 )
220 .with_field_path("SG4/SG8/SG10/CCI/C240/7037")
221 .with_rule("Muss [182]");
222 let loc = EdifactView.location(&issue);
223
224 assert_eq!(
227 TechnicalNarrator.describe(&issue, loc.as_deref()),
228 "Field 'Merkmal, Code' at SG4/SG8/SG10/CCI/C240/7037 is present but does not satisfy condition: Muss [182]"
229 );
230 }
231
232 #[test]
233 fn condition_unknown_joins_multiple_id_groups_with_semicolons() {
234 let issue = ValidationIssue::new(
235 Severity::Info,
236 IssueKind::ConditionUnknown {
237 field_name: "Merkmal, Code".into(),
238 unresolved: UnresolvedConditions {
239 external: vec![182],
240 undetermined: vec![6],
241 missing: vec![570],
242 },
243 },
244 )
245 .with_field_path("SG4/SG8/SG10/CCI/C240/7037");
246 let loc = EdifactView.location(&issue);
247
248 assert_eq!(
254 TechnicalNarrator.describe(&issue, loc.as_deref()),
255 "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])"
256 );
257 }
258
259 #[test]
260 fn package_cardinality_matches_the_legacy_message() {
261 let issue = ValidationIssue::new(
262 Severity::Error,
263 IssueKind::PackageCardinality {
264 package_id: "1".into(),
265 present: 2,
266 min: 0,
267 max: 1,
268 codes: vec!["A".into(), "B".into()],
269 },
270 )
271 .with_field_path("SG4/SG8/SG10");
272 let loc = EdifactView.location(&issue);
273
274 assert_eq!(
279 TechnicalNarrator.describe(&issue, loc.as_deref()),
280 "Package [1P0..1] at SG4/SG8/SG10: 2 code(s) present (allowed 0..1). Codes in package: [A, B]"
281 );
282 }
283
284 #[test]
285 fn code_not_allowed_for_pid_matches_the_legacy_message() {
286 let issue = ValidationIssue::new(
287 Severity::Warning,
288 IssueKind::CodeNotAllowedForPid {
289 value: "Z99".into(),
290 allowed: vec!["Z01".into(), "Z02".into(), "Z98".into()],
291 },
292 );
293
294 assert_eq!(
297 TechnicalNarrator.describe(&issue, None),
298 "Code 'Z99' is not allowed for this PID. Allowed: [Z01, Z02, Z98]"
299 );
300 }
301
302 #[test]
303 fn unt_count_not_verifiable_matches_the_legacy_message() {
304 let issue = ValidationIssue::new(
305 Severity::Warning,
306 IssueKind::UntCountNotVerifiable { unh_count: 3 },
307 );
308
309 assert_eq!(
312 TechnicalNarrator.describe(&issue, None),
313 "UNT validation requires per-message segments, found 3 UNH segments"
314 );
315 }
316
317 #[test]
318 fn structure_diagnostic_passes_its_detail_through_verbatim() {
319 let detail = "Segment 'FTX' at position 15 is not defined in the PID-filtered MIG; \
325 the assembler advanced past it";
326 let issue = ValidationIssue::new(
327 Severity::Warning,
328 IssueKind::StructureDiagnostic {
329 kind: StructureDiagnosticKind::UnexpectedSegment,
330 segment_id: "FTX".into(),
331 position: 15,
332 detail: detail.into(),
333 },
334 );
335
336 assert_eq!(TechnicalNarrator.describe(&issue, None), detail);
337 }
338}