Skip to main content

mig_bo4e/
pid_validation.rs

1//! PID validation errors — typed, LLM-consumable error reports.
2
3use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt;
6
7use serde_json::Value;
8
9use crate::pid_requirements::{
10    CodeValue, EntityGroupRequirement, EntityRequirement, EntityScope, EntityVariantRequirement,
11    FieldRequirement, KindSelector, NestedElementKind, NestedListRequirement, PidRequirements,
12    VariantQualifier,
13};
14
15/// Severity of a validation error.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Severity {
18    /// Field is unconditionally required (Muss/X) or condition evaluated to True.
19    Error,
20    /// Condition evaluated to Unknown (depends on external context).
21    Warning,
22}
23
24/// A single PID validation error.
25#[derive(Debug, Clone)]
26pub enum PidValidationError {
27    /// An entire entity is missing from the interchange.
28    MissingEntity {
29        entity: String,
30        ahb_status: String,
31        severity: Severity,
32    },
33    /// A required field is None/missing.
34    MissingField {
35        entity: String,
36        field: String,
37        ahb_status: String,
38        rust_type: Option<String>,
39        valid_values: Vec<(String, String)>,
40        severity: Severity,
41    },
42    /// A code field has a value not in the allowed set.
43    InvalidCode {
44        entity: String,
45        field: String,
46        value: String,
47        valid_values: Vec<(String, String)>,
48    },
49    /// Something is present although its condition does not hold: an entity
50    /// (`field` empty), a code (`value`) or a list element. Only a
51    /// condition-aware validator raises it, for a `Muss`/`X` status with a
52    /// condition that evaluates to false where the element sits. A warning for
53    /// now, while the check proves itself on real messages.
54    NotAllowed {
55        entity: String,
56        field: String,
57        value: Option<String>,
58        ahb_status: String,
59        severity: Severity,
60    },
61}
62
63impl PidValidationError {
64    pub fn severity(&self) -> &Severity {
65        match self {
66            Self::MissingEntity { severity, .. } => severity,
67            Self::MissingField { severity, .. } => severity,
68            Self::NotAllowed { severity, .. } => severity,
69            Self::InvalidCode { .. } => &Severity::Error,
70        }
71    }
72
73    pub fn is_error(&self) -> bool {
74        matches!(self.severity(), Severity::Error)
75    }
76}
77
78impl fmt::Display for PidValidationError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            PidValidationError::MissingEntity {
82                entity,
83                ahb_status,
84                severity,
85            } => {
86                let label = severity_label(severity);
87                write!(
88                    f,
89                    "{label}: missing entity '{entity}' (required: {ahb_status})"
90                )
91            }
92            PidValidationError::MissingField {
93                entity,
94                field,
95                ahb_status,
96                rust_type,
97                valid_values,
98                severity,
99            } => {
100                let label = severity_label(severity);
101                write!(
102                    f,
103                    "{label}: missing {entity}.{field} (required: {ahb_status})"
104                )?;
105                if let Some(rt) = rust_type {
106                    write!(f, "\n  → type: {rt}")?;
107                }
108                if !valid_values.is_empty() {
109                    let codes: Vec<String> = valid_values
110                        .iter()
111                        .map(|(code, meaning)| {
112                            if meaning.is_empty() {
113                                code.clone()
114                            } else {
115                                format!("{code} ({meaning})")
116                            }
117                        })
118                        .collect();
119                    write!(f, "\n  → valid: {}", codes.join(", "))?;
120                }
121                Ok(())
122            }
123            PidValidationError::InvalidCode {
124                entity,
125                field,
126                value,
127                valid_values,
128            } => {
129                write!(f, "INVALID: {entity}.{field} = \"{value}\"")?;
130                if !valid_values.is_empty() {
131                    let codes: Vec<String> = valid_values.iter().map(|(c, _)| c.clone()).collect();
132                    write!(f, "\n  → valid: {}", codes.join(", "))?;
133                }
134                Ok(())
135            }
136            PidValidationError::NotAllowed {
137                entity,
138                field,
139                value,
140                ahb_status,
141                severity,
142            } => {
143                write!(f, "{}: {entity}", severity_label(severity))?;
144                if !field.is_empty() {
145                    write!(f, ".{field}")?;
146                }
147                if let Some(value) = value {
148                    write!(f, " = \"{value}\"")?;
149                }
150                write!(
151                    f,
152                    " present although its condition does not hold ({ahb_status})"
153                )
154            }
155        }
156    }
157}
158
159fn severity_label(severity: &Severity) -> &'static str {
160    match severity {
161        Severity::Error => "ERROR",
162        Severity::Warning => "WARNING",
163    }
164}
165
166/// A collection of validation errors for a PID.
167pub struct ValidationReport(pub Vec<PidValidationError>);
168
169impl ValidationReport {
170    /// Returns true if the report contains any errors (not just warnings).
171    pub fn has_errors(&self) -> bool {
172        self.0.iter().any(|e| e.is_error())
173    }
174
175    /// Returns only the errors (not warnings).
176    pub fn errors(&self) -> Vec<&PidValidationError> {
177        self.0.iter().filter(|e| e.is_error()).collect()
178    }
179
180    /// Returns true if the report is empty (no errors or warnings).
181    pub fn is_empty(&self) -> bool {
182        self.0.is_empty()
183    }
184
185    /// Returns the number of validation errors.
186    pub fn len(&self) -> usize {
187        self.0.len()
188    }
189}
190
191impl fmt::Display for ValidationReport {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        for (i, err) in self.0.iter().enumerate() {
194            if i > 0 {
195                writeln!(f)?;
196            }
197            write!(f, "{err}")?;
198        }
199        Ok(())
200    }
201}
202
203// ── Validation Logic ──────────────────────────────────────────────────────
204
205/// Validate a BO4E JSON value against PID requirements.
206///
207/// Validates ALL entities (both message-level and transaction-level).
208/// Use [`validate_pid_json_transaction`] to validate only transaction-level entities.
209///
210/// Walks the requirements and checks:
211/// 1. Required entities are present in the JSON
212/// 2. Required fields are present within each entity
213/// 3. Code fields have values in the allowed set
214pub fn validate_pid_json(json: &Value, requirements: &PidRequirements) -> Vec<PidValidationError> {
215    validate_entities(json, &requirements.entities, None)
216}
217
218/// Validate only transaction-level entities in a BO4E JSON value.
219///
220/// Skips message-level entities (e.g., Marktteilnehmer, Kontakt from SG2/SG3)
221/// that are outside the transaction scope. Use this when validating a transaction
222/// payload that doesn't include message-level data.
223pub fn validate_pid_json_transaction(
224    json: &Value,
225    requirements: &PidRequirements,
226) -> Vec<PidValidationError> {
227    validate_entities(json, &requirements.entities, Some(EntityScope::Transaction))
228}
229
230/// Internal: validate entities, optionally filtering by scope.
231fn validate_entities(
232    json: &Value,
233    entities: &[EntityRequirement],
234    scope_filter: Option<EntityScope>,
235) -> Vec<PidValidationError> {
236    let mut errors = Vec::new();
237
238    for entity_req in entities {
239        // Skip entities not matching the requested scope
240        if let Some(ref scope) = scope_filter {
241            if &entity_req.scope != scope {
242                continue;
243            }
244        }
245
246        let key = to_camel_case(&entity_req.entity);
247
248        match json.get(&key) {
249            None | Some(serde_json::Value::Null) => {
250                if is_unconditionally_required(&entity_req.ahb_status) {
251                    errors.push(PidValidationError::MissingEntity {
252                        entity: entity_req.entity.clone(),
253                        ahb_status: entity_req.ahb_status.clone(),
254                        severity: Severity::Error,
255                    });
256                }
257            }
258            Some(val) => {
259                // An array is one element per repetition, whatever the schema
260                // says the group allows (a merged group can count MaxRep 1).
261                if let Some(arr) = val.as_array() {
262                    for element in arr {
263                        validate_entity_fields(element, entity_req, &mut errors);
264                    }
265                } else {
266                    validate_entity_fields(val, entity_req, &mut errors);
267                }
268            }
269        }
270    }
271
272    errors
273}
274
275/// Traverse a dot-separated path in a JSON value, trying both the original
276/// key and its camelCase variant at each level.
277pub fn get_nested<'a>(json: &'a Value, path: &str) -> Option<&'a Value> {
278    // A list target (`werte[].code`): the value in the first element that has
279    // one — a list with the field present counts as present.
280    if let Some((list, rest)) = path.split_once("[].") {
281        return get_nested(json, list)?
282            .as_array()?
283            .iter()
284            .find_map(|item| get_nested(item, rest).filter(|v| !v.is_null()));
285    }
286    let mut current = json;
287    for part in path.split('.') {
288        current = current.get(part).or_else(|| {
289            if part.contains('_') {
290                current.get(snake_to_camel_case(part))
291            } else {
292                None
293            }
294        })?;
295    }
296    Some(current)
297}
298
299/// Validate fields within a single entity JSON object.
300fn validate_entity_fields(
301    entity_json: &Value,
302    entity_req: &EntityRequirement,
303    errors: &mut Vec<PidValidationError>,
304) {
305    let fields = effective_field_requirements(entity_req, entity_json);
306    let exempt =
307        fields_of_unrequired_absent_groups(entity_req, entity_json, is_unconditionally_required);
308    for field_req in fields.iter() {
309        // Traverse dot-separated paths (e.g. "produktIdentifikation.funktion")
310        // and try camelCase variants at each level for typed struct compatibility.
311        let val = get_nested(entity_json, &field_req.bo4e_name);
312
313        // Treat null values as missing — JSON null means "not provided"
314        let val = val.filter(|v| !v.is_null());
315
316        match val {
317            None if exempt.contains(field_req.bo4e_name.as_str()) => {}
318            None => {
319                if is_unconditionally_required(&field_req.ahb_status) {
320                    errors.push(PidValidationError::MissingField {
321                        entity: entity_req.entity.clone(),
322                        field: field_req.bo4e_name.clone(),
323                        ahb_status: field_req.ahb_status.clone(),
324                        rust_type: field_req.enum_name.clone(),
325                        valid_values: code_values_to_tuples(&field_req.valid_codes),
326                        severity: Severity::Error,
327                    });
328                }
329            }
330            Some(val) => {
331                validate_code_value(val, entity_req, field_req, errors);
332            }
333        }
334    }
335    validate_nested_lists(
336        &entity_req.entity,
337        entity_json,
338        &entity_req.nested,
339        "",
340        &|status, _| is_unconditionally_required(status).then_some(Severity::Error),
341        &|_| None,
342        // Only a condition-aware validator can tell a condition does not hold.
343        &|_, _| false,
344        errors,
345    );
346}
347
348/// Validate the lists nested in one entity element (see
349/// [`NestedListRequirement`]).
350///
351/// `required(status, position)` says whether a status demands its part of the
352/// message here, and how firmly: `position` is where in the element the part
353/// is (`[("zuordnungen", 3)]` for the fields of a list element, `[]` for the
354/// list itself), so a condition can be judged in that element's own group
355/// instance ("im selben CCI"). `prefix` names the enclosing list for findings
356/// in a list nested in another (`betreiber[].`).
357pub fn validate_nested_lists(
358    entity: &str,
359    element: &Value,
360    lists: &[NestedListRequirement],
361    prefix: &str,
362    required: &dyn Fn(&str, &[(String, usize)]) -> Option<Severity>,
363    variant_holds: &dyn Fn(&VariantQualifier) -> Option<bool>,
364    forbidden: &dyn Fn(&str, &[(String, usize)]) -> bool,
365    errors: &mut Vec<PidValidationError>,
366) {
367    nested_lists_at(
368        entity,
369        element,
370        lists,
371        prefix,
372        &mut Vec::new(),
373        required,
374        variant_holds,
375        forbidden,
376        errors,
377    );
378}
379
380/// [`validate_nested_lists`] for the element at `position`.
381#[allow(clippy::too_many_arguments)]
382fn nested_lists_at(
383    entity: &str,
384    element: &Value,
385    lists: &[NestedListRequirement],
386    prefix: &str,
387    position: &mut Vec<(String, usize)>,
388    required: &dyn Fn(&str, &[(String, usize)]) -> Option<Severity>,
389    variant_holds: &dyn Fn(&VariantQualifier) -> Option<bool>,
390    forbidden: &dyn Fn(&str, &[(String, usize)]) -> bool,
391    errors: &mut Vec<PidValidationError>,
392) {
393    // A kind of another transaction variant does not apply here; one whose
394    // variant cannot be told (the basic validator has no tree) is not demanded.
395    let applies = |kind: &NestedElementKind| {
396        kind.transaction_variant
397            .as_ref()
398            .map_or(Some(true), variant_holds)
399    };
400    // Several requirements may write one list (one per variant of the parent's
401    // group, e.g. six SG8 variants feeding `ZaehlerDaten.zuordnungen`).
402    let mut fields: Vec<&str> = lists.iter().map(|l| l.field.as_str()).collect();
403    fields.sort_unstable();
404    fields.dedup();
405    for field in fields {
406        // Only the lists of this parent's variant (`kontaktwege` of the Z08
407        // partner, not of every partner).
408        let candidates: Vec<&NestedListRequirement> = lists
409            .iter()
410            .filter(|l| l.field == field)
411            .filter(|l| {
412                l.parent_selector
413                    .iter()
414                    .all(|selector| selector_matches(selector, element))
415            })
416            .collect();
417        if candidates.is_empty() {
418            continue;
419        }
420        let items: &[Value] = get_nested(element, field)
421            .and_then(|v| v.as_array())
422            .map_or(&[], |a| a.as_slice());
423        let label = format!("{prefix}{field}");
424        let alone = candidates.len() == 1;
425
426        // The requirement this parent's list follows: the only one, or the one
427        // whose kinds every element is. Otherwise which kinds are needed here
428        // cannot be told, and only the elements present are judged.
429        let chosen = match &candidates[..] {
430            [only] => Some(*only),
431            _ if items.is_empty() => None,
432            _ => {
433                let fitting: Vec<&&NestedListRequirement> = candidates
434                    .iter()
435                    .filter(|l| items.iter().all(|item| kind_of(l, item, false).is_some()))
436                    .collect();
437                match fitting[..] {
438                    [one] => Some(*one),
439                    _ => None,
440                }
441            }
442        };
443
444        if let Some(list) = chosen {
445            for kind in &list.kinds {
446                if applies(kind) != Some(true) {
447                    continue;
448                }
449                let present = if alone && list.kinds.len() == 1 {
450                    !items.is_empty()
451                } else {
452                    items.iter().any(|item| kind_matches(kind, item))
453                };
454                if present {
455                    continue;
456                }
457                if let Some(severity) = required(&kind.ahb_status, position) {
458                    let codes = kind.selector.first().map_or(&[][..], |s| &s.codes[..]);
459                    // Named by its selector's code where the list has several
460                    // kinds to tell apart (`zuordnungen[zugeordneterMarktpartner]`).
461                    let name = if alone && list.kinds.len() == 1 {
462                        String::new()
463                    } else {
464                        codes
465                            .first()
466                            .map(|c| c.bo4e_value.clone().unwrap_or_else(|| c.code.clone()))
467                            .unwrap_or_default()
468                    };
469                    errors.push(PidValidationError::MissingField {
470                        entity: entity.to_string(),
471                        field: format!("{label}[{name}]"),
472                        ahb_status: kind.ahb_status.clone(),
473                        rust_type: None,
474                        valid_values: code_values_to_tuples(codes),
475                        severity,
476                    });
477                }
478            }
479        }
480
481        for (index, item) in items.iter().enumerate() {
482            position.push((field.to_string(), index));
483            let here = position.clone();
484            let required_here = |status: &str| required(status, &here);
485            let matching: Vec<(&NestedListRequirement, &NestedElementKind)> = match chosen {
486                Some(list) => kind_of(list, item, alone)
487                    .filter(|k| applies(k) != Some(false))
488                    .map(|k| (list, k))
489                    .into_iter()
490                    .collect(),
491                None => candidates
492                    .iter()
493                    .flat_map(|l| {
494                        l.kinds
495                            .iter()
496                            .filter(|k| applies(k) != Some(false))
497                            .filter(|k| kind_matches(k, item))
498                            .map(move |k| (*l, k))
499                    })
500                    .collect(),
501            };
502            // Which variant of the parent's group an element came from is not
503            // recorded: it is judged by the matching kind it satisfies best, a
504            // kind with a selector before one without.
505            let best = matching
506                .iter()
507                .map(|(l, k)| {
508                    (
509                        *l,
510                        *k,
511                        element_findings(entity, &label, k, item, &required_here),
512                    )
513                })
514                .min_by_key(|(_, k, f)| (f.len(), k.selector.is_empty()));
515            if let Some((list, kind, findings)) = best {
516                errors.extend(findings);
517                // Present although its kind's condition does not hold, or
518                // carrying a field or code whose condition does not.
519                let forbidden_here = |status: &str| forbidden(status, &here);
520                if forbidden_here(&kind.ahb_status) {
521                    let name = kind
522                        .selector
523                        .first()
524                        .and_then(|s| s.codes.first())
525                        .map(|c| c.bo4e_value.clone().unwrap_or_else(|| c.code.clone()))
526                        .unwrap_or_default();
527                    errors.push(PidValidationError::NotAllowed {
528                        entity: entity.to_string(),
529                        field: format!("{label}[{name}]"),
530                        value: None,
531                        ahb_status: kind.ahb_status.clone(),
532                        severity: Severity::Warning,
533                    });
534                } else {
535                    errors.extend(not_allowed_codes(
536                        entity,
537                        &format!("{label}[]."),
538                        &kind.fields,
539                        item,
540                        &forbidden_here,
541                    ));
542                }
543                nested_lists_at(
544                    entity,
545                    item,
546                    &list.nested,
547                    &format!("{label}[]."),
548                    position,
549                    required,
550                    variant_holds,
551                    forbidden,
552                    errors,
553                );
554            }
555            position.pop();
556        }
557    }
558}
559
560/// The kind of `list` an element is, if any. A list alone on its field with a
561/// single kind takes every element as that kind, so a wrong code in its
562/// selector is reported as a wrong code rather than as a missing kind.
563fn kind_of<'l>(
564    list: &'l NestedListRequirement,
565    item: &Value,
566    alone: bool,
567) -> Option<&'l NestedElementKind> {
568    match &list.kinds[..] {
569        [only] if alone => Some(only),
570        kinds => kinds.iter().find(|k| kind_matches(k, item)),
571    }
572}
573
574/// Whether `item` is of `kind`: every selector field holds one of its codes,
575/// in raw or translated spelling.
576fn kind_matches(kind: &NestedElementKind, item: &Value) -> bool {
577    kind.selector
578        .iter()
579        .all(|selector| selector_matches(selector, item))
580}
581
582/// Whether `item`'s `selector.field` holds one of the selector's codes.
583fn selector_matches(selector: &KindSelector, item: &Value) -> bool {
584    get_nested(item, &selector.field)
585        .and_then(code_field_value)
586        .is_some_and(|value| {
587            selector
588                .codes
589                .iter()
590                .any(|c| c.code == value || c.bo4e_value.as_deref() == Some(value))
591        })
592}
593
594/// The codes `element` carries although their condition does not hold: codes
595/// sent in a segment of their own condition
596/// ([`CodeValue::ahb_status`](crate::pid_requirements::CodeValue), SG10
597/// CAV+ZB4 "Messstellenbetreiber Alt"). A plain field's status is not judged:
598/// its conditions state what the value must be (`[22]` "Es ist die Zeitraum-ID
599/// … einzutragen"), which the EDIFACT validator reports. `label` prefixes the
600/// field names (`zuordnungen[].`).
601pub fn not_allowed_codes(
602    entity: &str,
603    label: &str,
604    fields: &[FieldRequirement],
605    element: &Value,
606    forbidden: &dyn Fn(&str) -> bool,
607) -> Vec<PidValidationError> {
608    let mut out = Vec::new();
609    for field_req in fields {
610        let values = all_nested(element, &field_req.bo4e_name);
611        if values.is_empty() {
612            continue;
613        }
614        let name = format!("{label}{}", field_req.bo4e_name);
615        for value in values {
616            let Some(code) = code_field_value(value) else {
617                continue;
618            };
619            let status = field_req
620                .valid_codes
621                .iter()
622                .find(|cv| cv.code == code || cv.bo4e_value.as_deref() == Some(code))
623                .and_then(|cv| cv.ahb_status.as_deref());
624            if let Some(status) = status.filter(|s| forbidden(s)) {
625                out.push(PidValidationError::NotAllowed {
626                    entity: entity.to_string(),
627                    field: name.clone(),
628                    value: Some(code.to_string()),
629                    ahb_status: status.to_string(),
630                    severity: Severity::Warning,
631                });
632            }
633        }
634    }
635    out
636}
637
638/// The findings on one list element judged as `kind`: its missing fields and
639/// wrong codes.
640fn element_findings(
641    entity: &str,
642    label: &str,
643    kind: &NestedElementKind,
644    item: &Value,
645    required: &dyn Fn(&str) -> Option<Severity>,
646) -> Vec<PidValidationError> {
647    let mut out = Vec::new();
648    for field_req in &kind.fields {
649        let name = format!("{label}[].{}", field_req.bo4e_name);
650        let values = all_nested(item, &field_req.bo4e_name);
651        if values.is_empty() {
652            if let Some(severity) = required(&field_req.ahb_status) {
653                out.push(PidValidationError::MissingField {
654                    entity: entity.to_string(),
655                    field: name,
656                    ahb_status: field_req.ahb_status.clone(),
657                    rust_type: field_req.enum_name.clone(),
658                    valid_values: code_values_to_tuples(&field_req.valid_codes),
659                    severity,
660                });
661            }
662            continue;
663        }
664        for value in values {
665            if let Some(value) = invalid_code_value(value, field_req) {
666                out.push(PidValidationError::InvalidCode {
667                    entity: entity.to_string(),
668                    field: name.clone(),
669                    value,
670                    valid_values: code_values_to_tuples(&field_req.valid_codes),
671                });
672            }
673        }
674    }
675    out
676}
677
678/// Every non-null value at `path`: all elements' for a list target
679/// (`werte[].code`), where [`get_nested`] finds only the first.
680fn all_nested<'a>(json: &'a Value, path: &str) -> Vec<&'a Value> {
681    if let Some((list, rest)) = path.split_once("[].") {
682        return get_nested(json, list)
683            .and_then(|v| v.as_array())
684            .map(|items| {
685                items
686                    .iter()
687                    .flat_map(|item| all_nested(item, rest))
688                    .collect()
689            })
690            .unwrap_or_default();
691    }
692    get_nested(json, path)
693        .filter(|v| !v.is_null())
694        .into_iter()
695        .collect()
696}
697
698/// Validate that a code field's value is in the allowed set.
699fn validate_code_value(
700    val: &Value,
701    entity_req: &EntityRequirement,
702    field_req: &FieldRequirement,
703    errors: &mut Vec<PidValidationError>,
704) {
705    if let Some(value) = invalid_code_value(val, field_req) {
706        errors.push(PidValidationError::InvalidCode {
707            entity: entity_req.entity.clone(),
708            field: field_req.bo4e_name.clone(),
709            value,
710            valid_values: code_values_to_tuples(&field_req.valid_codes),
711        });
712    }
713}
714
715/// The code carried by a BO4E code field: a plain string, or the `code` member of
716/// a `{code, meaning, enum}` object as written by `from_edifact`.
717pub fn code_field_value(val: &Value) -> Option<&str> {
718    val.as_str()
719        .or_else(|| val.get("code").and_then(|c| c.as_str()))
720}
721
722/// Check a code field's value against `field_req.valid_codes`.
723///
724/// Returns the offending value if it is invalid, `None` if it is valid or not a
725/// code value at all. A value is valid when it equals a valid raw EDIFACT code
726/// or the BO4E value the mapping's `enum_map` translates a valid code to — the
727/// two spellings `to_edifact` accepts.
728pub fn invalid_code_value(val: &Value, field_req: &FieldRequirement) -> Option<String> {
729    if field_req.valid_codes.is_empty() {
730        return None;
731    }
732    let value = code_field_value(val)?;
733    let is_valid = field_req
734        .valid_codes
735        .iter()
736        .any(|cv| cv.code == value || cv.bo4e_value.as_deref() == Some(value));
737    (!is_valid).then(|| value.to_string())
738}
739
740/// The field requirements that apply to one element of an entity.
741///
742/// For an entity without [`EntityRequirement::variants`] this is simply its
743/// `fields`. For a multi-variant entity (e.g. `Geschaeftspartner` fed by
744/// `sg12_z03`/`sg12_z07`/…), the element's discriminator value (raw code or
745/// `enum_map`ped BO4E value, string or code object) selects the matching
746/// variant, and the variant-owned fields are replaced by that variant's
747/// requirements — fields the variant's group lacks do not apply.
748///
749/// If the discriminator is missing or matches no variant, all variants are
750/// candidates and are combined leniently: codes are unioned, and a field keeps
751/// its AHB status only if every candidate agrees on it (otherwise it is treated
752/// as optional), so an unidentifiable element is never held to the required
753/// fields of a variant it may not be.
754pub fn effective_field_requirements<'a>(
755    entity_req: &'a EntityRequirement,
756    element: &Value,
757) -> Cow<'a, [FieldRequirement]> {
758    if entity_req.variants.is_empty() {
759        return Cow::Borrowed(&entity_req.fields);
760    }
761
762    // Candidate variants, per discriminator field.
763    let mut by_field: BTreeMap<&str, Vec<&EntityVariantRequirement>> = BTreeMap::new();
764    for v in &entity_req.variants {
765        by_field
766            .entry(v.discriminator_field.as_str())
767            .or_default()
768            .push(v);
769    }
770    let mut candidates: Vec<&EntityVariantRequirement> = Vec::new();
771    for (field, group) in by_field {
772        let value = get_nested(element, field).and_then(code_field_value);
773        let matched: Vec<&EntityVariantRequirement> = group
774            .iter()
775            .copied()
776            .filter(|v| value.is_some_and(|s| v.code == s || v.bo4e_value.as_deref() == Some(s)))
777            .collect();
778        candidates.extend(if matched.is_empty() { group } else { matched });
779    }
780
781    // Fields governed by variants (in first-seen order).
782    let mut owned: Vec<&str> = Vec::new();
783    let mut owned_set: BTreeSet<&str> = BTreeSet::new();
784    for v in &entity_req.variants {
785        for f in &v.fields {
786            if owned_set.insert(f.bo4e_name.as_str()) {
787                owned.push(f.bo4e_name.as_str());
788            }
789        }
790    }
791
792    let mut combined: BTreeMap<&str, FieldRequirement> = BTreeMap::new();
793    for name in owned {
794        let reqs: Vec<&FieldRequirement> = candidates
795            .iter()
796            .filter_map(|v| v.fields.iter().find(|f| f.bo4e_name == name))
797            .collect();
798        let Some((first, rest)) = reqs.split_first() else {
799            continue; // not applicable to any candidate variant
800        };
801        let mut field = (*first).clone();
802        let mut statuses_agree = reqs.len() == candidates.len();
803        for r in rest {
804            if r.ahb_status != field.ahb_status {
805                statuses_agree = false;
806            }
807            for cv in &r.valid_codes {
808                if !field.valid_codes.iter().any(|c| c.code == cv.code) {
809                    field.valid_codes.push(cv.clone());
810                }
811            }
812        }
813        if !statuses_agree {
814            field.ahb_status = String::new();
815        }
816        combined.insert(name, field);
817    }
818
819    let mut result: Vec<FieldRequirement> = Vec::with_capacity(entity_req.fields.len());
820    for f in &entity_req.fields {
821        if owned_set.contains(f.bo4e_name.as_str()) {
822            if let Some(c) = combined.remove(f.bo4e_name.as_str()) {
823                result.push(c);
824            }
825        } else {
826            result.push(f.clone());
827        }
828    }
829    result.extend(combined.into_values());
830    Cow::Owned(result)
831}
832
833/// The groups of a multi-group entity (see [`EntityRequirement::groups`]) that
834/// `element` carries no data for.
835pub fn absent_groups<'a>(
836    entity_req: &'a EntityRequirement,
837    element: &'a Value,
838) -> impl Iterator<Item = &'a EntityGroupRequirement> + 'a {
839    entity_req.groups.iter().filter(move |g| {
840        !g.fields
841            .iter()
842            .any(|f| get_nested(element, f).is_some_and(|v| !v.is_null()))
843    })
844}
845
846/// The fields `element` need not carry because every group writing them is
847/// absent from it and not required.
848///
849/// `group_required` decides from a group's AHB status. A present entity of a
850/// multi-group entity says nothing about any one of its groups: 55043's
851/// `Marktlokation` with only LOC+Z16 data has no ruhende Marktlokation, so the
852/// LOC+Z22 group's `X` fields do not apply — unless that group is itself
853/// required, in which case they are reported as usual.
854pub fn fields_of_unrequired_absent_groups<'a>(
855    entity_req: &'a EntityRequirement,
856    element: &'a Value,
857    mut group_required: impl FnMut(&str) -> bool,
858) -> BTreeSet<&'a str> {
859    let exempt: Vec<&EntityGroupRequirement> = absent_groups(entity_req, element)
860        .filter(|g| !group_required(&g.ahb_status))
861        .collect();
862    let mut fields = BTreeSet::new();
863    for g in &exempt {
864        for f in &g.fields {
865            // A field another group also writes stays, unless that group is
866            // exempt as well.
867            let kept_elsewhere = entity_req.groups.iter().any(|other| {
868                other.fields.contains(f) && !exempt.iter().any(|e| std::ptr::eq(*e, other))
869            });
870            if !kept_elsewhere {
871                fields.insert(f.as_str());
872            }
873        }
874    }
875    fields
876}
877
878/// Convert CodeValue vec to (code, meaning) tuples.
879fn code_values_to_tuples(codes: &[CodeValue]) -> Vec<(String, String)> {
880    codes
881        .iter()
882        .map(|cv| (cv.code.clone(), cv.meaning.clone()))
883        .collect()
884}
885
886/// Convert PascalCase entity name to camelCase JSON key.
887///
888/// "Prozessdaten" → "prozessdaten"
889/// "RuhendeMarktlokation" → "ruhendeMarktlokation"
890/// "Marktlokation" → "marktlokation"
891fn to_camel_case(s: &str) -> String {
892    if s.is_empty() {
893        return String::new();
894    }
895    let mut chars = s.chars();
896    let first = chars.next().unwrap();
897    let mut result = first.to_lowercase().to_string();
898    result.extend(chars);
899    result
900}
901
902/// Convert a snake_case field name to camelCase.
903///
904/// This mirrors what `#[serde(rename_all = "camelCase")]` does at runtime, allowing
905/// the validator to find fields in JSON that was produced by typed structs even when
906/// the requirement stores the field name as snake_case (as it comes from TOML).
907///
908/// Examples:
909/// - `"code_codepflege"` → `"codeCodepflege"`
910/// - `"vorgang_id"` → `"vorgangId"`
911/// - `"marktlokation"` → `"marktlokation"` (unchanged — no underscores)
912fn snake_to_camel_case(s: &str) -> String {
913    let mut result = String::with_capacity(s.len());
914    let mut capitalize_next = false;
915    for ch in s.chars() {
916        if ch == '_' {
917            capitalize_next = true;
918        } else if capitalize_next {
919            result.extend(ch.to_uppercase());
920            capitalize_next = false;
921        } else {
922            result.push(ch);
923        }
924    }
925    result
926}
927
928/// Returns true if the AHB status indicates an unconditionally required field.
929fn is_unconditionally_required(ahb_status: &str) -> bool {
930    matches!(ahb_status, "X" | "Muss" | "Soll")
931}
932
933#[cfg(test)]
934mod tests {
935    use super::*;
936
937    /// A list kind bound to a transaction variant (55070: SG10s only in the
938    /// IDE+24 variant) is demanded where that variant holds, and neither where
939    /// another holds nor where it cannot be told.
940    #[test]
941    fn a_variant_bound_kind_is_demanded_only_in_its_variant() {
942        use crate::pid_requirements::{NestedElementKind, NestedListRequirement, VariantQualifier};
943        let lists = vec![NestedListRequirement {
944            field: "zuordnungen".to_string(),
945            bo4e_type: "Zuordnung".to_string(),
946            source_path: "sg4.sg8_z22.sg10".to_string(),
947            kinds: vec![NestedElementKind {
948                ahb_status: "Muss".to_string(),
949                selector: vec![],
950                fields: vec![],
951                transaction_variant: Some(VariantQualifier {
952                    group: "SG4".to_string(),
953                    segment: "IDE".to_string(),
954                    codes: vec!["24".to_string()],
955                }),
956            }],
957            parent_selector: vec![],
958            nested: vec![],
959        }];
960        let demanded = |holds: Option<bool>| {
961            let mut errors = Vec::new();
962            validate_nested_lists(
963                "SummenzeitreihenDaten",
964                &serde_json::json!({}),
965                &lists,
966                "",
967                &|_, _| Some(Severity::Error),
968                &|_| holds,
969                &|_, _| false,
970                &mut errors,
971            );
972            errors.len()
973        };
974        assert_eq!(demanded(Some(true)), 1);
975        assert_eq!(demanded(Some(false)), 0);
976        assert_eq!(demanded(None), 0);
977    }
978    use crate::pid_requirements::{
979        Bo4eRefType, Cardinality, CodeValue, EntityRequirement, FieldRequirement, PidRequirements,
980    };
981    use serde_json::json;
982
983    fn sample_requirements() -> PidRequirements {
984        PidRequirements {
985            pid: "55001".to_string(),
986            beschreibung: "Anmeldung verb. MaLo".to_string(),
987            entities: vec![
988                EntityRequirement {
989                    entity: "Prozessdaten".to_string(),
990                    ref_type: Bo4eRefType::Object {
991                        type_name: "Prozessdaten".to_string(),
992
993                        cardinality: Cardinality::REQUIRED,
994                    },
995
996                    ahb_status: "Muss".to_string(),
997                    map_key: None,
998                    scope: EntityScope::Transaction,
999                    variants: vec![],
1000                    groups: vec![],
1001                    fields: vec![
1002                        FieldRequirement {
1003                            bo4e_name: "vorgangId".to_string(),
1004                            ahb_status: "X".to_string(),
1005                            field_type: "data".to_string(),
1006                            format: None,
1007                            enum_name: None,
1008                            valid_codes: vec![],
1009                            child_group: None,
1010                            ref_type: Bo4eRefType::Unknown,
1011                        },
1012                        FieldRequirement {
1013                            bo4e_name: "transaktionsgrund".to_string(),
1014                            ahb_status: "X".to_string(),
1015                            field_type: "code".to_string(),
1016                            format: None,
1017                            enum_name: Some("Transaktionsgrund".to_string()),
1018                            valid_codes: vec![
1019                                CodeValue {
1020                                    code: "E01".to_string(),
1021                                    meaning: "Ein-/Auszug (Einzug)".to_string(),
1022                                    enum_name: None,
1023                                    bo4e_value: None,
1024                                    ahb_status: None,
1025                                },
1026                                CodeValue {
1027                                    code: "E03".to_string(),
1028                                    meaning: "Wechsel".to_string(),
1029                                    enum_name: None,
1030                                    bo4e_value: None,
1031                                    ahb_status: None,
1032                                },
1033                            ],
1034                            child_group: None,
1035                            ref_type: Bo4eRefType::Unknown,
1036                        },
1037                    ],
1038                    nested: Vec::new(),
1039                },
1040                EntityRequirement {
1041                    entity: "Marktlokation".to_string(),
1042                    ref_type: Bo4eRefType::Object {
1043                        type_name: "Marktlokation".to_string(),
1044
1045                        cardinality: Cardinality::REQUIRED,
1046                    },
1047
1048                    ahb_status: "Muss".to_string(),
1049                    map_key: None,
1050                    scope: EntityScope::Transaction,
1051                    variants: vec![],
1052                    groups: vec![],
1053                    fields: vec![
1054                        FieldRequirement {
1055                            bo4e_name: "marktlokationsId".to_string(),
1056                            ahb_status: "X".to_string(),
1057                            field_type: "data".to_string(),
1058                            format: None,
1059                            enum_name: None,
1060                            valid_codes: vec![],
1061                            child_group: None,
1062                            ref_type: Bo4eRefType::Unknown,
1063                        },
1064                        FieldRequirement {
1065                            bo4e_name: "haushaltskunde".to_string(),
1066                            ahb_status: "X".to_string(),
1067                            field_type: "code".to_string(),
1068                            format: None,
1069                            enum_name: Some("Haushaltskunde".to_string()),
1070                            valid_codes: vec![
1071                                CodeValue {
1072                                    code: "Z15".to_string(),
1073                                    meaning: "Ja".to_string(),
1074                                    enum_name: None,
1075                                    bo4e_value: None,
1076                                    ahb_status: None,
1077                                },
1078                                CodeValue {
1079                                    code: "Z18".to_string(),
1080                                    meaning: "Nein".to_string(),
1081                                    enum_name: None,
1082                                    bo4e_value: None,
1083                                    ahb_status: None,
1084                                },
1085                            ],
1086                            child_group: None,
1087                            ref_type: Bo4eRefType::Unknown,
1088                        },
1089                    ],
1090                    nested: Vec::new(),
1091                },
1092                EntityRequirement {
1093                    entity: "Geschaeftspartner".to_string(),
1094                    ref_type: Bo4eRefType::Object {
1095                        type_name: "Geschaeftspartner".to_string(),
1096
1097                        cardinality: Cardinality {
1098                            min: 1,
1099                            max: Some(7),
1100                        },
1101                    },
1102
1103                    ahb_status: "Muss".to_string(),
1104                    map_key: None,
1105                    scope: EntityScope::Transaction,
1106                    variants: vec![],
1107                    groups: vec![],
1108                    fields: vec![FieldRequirement {
1109                        bo4e_name: "identifikation".to_string(),
1110                        ahb_status: "X".to_string(),
1111                        field_type: "data".to_string(),
1112                        format: None,
1113                        enum_name: None,
1114                        valid_codes: vec![],
1115                        child_group: None,
1116                        ref_type: Bo4eRefType::Unknown,
1117                    }],
1118                    nested: Vec::new(),
1119                },
1120            ],
1121        }
1122    }
1123
1124    #[test]
1125    fn test_validate_complete_json() {
1126        let reqs = sample_requirements();
1127        let json = json!({
1128            "prozessdaten": {
1129                "vorgangId": "ABC123",
1130                "transaktionsgrund": "E01"
1131            },
1132            "marktlokation": {
1133                "marktlokationsId": "51234567890",
1134                "haushaltskunde": "Z15"
1135            },
1136            "geschaeftspartner": [
1137                { "identifikation": "9900000000003" }
1138            ]
1139        });
1140
1141        let errors = validate_pid_json(&json, &reqs);
1142        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
1143    }
1144
1145    #[test]
1146    fn test_validate_missing_entity() {
1147        let reqs = sample_requirements();
1148        let json = json!({
1149            "prozessdaten": {
1150                "vorgangId": "ABC123",
1151                "transaktionsgrund": "E01"
1152            },
1153            "geschaeftspartner": [
1154                { "identifikation": "9900000000003" }
1155            ]
1156        });
1157        // Marktlokation is missing
1158
1159        let errors = validate_pid_json(&json, &reqs);
1160        assert_eq!(errors.len(), 1);
1161        match &errors[0] {
1162            PidValidationError::MissingEntity {
1163                entity,
1164                ahb_status,
1165                severity,
1166            } => {
1167                assert_eq!(entity, "Marktlokation");
1168                assert_eq!(ahb_status, "Muss");
1169                assert_eq!(severity, &Severity::Error);
1170            }
1171            other => panic!("Expected MissingEntity, got: {other:?}"),
1172        }
1173
1174        // Display check
1175        let msg = errors[0].to_string();
1176        assert!(msg.contains("ERROR"));
1177        assert!(msg.contains("Marktlokation"));
1178        assert!(msg.contains("Muss"));
1179    }
1180
1181    #[test]
1182    fn test_validate_missing_field() {
1183        let reqs = sample_requirements();
1184        let json = json!({
1185            "prozessdaten": {
1186                "transaktionsgrund": "E01"
1187                // vorgangId is missing
1188            },
1189            "marktlokation": {
1190                "marktlokationsId": "51234567890",
1191                "haushaltskunde": "Z15"
1192            },
1193            "geschaeftspartner": [
1194                { "identifikation": "9900000000003" }
1195            ]
1196        });
1197
1198        let errors = validate_pid_json(&json, &reqs);
1199        assert_eq!(errors.len(), 1);
1200        match &errors[0] {
1201            PidValidationError::MissingField {
1202                entity,
1203                field,
1204                ahb_status,
1205                severity,
1206                ..
1207            } => {
1208                assert_eq!(entity, "Prozessdaten");
1209                assert_eq!(field, "vorgangId");
1210                assert_eq!(ahb_status, "X");
1211                assert_eq!(severity, &Severity::Error);
1212            }
1213            other => panic!("Expected MissingField, got: {other:?}"),
1214        }
1215
1216        let msg = errors[0].to_string();
1217        assert!(msg.contains("ERROR"));
1218        assert!(msg.contains("Prozessdaten.vorgangId"));
1219    }
1220
1221    #[test]
1222    fn test_validate_invalid_code() {
1223        let reqs = sample_requirements();
1224        let json = json!({
1225            "prozessdaten": {
1226                "vorgangId": "ABC123",
1227                "transaktionsgrund": "E01"
1228            },
1229            "marktlokation": {
1230                "marktlokationsId": "51234567890",
1231                "haushaltskunde": "Z99"  // Invalid code
1232            },
1233            "geschaeftspartner": [
1234                { "identifikation": "9900000000003" }
1235            ]
1236        });
1237
1238        let errors = validate_pid_json(&json, &reqs);
1239        assert_eq!(errors.len(), 1);
1240        match &errors[0] {
1241            PidValidationError::InvalidCode {
1242                entity,
1243                field,
1244                value,
1245                valid_values,
1246            } => {
1247                assert_eq!(entity, "Marktlokation");
1248                assert_eq!(field, "haushaltskunde");
1249                assert_eq!(value, "Z99");
1250                assert_eq!(valid_values.len(), 2);
1251                assert!(valid_values.iter().any(|(c, _)| c == "Z15"));
1252                assert!(valid_values.iter().any(|(c, _)| c == "Z18"));
1253            }
1254            other => panic!("Expected InvalidCode, got: {other:?}"),
1255        }
1256
1257        let msg = errors[0].to_string();
1258        assert!(msg.contains("INVALID"));
1259        assert!(msg.contains("Z99"));
1260        assert!(msg.contains("Z15"));
1261    }
1262
1263    #[test]
1264    fn test_validate_array_entity() {
1265        let reqs = sample_requirements();
1266        let json = json!({
1267            "prozessdaten": {
1268                "vorgangId": "ABC123",
1269                "transaktionsgrund": "E01"
1270            },
1271            "marktlokation": {
1272                "marktlokationsId": "51234567890",
1273                "haushaltskunde": "Z15"
1274            },
1275            "geschaeftspartner": [
1276                { "identifikation": "9900000000003" },
1277                { }  // Missing identifikation in second element
1278            ]
1279        });
1280
1281        let errors = validate_pid_json(&json, &reqs);
1282        assert_eq!(errors.len(), 1);
1283        match &errors[0] {
1284            PidValidationError::MissingField { entity, field, .. } => {
1285                assert_eq!(entity, "Geschaeftspartner");
1286                assert_eq!(field, "identifikation");
1287            }
1288            other => panic!("Expected MissingField, got: {other:?}"),
1289        }
1290    }
1291
1292    #[test]
1293    fn test_to_camel_case() {
1294        assert_eq!(to_camel_case("Prozessdaten"), "prozessdaten");
1295        assert_eq!(
1296            to_camel_case("RuhendeMarktlokation"),
1297            "ruhendeMarktlokation"
1298        );
1299        assert_eq!(to_camel_case("Marktlokation"), "marktlokation");
1300        assert_eq!(to_camel_case(""), "");
1301    }
1302
1303    #[test]
1304    fn test_snake_to_camel_case() {
1305        assert_eq!(snake_to_camel_case("code_codepflege"), "codeCodepflege");
1306        assert_eq!(snake_to_camel_case("vorgang_id"), "vorgangId");
1307        assert_eq!(snake_to_camel_case("marktlokation"), "marktlokation");
1308        assert_eq!(snake_to_camel_case(""), "");
1309        assert_eq!(snake_to_camel_case("a_b_c"), "aBC");
1310    }
1311
1312    /// A field stored as snake_case in requirements (e.g. from TOML) must be found
1313    /// in JSON that was produced by a typed struct using `#[serde(rename_all = "camelCase")]`.
1314    #[test]
1315    fn test_camel_case_fallback_for_snake_case_bo4e_name() {
1316        let reqs = PidRequirements {
1317            pid: "55077".to_string(),
1318            beschreibung: "Test camelCase fallback".to_string(),
1319            entities: vec![EntityRequirement {
1320                entity: "Zuordnung".to_string(),
1321                ref_type: Bo4eRefType::Object {
1322                    type_name: "Zuordnung".to_string(),
1323
1324                    cardinality: Cardinality::REQUIRED,
1325                },
1326
1327                ahb_status: "Muss".to_string(),
1328                map_key: None,
1329                scope: EntityScope::Transaction,
1330                variants: vec![],
1331                groups: vec![],
1332                fields: vec![
1333                    FieldRequirement {
1334                        // snake_case as stored in TOML requirements
1335                        bo4e_name: "code_codepflege".to_string(),
1336                        ahb_status: "X".to_string(),
1337                        field_type: "data".to_string(),
1338                        format: None,
1339                        enum_name: None,
1340                        valid_codes: vec![],
1341                        child_group: None,
1342                        ref_type: Bo4eRefType::Unknown,
1343                    },
1344                    FieldRequirement {
1345                        bo4e_name: "codeliste".to_string(),
1346                        ahb_status: "X".to_string(),
1347                        field_type: "data".to_string(),
1348                        format: None,
1349                        enum_name: None,
1350                        valid_codes: vec![],
1351                        child_group: None,
1352                        ref_type: Bo4eRefType::Unknown,
1353                    },
1354                ],
1355                nested: Vec::new(),
1356            }],
1357        };
1358
1359        // JSON produced by a typed struct with #[serde(rename_all = "camelCase")]:
1360        // code_codepflege → codeCodepflege
1361        let json_camel = json!({
1362            "zuordnung": {
1363                "codeCodepflege": "DE_BDEW",
1364                "codeliste": "6"
1365            }
1366        });
1367
1368        let errors = validate_pid_json(&json_camel, &reqs);
1369        assert!(
1370            errors.is_empty(),
1371            "Expected no errors when field is present under camelCase key, got: {errors:?}"
1372        );
1373
1374        // Also verify that snake_case key in JSON still works (backward compat).
1375        let json_snake = json!({
1376            "zuordnung": {
1377                "code_codepflege": "DE_BDEW",
1378                "codeliste": "6"
1379            }
1380        });
1381
1382        let errors = validate_pid_json(&json_snake, &reqs);
1383        assert!(
1384            errors.is_empty(),
1385            "Expected no errors when field is present under snake_case key, got: {errors:?}"
1386        );
1387
1388        // When the field is truly absent, a MissingField error must still be raised.
1389        let json_missing = json!({
1390            "zuordnung": {
1391                "codeliste": "6"
1392            }
1393        });
1394
1395        let errors = validate_pid_json(&json_missing, &reqs);
1396        assert_eq!(errors.len(), 1);
1397        match &errors[0] {
1398            PidValidationError::MissingField { field, .. } => {
1399                assert_eq!(field, "code_codepflege");
1400            }
1401            other => panic!("Expected MissingField, got: {other:?}"),
1402        }
1403    }
1404
1405    #[test]
1406    fn test_is_unconditionally_required() {
1407        assert!(is_unconditionally_required("X"));
1408        assert!(is_unconditionally_required("Muss"));
1409        assert!(is_unconditionally_required("Soll"));
1410        assert!(!is_unconditionally_required("Kann"));
1411        assert!(!is_unconditionally_required("[1]"));
1412        assert!(!is_unconditionally_required(""));
1413    }
1414
1415    #[test]
1416    fn test_validation_report_display() {
1417        let errors = vec![
1418            PidValidationError::MissingEntity {
1419                entity: "Marktlokation".to_string(),
1420                ahb_status: "Muss".to_string(),
1421                severity: Severity::Error,
1422            },
1423            PidValidationError::MissingField {
1424                entity: "Prozessdaten".to_string(),
1425                field: "vorgangId".to_string(),
1426                ahb_status: "X".to_string(),
1427                rust_type: None,
1428                valid_values: vec![],
1429                severity: Severity::Error,
1430            },
1431        ];
1432        let report = ValidationReport(errors);
1433        assert!(report.has_errors());
1434        assert_eq!(report.len(), 2);
1435        assert!(!report.is_empty());
1436
1437        let display = report.to_string();
1438        assert!(display.contains("missing entity 'Marktlokation'"));
1439        assert!(display.contains("missing Prozessdaten.vorgangId"));
1440    }
1441
1442    #[test]
1443    fn test_missing_field_with_type_and_values_display() {
1444        let err = PidValidationError::MissingField {
1445            entity: "Marktlokation".to_string(),
1446            field: "haushaltskunde".to_string(),
1447            ahb_status: "Muss".to_string(),
1448            rust_type: Some("Haushaltskunde".to_string()),
1449            valid_values: vec![
1450                ("Z15".to_string(), "Ja".to_string()),
1451                ("Z18".to_string(), "Nein".to_string()),
1452            ],
1453            severity: Severity::Error,
1454        };
1455        let msg = err.to_string();
1456        assert!(msg.contains("type: Haushaltskunde"));
1457        assert!(msg.contains("valid: Z15 (Ja), Z18 (Nein)"));
1458    }
1459
1460    #[test]
1461    fn test_optional_fields_not_flagged() {
1462        let reqs = PidRequirements {
1463            pid: "99999".to_string(),
1464            beschreibung: "Test".to_string(),
1465            entities: vec![EntityRequirement {
1466                entity: "Test".to_string(),
1467                ref_type: Bo4eRefType::Object {
1468                    type_name: "Test".to_string(),
1469
1470                    cardinality: Cardinality::OPTIONAL,
1471                },
1472
1473                ahb_status: "Kann".to_string(),
1474                map_key: None,
1475                scope: EntityScope::Transaction,
1476                variants: vec![],
1477                groups: vec![],
1478                fields: vec![FieldRequirement {
1479                    bo4e_name: "optionalField".to_string(),
1480                    ahb_status: "Kann".to_string(),
1481                    field_type: "data".to_string(),
1482                    format: None,
1483                    enum_name: None,
1484                    valid_codes: vec![],
1485                    child_group: None,
1486                    ref_type: Bo4eRefType::Unknown,
1487                }],
1488                nested: Vec::new(),
1489            }],
1490        };
1491
1492        // Entity missing but optional — no error
1493        let errors = validate_pid_json(&json!({}), &reqs);
1494        assert!(errors.is_empty());
1495
1496        // Entity present, field missing but optional — no error
1497        let errors = validate_pid_json(&json!({ "test": {} }), &reqs);
1498        assert!(errors.is_empty());
1499    }
1500
1501    /// Regression test for issue #48: nested dot-path fields reported as missing
1502    /// even when present (e.g. `produktIdentifikation.funktion`).
1503    #[test]
1504    fn test_nested_dot_path_fields_not_falsely_missing() {
1505        let reqs = PidRequirements {
1506            pid: "55001".to_string(),
1507            beschreibung: "Test nested paths".to_string(),
1508            entities: vec![EntityRequirement {
1509                entity: "ProduktpaketDaten".to_string(),
1510                ref_type: Bo4eRefType::Object {
1511                    type_name: "ProduktpaketDaten".to_string(),
1512
1513                    cardinality: Cardinality {
1514                        min: 1,
1515                        max: Some(99999),
1516                    },
1517                },
1518
1519                ahb_status: "Muss".to_string(),
1520                map_key: None,
1521                scope: EntityScope::Transaction,
1522                variants: vec![],
1523                groups: vec![],
1524                fields: vec![
1525                    FieldRequirement {
1526                        bo4e_name: "produktIdentifikation.funktion".to_string(),
1527                        ahb_status: "X".to_string(),
1528                        field_type: "code".to_string(),
1529                        format: None,
1530                        enum_name: Some("Produktidentifikation".to_string()),
1531                        valid_codes: vec![CodeValue {
1532                            code: "5".to_string(),
1533                            meaning: "Produktidentifikation".to_string(),
1534                            enum_name: None,
1535                            bo4e_value: None,
1536                            ahb_status: None,
1537                        }],
1538                        child_group: None,
1539                        ref_type: Bo4eRefType::Unknown,
1540                    },
1541                    FieldRequirement {
1542                        bo4e_name: "produktMerkmal.code".to_string(),
1543                        ahb_status: "X".to_string(),
1544                        field_type: "code".to_string(),
1545                        format: None,
1546                        enum_name: None,
1547                        valid_codes: vec![],
1548                        child_group: None,
1549                        ref_type: Bo4eRefType::Unknown,
1550                    },
1551                ],
1552                nested: Vec::new(),
1553            }],
1554        };
1555
1556        // Exact JSON from issue #48
1557        let json = json!({
1558            "produktpaketDaten": [{
1559                "produktIdentifikation": { "funktion": "5", "id": "9991000002082", "typ": "Z11" },
1560                "produktMerkmal": { "code": "ZH9" }
1561            }]
1562        });
1563
1564        let errors = validate_pid_json(&json, &reqs);
1565        assert!(
1566            errors.is_empty(),
1567            "Nested dot-path fields should be found (issue #48), got: {errors:?}"
1568        );
1569    }
1570
1571    #[test]
1572    fn test_nested_dot_path_truly_missing() {
1573        let reqs = PidRequirements {
1574            pid: "55001".to_string(),
1575            beschreibung: "Test nested paths missing".to_string(),
1576            entities: vec![EntityRequirement {
1577                entity: "ProduktpaketDaten".to_string(),
1578                ref_type: Bo4eRefType::Object {
1579                    type_name: "ProduktpaketDaten".to_string(),
1580
1581                    cardinality: Cardinality {
1582                        min: 1,
1583                        max: Some(99999),
1584                    },
1585                },
1586
1587                ahb_status: "Muss".to_string(),
1588                map_key: None,
1589                scope: EntityScope::Transaction,
1590                variants: vec![],
1591                groups: vec![],
1592                fields: vec![FieldRequirement {
1593                    bo4e_name: "produktIdentifikation.funktion".to_string(),
1594                    ahb_status: "X".to_string(),
1595                    field_type: "data".to_string(),
1596                    format: None,
1597                    enum_name: None,
1598                    valid_codes: vec![],
1599                    child_group: None,
1600                    ref_type: Bo4eRefType::Unknown,
1601                }],
1602                nested: Vec::new(),
1603            }],
1604        };
1605
1606        // Parent exists but nested field is missing
1607        let json = json!({
1608            "produktpaketDaten": [{
1609                "produktIdentifikation": { "id": "123" }
1610            }]
1611        });
1612
1613        let errors = validate_pid_json(&json, &reqs);
1614        assert_eq!(errors.len(), 1, "Should report missing nested field");
1615        match &errors[0] {
1616            PidValidationError::MissingField { field, .. } => {
1617                assert_eq!(field, "produktIdentifikation.funktion");
1618            }
1619            other => panic!("Expected MissingField, got: {other:?}"),
1620        }
1621    }
1622
1623    fn field(name: &str, status: &str, codes: &[(&str, &str)]) -> FieldRequirement {
1624        FieldRequirement {
1625            bo4e_name: name.to_string(),
1626            ahb_status: status.to_string(),
1627            field_type: if codes.is_empty() { "data" } else { "code" }.to_string(),
1628            format: None,
1629            enum_name: None,
1630            valid_codes: codes
1631                .iter()
1632                .map(|(code, mapped)| CodeValue {
1633                    code: code.to_string(),
1634                    meaning: String::new(),
1635                    enum_name: None,
1636                    bo4e_value: Some(mapped.to_string()),
1637                    ahb_status: None,
1638                })
1639                .collect(),
1640            child_group: None,
1641            ref_type: Bo4eRefType::Unknown,
1642        }
1643    }
1644
1645    /// Geschaeftspartner fed by two NAD variants: Z03 (address, no name) and
1646    /// Z07 (name, no address), shaped like PID 55042 (issue #104).
1647    fn multi_variant_requirements() -> PidRequirements {
1648        let z03 = ("Z03", "messlokationsadresse");
1649        let z07 = ("Z07", "kundeMsb");
1650        PidRequirements {
1651            pid: "55042".to_string(),
1652            beschreibung: String::new(),
1653            entities: vec![EntityRequirement {
1654                entity: "Geschaeftspartner".to_string(),
1655                ref_type: Bo4eRefType::Object {
1656                    type_name: "Geschaeftspartner".to_string(),
1657                    cardinality: Cardinality {
1658                        min: 1,
1659                        max: Some(99),
1660                    },
1661                },
1662                ahb_status: "Muss".to_string(),
1663                // Entity-level union, as built from the merged schema groups.
1664                fields: vec![
1665                    field("adresse.ort", "X", &[]),
1666                    field("name1", "X", &[]),
1667                    field("partnerrolle", "X", &[z03, z07]),
1668                ],
1669                map_key: None,
1670                scope: EntityScope::Transaction,
1671                variants: vec![
1672                    EntityVariantRequirement {
1673                        discriminator_field: "partnerrolle".to_string(),
1674                        code: "Z03".to_string(),
1675                        bo4e_value: Some("messlokationsadresse".to_string()),
1676                        source_paths: vec!["sg4.sg12_z03".to_string()],
1677                        fields: vec![
1678                            field("adresse.ort", "X", &[]),
1679                            field("partnerrolle", "X", &[z03]),
1680                        ],
1681                    },
1682                    EntityVariantRequirement {
1683                        discriminator_field: "partnerrolle".to_string(),
1684                        code: "Z07".to_string(),
1685                        bo4e_value: Some("kundeMsb".to_string()),
1686                        source_paths: vec!["sg4.sg12_z07".to_string()],
1687                        fields: vec![field("name1", "X", &[]), field("partnerrolle", "X", &[z07])],
1688                    },
1689                ],
1690                groups: vec![],
1691                nested: Vec::new(),
1692            }],
1693        }
1694    }
1695
1696    /// `Marktlokation` fed by LOC+Z16 and LOC+Z22, as in FV2604 UTILMD_Strom.
1697    fn multi_group_requirements(z22_status: &str) -> PidRequirements {
1698        let group = |path: &str, status: &str, fields: &[&str]| EntityGroupRequirement {
1699            source_path: path.to_string(),
1700            ahb_status: status.to_string(),
1701            fields: fields.iter().map(|f| f.to_string()).collect(),
1702        };
1703        PidRequirements {
1704            pid: "55043".to_string(),
1705            beschreibung: String::new(),
1706            entities: vec![EntityRequirement {
1707                entity: "Marktlokation".to_string(),
1708                ref_type: Bo4eRefType::Object {
1709                    type_name: "Marktlokation".to_string(),
1710                    cardinality: Cardinality::REQUIRED,
1711                },
1712                ahb_status: "Muss".to_string(),
1713                fields: vec![
1714                    field("marktlokationsId", "X", &[]),
1715                    field("ruhendeMarktlokationsId", "X", &[]),
1716                    field("ruhendeMarktlokationZeitraumId", "Kann", &[]),
1717                ],
1718                map_key: None,
1719                scope: EntityScope::Transaction,
1720                variants: vec![],
1721                groups: vec![
1722                    group("sg4.sg5_z16", "Muss", &["marktlokationsId"]),
1723                    group(
1724                        "sg4.sg5_z22",
1725                        z22_status,
1726                        &["ruhendeMarktlokationsId", "ruhendeMarktlokationZeitraumId"],
1727                    ),
1728                ],
1729                nested: Vec::new(),
1730            }],
1731        }
1732    }
1733
1734    fn missing_fields(errors: &[PidValidationError]) -> Vec<&str> {
1735        errors
1736            .iter()
1737            .filter_map(|e| match e {
1738                PidValidationError::MissingField { field, .. } => Some(field.as_str()),
1739                _ => None,
1740            })
1741            .collect()
1742    }
1743
1744    #[test]
1745    fn an_absent_optional_groups_fields_are_not_demanded() {
1746        let reqs = multi_group_requirements("Soll [2003]");
1747        let errors = validate_pid_json(&json!({ "marktlokation": {} }), &reqs);
1748        // The Z16 group is required, so its fields are; Z22's are not.
1749        assert_eq!(missing_fields(&errors), vec!["marktlokationsId"]);
1750    }
1751
1752    #[test]
1753    fn a_filled_groups_fields_are_demanded() {
1754        let reqs = multi_group_requirements("Soll [2003]");
1755        let json = json!({ "marktlokation": {
1756            "marktlokationsId": "51238696781",
1757            "ruhendeMarktlokationZeitraumId": "1"
1758        }});
1759        let errors = validate_pid_json(&json, &reqs);
1760        assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
1761    }
1762
1763    #[test]
1764    fn an_absent_required_groups_fields_are_demanded() {
1765        let reqs = multi_group_requirements("Muss");
1766        let json = json!({ "marktlokation": { "marktlokationsId": "51238696781" } });
1767        let errors = validate_pid_json(&json, &reqs);
1768        assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
1769    }
1770
1771    #[test]
1772    fn multi_variant_entity_uses_the_elements_own_variant() {
1773        let reqs = multi_variant_requirements();
1774        // Every spelling of the qualifier: raw code / enum_map name, string / object.
1775        let json = json!({
1776            "geschaeftspartner": [
1777                { "partnerrolle": "Z03", "adresse": { "ort": "Berlin" } },
1778                { "partnerrolle": "kundeMsb", "name1": "Muster" },
1779                { "partnerrolle": { "code": "messlokationsadresse", "meaning": "x" },
1780                  "adresse": { "ort": "Köln" } },
1781                { "partnerrolle": { "code": "Z07" }, "name1": "Beispiel" },
1782            ]
1783        });
1784        let errors = validate_pid_json(&json, &reqs);
1785        assert!(errors.is_empty(), "{}", ValidationReport(errors));
1786    }
1787
1788    #[test]
1789    fn multi_variant_entity_reports_variant_required_fields() {
1790        let reqs = multi_variant_requirements();
1791        let json = json!({ "geschaeftspartner": [{ "partnerrolle": "kundeMsb" }] });
1792        let errors = validate_pid_json(&json, &reqs);
1793        assert_eq!(errors.len(), 1, "{}", ValidationReport(errors));
1794        assert!(matches!(
1795            &errors[0],
1796            PidValidationError::MissingField { field, .. } if field == "name1"
1797        ));
1798    }
1799
1800    #[test]
1801    fn multi_variant_entity_unknown_qualifier_is_invalid_code_only() {
1802        let reqs = multi_variant_requirements();
1803        for bad in [json!("Z99"), json!("bogus"), json!({ "code": "Z99" })] {
1804            let json = json!({ "geschaeftspartner": [{ "partnerrolle": bad }] });
1805            let errors = validate_pid_json(&json, &reqs);
1806            // No variant matches: variant fields become optional, codes are unioned.
1807            assert_eq!(errors.len(), 1, "{bad}: {}", ValidationReport(errors));
1808            match &errors[0] {
1809                PidValidationError::InvalidCode {
1810                    field,
1811                    valid_values,
1812                    ..
1813                } => {
1814                    assert_eq!(field, "partnerrolle");
1815                    let codes: Vec<&str> = valid_values.iter().map(|(c, _)| c.as_str()).collect();
1816                    assert_eq!(codes, ["Z03", "Z07"]);
1817                }
1818                other => panic!("expected InvalidCode, got {other:?}"),
1819            }
1820        }
1821    }
1822
1823    #[test]
1824    fn code_objects_and_enum_mapped_names_are_code_checked() {
1825        let f = field("partnerrolle", "X", &[("Z07", "kundeMsb")]);
1826        assert_eq!(invalid_code_value(&json!("Z07"), &f), None);
1827        assert_eq!(invalid_code_value(&json!("kundeMsb"), &f), None);
1828        assert_eq!(invalid_code_value(&json!({ "code": "kundeMsb" }), &f), None);
1829        assert_eq!(invalid_code_value(&json!({ "code": "Z07" }), &f), None);
1830        assert_eq!(
1831            invalid_code_value(&json!({ "code": "Z99", "meaning": null }), &f),
1832            Some("Z99".to_string())
1833        );
1834        assert_eq!(
1835            invalid_code_value(&json!("kundeLf"), &f),
1836            Some("kundeLf".to_string())
1837        );
1838        // Non-code values (numbers, objects without code) are not code-checked.
1839        assert_eq!(invalid_code_value(&json!(7), &f), None);
1840        assert_eq!(invalid_code_value(&json!({ "meaning": "x" }), &f), None);
1841    }
1842}