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                            ref_type: Bo4eRefType::Unknown,
1010                        },
1011                        FieldRequirement {
1012                            bo4e_name: "transaktionsgrund".to_string(),
1013                            ahb_status: "X".to_string(),
1014                            field_type: "code".to_string(),
1015                            format: None,
1016                            enum_name: Some("Transaktionsgrund".to_string()),
1017                            valid_codes: vec![
1018                                CodeValue {
1019                                    code: "E01".to_string(),
1020                                    meaning: "Ein-/Auszug (Einzug)".to_string(),
1021                                    enum_name: None,
1022                                    bo4e_value: None,
1023                                    ahb_status: None,
1024                                },
1025                                CodeValue {
1026                                    code: "E03".to_string(),
1027                                    meaning: "Wechsel".to_string(),
1028                                    enum_name: None,
1029                                    bo4e_value: None,
1030                                    ahb_status: None,
1031                                },
1032                            ],
1033                            ref_type: Bo4eRefType::Unknown,
1034                        },
1035                    ],
1036                    nested: Vec::new(),
1037                },
1038                EntityRequirement {
1039                    entity: "Marktlokation".to_string(),
1040                    ref_type: Bo4eRefType::Object {
1041                        type_name: "Marktlokation".to_string(),
1042
1043                        cardinality: Cardinality::REQUIRED,
1044                    },
1045
1046                    ahb_status: "Muss".to_string(),
1047                    map_key: None,
1048                    scope: EntityScope::Transaction,
1049                    variants: vec![],
1050                    groups: vec![],
1051                    fields: vec![
1052                        FieldRequirement {
1053                            bo4e_name: "marktlokationsId".to_string(),
1054                            ahb_status: "X".to_string(),
1055                            field_type: "data".to_string(),
1056                            format: None,
1057                            enum_name: None,
1058                            valid_codes: vec![],
1059                            ref_type: Bo4eRefType::Unknown,
1060                        },
1061                        FieldRequirement {
1062                            bo4e_name: "haushaltskunde".to_string(),
1063                            ahb_status: "X".to_string(),
1064                            field_type: "code".to_string(),
1065                            format: None,
1066                            enum_name: Some("Haushaltskunde".to_string()),
1067                            valid_codes: vec![
1068                                CodeValue {
1069                                    code: "Z15".to_string(),
1070                                    meaning: "Ja".to_string(),
1071                                    enum_name: None,
1072                                    bo4e_value: None,
1073                                    ahb_status: None,
1074                                },
1075                                CodeValue {
1076                                    code: "Z18".to_string(),
1077                                    meaning: "Nein".to_string(),
1078                                    enum_name: None,
1079                                    bo4e_value: None,
1080                                    ahb_status: None,
1081                                },
1082                            ],
1083                            ref_type: Bo4eRefType::Unknown,
1084                        },
1085                    ],
1086                    nested: Vec::new(),
1087                },
1088                EntityRequirement {
1089                    entity: "Geschaeftspartner".to_string(),
1090                    ref_type: Bo4eRefType::Object {
1091                        type_name: "Geschaeftspartner".to_string(),
1092
1093                        cardinality: Cardinality {
1094                            min: 1,
1095                            max: Some(7),
1096                        },
1097                    },
1098
1099                    ahb_status: "Muss".to_string(),
1100                    map_key: None,
1101                    scope: EntityScope::Transaction,
1102                    variants: vec![],
1103                    groups: vec![],
1104                    fields: vec![FieldRequirement {
1105                        bo4e_name: "identifikation".to_string(),
1106                        ahb_status: "X".to_string(),
1107                        field_type: "data".to_string(),
1108                        format: None,
1109                        enum_name: None,
1110                        valid_codes: vec![],
1111                        ref_type: Bo4eRefType::Unknown,
1112                    }],
1113                    nested: Vec::new(),
1114                },
1115            ],
1116        }
1117    }
1118
1119    #[test]
1120    fn test_validate_complete_json() {
1121        let reqs = sample_requirements();
1122        let json = json!({
1123            "prozessdaten": {
1124                "vorgangId": "ABC123",
1125                "transaktionsgrund": "E01"
1126            },
1127            "marktlokation": {
1128                "marktlokationsId": "51234567890",
1129                "haushaltskunde": "Z15"
1130            },
1131            "geschaeftspartner": [
1132                { "identifikation": "9900000000003" }
1133            ]
1134        });
1135
1136        let errors = validate_pid_json(&json, &reqs);
1137        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
1138    }
1139
1140    #[test]
1141    fn test_validate_missing_entity() {
1142        let reqs = sample_requirements();
1143        let json = json!({
1144            "prozessdaten": {
1145                "vorgangId": "ABC123",
1146                "transaktionsgrund": "E01"
1147            },
1148            "geschaeftspartner": [
1149                { "identifikation": "9900000000003" }
1150            ]
1151        });
1152        // Marktlokation is missing
1153
1154        let errors = validate_pid_json(&json, &reqs);
1155        assert_eq!(errors.len(), 1);
1156        match &errors[0] {
1157            PidValidationError::MissingEntity {
1158                entity,
1159                ahb_status,
1160                severity,
1161            } => {
1162                assert_eq!(entity, "Marktlokation");
1163                assert_eq!(ahb_status, "Muss");
1164                assert_eq!(severity, &Severity::Error);
1165            }
1166            other => panic!("Expected MissingEntity, got: {other:?}"),
1167        }
1168
1169        // Display check
1170        let msg = errors[0].to_string();
1171        assert!(msg.contains("ERROR"));
1172        assert!(msg.contains("Marktlokation"));
1173        assert!(msg.contains("Muss"));
1174    }
1175
1176    #[test]
1177    fn test_validate_missing_field() {
1178        let reqs = sample_requirements();
1179        let json = json!({
1180            "prozessdaten": {
1181                "transaktionsgrund": "E01"
1182                // vorgangId is missing
1183            },
1184            "marktlokation": {
1185                "marktlokationsId": "51234567890",
1186                "haushaltskunde": "Z15"
1187            },
1188            "geschaeftspartner": [
1189                { "identifikation": "9900000000003" }
1190            ]
1191        });
1192
1193        let errors = validate_pid_json(&json, &reqs);
1194        assert_eq!(errors.len(), 1);
1195        match &errors[0] {
1196            PidValidationError::MissingField {
1197                entity,
1198                field,
1199                ahb_status,
1200                severity,
1201                ..
1202            } => {
1203                assert_eq!(entity, "Prozessdaten");
1204                assert_eq!(field, "vorgangId");
1205                assert_eq!(ahb_status, "X");
1206                assert_eq!(severity, &Severity::Error);
1207            }
1208            other => panic!("Expected MissingField, got: {other:?}"),
1209        }
1210
1211        let msg = errors[0].to_string();
1212        assert!(msg.contains("ERROR"));
1213        assert!(msg.contains("Prozessdaten.vorgangId"));
1214    }
1215
1216    #[test]
1217    fn test_validate_invalid_code() {
1218        let reqs = sample_requirements();
1219        let json = json!({
1220            "prozessdaten": {
1221                "vorgangId": "ABC123",
1222                "transaktionsgrund": "E01"
1223            },
1224            "marktlokation": {
1225                "marktlokationsId": "51234567890",
1226                "haushaltskunde": "Z99"  // Invalid code
1227            },
1228            "geschaeftspartner": [
1229                { "identifikation": "9900000000003" }
1230            ]
1231        });
1232
1233        let errors = validate_pid_json(&json, &reqs);
1234        assert_eq!(errors.len(), 1);
1235        match &errors[0] {
1236            PidValidationError::InvalidCode {
1237                entity,
1238                field,
1239                value,
1240                valid_values,
1241            } => {
1242                assert_eq!(entity, "Marktlokation");
1243                assert_eq!(field, "haushaltskunde");
1244                assert_eq!(value, "Z99");
1245                assert_eq!(valid_values.len(), 2);
1246                assert!(valid_values.iter().any(|(c, _)| c == "Z15"));
1247                assert!(valid_values.iter().any(|(c, _)| c == "Z18"));
1248            }
1249            other => panic!("Expected InvalidCode, got: {other:?}"),
1250        }
1251
1252        let msg = errors[0].to_string();
1253        assert!(msg.contains("INVALID"));
1254        assert!(msg.contains("Z99"));
1255        assert!(msg.contains("Z15"));
1256    }
1257
1258    #[test]
1259    fn test_validate_array_entity() {
1260        let reqs = sample_requirements();
1261        let json = json!({
1262            "prozessdaten": {
1263                "vorgangId": "ABC123",
1264                "transaktionsgrund": "E01"
1265            },
1266            "marktlokation": {
1267                "marktlokationsId": "51234567890",
1268                "haushaltskunde": "Z15"
1269            },
1270            "geschaeftspartner": [
1271                { "identifikation": "9900000000003" },
1272                { }  // Missing identifikation in second element
1273            ]
1274        });
1275
1276        let errors = validate_pid_json(&json, &reqs);
1277        assert_eq!(errors.len(), 1);
1278        match &errors[0] {
1279            PidValidationError::MissingField { entity, field, .. } => {
1280                assert_eq!(entity, "Geschaeftspartner");
1281                assert_eq!(field, "identifikation");
1282            }
1283            other => panic!("Expected MissingField, got: {other:?}"),
1284        }
1285    }
1286
1287    #[test]
1288    fn test_to_camel_case() {
1289        assert_eq!(to_camel_case("Prozessdaten"), "prozessdaten");
1290        assert_eq!(
1291            to_camel_case("RuhendeMarktlokation"),
1292            "ruhendeMarktlokation"
1293        );
1294        assert_eq!(to_camel_case("Marktlokation"), "marktlokation");
1295        assert_eq!(to_camel_case(""), "");
1296    }
1297
1298    #[test]
1299    fn test_snake_to_camel_case() {
1300        assert_eq!(snake_to_camel_case("code_codepflege"), "codeCodepflege");
1301        assert_eq!(snake_to_camel_case("vorgang_id"), "vorgangId");
1302        assert_eq!(snake_to_camel_case("marktlokation"), "marktlokation");
1303        assert_eq!(snake_to_camel_case(""), "");
1304        assert_eq!(snake_to_camel_case("a_b_c"), "aBC");
1305    }
1306
1307    /// A field stored as snake_case in requirements (e.g. from TOML) must be found
1308    /// in JSON that was produced by a typed struct using `#[serde(rename_all = "camelCase")]`.
1309    #[test]
1310    fn test_camel_case_fallback_for_snake_case_bo4e_name() {
1311        let reqs = PidRequirements {
1312            pid: "55077".to_string(),
1313            beschreibung: "Test camelCase fallback".to_string(),
1314            entities: vec![EntityRequirement {
1315                entity: "Zuordnung".to_string(),
1316                ref_type: Bo4eRefType::Object {
1317                    type_name: "Zuordnung".to_string(),
1318
1319                    cardinality: Cardinality::REQUIRED,
1320                },
1321
1322                ahb_status: "Muss".to_string(),
1323                map_key: None,
1324                scope: EntityScope::Transaction,
1325                variants: vec![],
1326                groups: vec![],
1327                fields: vec![
1328                    FieldRequirement {
1329                        // snake_case as stored in TOML requirements
1330                        bo4e_name: "code_codepflege".to_string(),
1331                        ahb_status: "X".to_string(),
1332                        field_type: "data".to_string(),
1333                        format: None,
1334                        enum_name: None,
1335                        valid_codes: vec![],
1336                        ref_type: Bo4eRefType::Unknown,
1337                    },
1338                    FieldRequirement {
1339                        bo4e_name: "codeliste".to_string(),
1340                        ahb_status: "X".to_string(),
1341                        field_type: "data".to_string(),
1342                        format: None,
1343                        enum_name: None,
1344                        valid_codes: vec![],
1345                        ref_type: Bo4eRefType::Unknown,
1346                    },
1347                ],
1348                nested: Vec::new(),
1349            }],
1350        };
1351
1352        // JSON produced by a typed struct with #[serde(rename_all = "camelCase")]:
1353        // code_codepflege → codeCodepflege
1354        let json_camel = json!({
1355            "zuordnung": {
1356                "codeCodepflege": "DE_BDEW",
1357                "codeliste": "6"
1358            }
1359        });
1360
1361        let errors = validate_pid_json(&json_camel, &reqs);
1362        assert!(
1363            errors.is_empty(),
1364            "Expected no errors when field is present under camelCase key, got: {errors:?}"
1365        );
1366
1367        // Also verify that snake_case key in JSON still works (backward compat).
1368        let json_snake = json!({
1369            "zuordnung": {
1370                "code_codepflege": "DE_BDEW",
1371                "codeliste": "6"
1372            }
1373        });
1374
1375        let errors = validate_pid_json(&json_snake, &reqs);
1376        assert!(
1377            errors.is_empty(),
1378            "Expected no errors when field is present under snake_case key, got: {errors:?}"
1379        );
1380
1381        // When the field is truly absent, a MissingField error must still be raised.
1382        let json_missing = json!({
1383            "zuordnung": {
1384                "codeliste": "6"
1385            }
1386        });
1387
1388        let errors = validate_pid_json(&json_missing, &reqs);
1389        assert_eq!(errors.len(), 1);
1390        match &errors[0] {
1391            PidValidationError::MissingField { field, .. } => {
1392                assert_eq!(field, "code_codepflege");
1393            }
1394            other => panic!("Expected MissingField, got: {other:?}"),
1395        }
1396    }
1397
1398    #[test]
1399    fn test_is_unconditionally_required() {
1400        assert!(is_unconditionally_required("X"));
1401        assert!(is_unconditionally_required("Muss"));
1402        assert!(is_unconditionally_required("Soll"));
1403        assert!(!is_unconditionally_required("Kann"));
1404        assert!(!is_unconditionally_required("[1]"));
1405        assert!(!is_unconditionally_required(""));
1406    }
1407
1408    #[test]
1409    fn test_validation_report_display() {
1410        let errors = vec![
1411            PidValidationError::MissingEntity {
1412                entity: "Marktlokation".to_string(),
1413                ahb_status: "Muss".to_string(),
1414                severity: Severity::Error,
1415            },
1416            PidValidationError::MissingField {
1417                entity: "Prozessdaten".to_string(),
1418                field: "vorgangId".to_string(),
1419                ahb_status: "X".to_string(),
1420                rust_type: None,
1421                valid_values: vec![],
1422                severity: Severity::Error,
1423            },
1424        ];
1425        let report = ValidationReport(errors);
1426        assert!(report.has_errors());
1427        assert_eq!(report.len(), 2);
1428        assert!(!report.is_empty());
1429
1430        let display = report.to_string();
1431        assert!(display.contains("missing entity 'Marktlokation'"));
1432        assert!(display.contains("missing Prozessdaten.vorgangId"));
1433    }
1434
1435    #[test]
1436    fn test_missing_field_with_type_and_values_display() {
1437        let err = PidValidationError::MissingField {
1438            entity: "Marktlokation".to_string(),
1439            field: "haushaltskunde".to_string(),
1440            ahb_status: "Muss".to_string(),
1441            rust_type: Some("Haushaltskunde".to_string()),
1442            valid_values: vec![
1443                ("Z15".to_string(), "Ja".to_string()),
1444                ("Z18".to_string(), "Nein".to_string()),
1445            ],
1446            severity: Severity::Error,
1447        };
1448        let msg = err.to_string();
1449        assert!(msg.contains("type: Haushaltskunde"));
1450        assert!(msg.contains("valid: Z15 (Ja), Z18 (Nein)"));
1451    }
1452
1453    #[test]
1454    fn test_optional_fields_not_flagged() {
1455        let reqs = PidRequirements {
1456            pid: "99999".to_string(),
1457            beschreibung: "Test".to_string(),
1458            entities: vec![EntityRequirement {
1459                entity: "Test".to_string(),
1460                ref_type: Bo4eRefType::Object {
1461                    type_name: "Test".to_string(),
1462
1463                    cardinality: Cardinality::OPTIONAL,
1464                },
1465
1466                ahb_status: "Kann".to_string(),
1467                map_key: None,
1468                scope: EntityScope::Transaction,
1469                variants: vec![],
1470                groups: vec![],
1471                fields: vec![FieldRequirement {
1472                    bo4e_name: "optionalField".to_string(),
1473                    ahb_status: "Kann".to_string(),
1474                    field_type: "data".to_string(),
1475                    format: None,
1476                    enum_name: None,
1477                    valid_codes: vec![],
1478                    ref_type: Bo4eRefType::Unknown,
1479                }],
1480                nested: Vec::new(),
1481            }],
1482        };
1483
1484        // Entity missing but optional — no error
1485        let errors = validate_pid_json(&json!({}), &reqs);
1486        assert!(errors.is_empty());
1487
1488        // Entity present, field missing but optional — no error
1489        let errors = validate_pid_json(&json!({ "test": {} }), &reqs);
1490        assert!(errors.is_empty());
1491    }
1492
1493    /// Regression test for issue #48: nested dot-path fields reported as missing
1494    /// even when present (e.g. `produktIdentifikation.funktion`).
1495    #[test]
1496    fn test_nested_dot_path_fields_not_falsely_missing() {
1497        let reqs = PidRequirements {
1498            pid: "55001".to_string(),
1499            beschreibung: "Test nested paths".to_string(),
1500            entities: vec![EntityRequirement {
1501                entity: "ProduktpaketDaten".to_string(),
1502                ref_type: Bo4eRefType::Object {
1503                    type_name: "ProduktpaketDaten".to_string(),
1504
1505                    cardinality: Cardinality {
1506                        min: 1,
1507                        max: Some(99999),
1508                    },
1509                },
1510
1511                ahb_status: "Muss".to_string(),
1512                map_key: None,
1513                scope: EntityScope::Transaction,
1514                variants: vec![],
1515                groups: vec![],
1516                fields: vec![
1517                    FieldRequirement {
1518                        bo4e_name: "produktIdentifikation.funktion".to_string(),
1519                        ahb_status: "X".to_string(),
1520                        field_type: "code".to_string(),
1521                        format: None,
1522                        enum_name: Some("Produktidentifikation".to_string()),
1523                        valid_codes: vec![CodeValue {
1524                            code: "5".to_string(),
1525                            meaning: "Produktidentifikation".to_string(),
1526                            enum_name: None,
1527                            bo4e_value: None,
1528                            ahb_status: None,
1529                        }],
1530                        ref_type: Bo4eRefType::Unknown,
1531                    },
1532                    FieldRequirement {
1533                        bo4e_name: "produktMerkmal.code".to_string(),
1534                        ahb_status: "X".to_string(),
1535                        field_type: "code".to_string(),
1536                        format: None,
1537                        enum_name: None,
1538                        valid_codes: vec![],
1539                        ref_type: Bo4eRefType::Unknown,
1540                    },
1541                ],
1542                nested: Vec::new(),
1543            }],
1544        };
1545
1546        // Exact JSON from issue #48
1547        let json = json!({
1548            "produktpaketDaten": [{
1549                "produktIdentifikation": { "funktion": "5", "id": "9991000002082", "typ": "Z11" },
1550                "produktMerkmal": { "code": "ZH9" }
1551            }]
1552        });
1553
1554        let errors = validate_pid_json(&json, &reqs);
1555        assert!(
1556            errors.is_empty(),
1557            "Nested dot-path fields should be found (issue #48), got: {errors:?}"
1558        );
1559    }
1560
1561    #[test]
1562    fn test_nested_dot_path_truly_missing() {
1563        let reqs = PidRequirements {
1564            pid: "55001".to_string(),
1565            beschreibung: "Test nested paths missing".to_string(),
1566            entities: vec![EntityRequirement {
1567                entity: "ProduktpaketDaten".to_string(),
1568                ref_type: Bo4eRefType::Object {
1569                    type_name: "ProduktpaketDaten".to_string(),
1570
1571                    cardinality: Cardinality {
1572                        min: 1,
1573                        max: Some(99999),
1574                    },
1575                },
1576
1577                ahb_status: "Muss".to_string(),
1578                map_key: None,
1579                scope: EntityScope::Transaction,
1580                variants: vec![],
1581                groups: vec![],
1582                fields: vec![FieldRequirement {
1583                    bo4e_name: "produktIdentifikation.funktion".to_string(),
1584                    ahb_status: "X".to_string(),
1585                    field_type: "data".to_string(),
1586                    format: None,
1587                    enum_name: None,
1588                    valid_codes: vec![],
1589                    ref_type: Bo4eRefType::Unknown,
1590                }],
1591                nested: Vec::new(),
1592            }],
1593        };
1594
1595        // Parent exists but nested field is missing
1596        let json = json!({
1597            "produktpaketDaten": [{
1598                "produktIdentifikation": { "id": "123" }
1599            }]
1600        });
1601
1602        let errors = validate_pid_json(&json, &reqs);
1603        assert_eq!(errors.len(), 1, "Should report missing nested field");
1604        match &errors[0] {
1605            PidValidationError::MissingField { field, .. } => {
1606                assert_eq!(field, "produktIdentifikation.funktion");
1607            }
1608            other => panic!("Expected MissingField, got: {other:?}"),
1609        }
1610    }
1611
1612    fn field(name: &str, status: &str, codes: &[(&str, &str)]) -> FieldRequirement {
1613        FieldRequirement {
1614            bo4e_name: name.to_string(),
1615            ahb_status: status.to_string(),
1616            field_type: if codes.is_empty() { "data" } else { "code" }.to_string(),
1617            format: None,
1618            enum_name: None,
1619            valid_codes: codes
1620                .iter()
1621                .map(|(code, mapped)| CodeValue {
1622                    code: code.to_string(),
1623                    meaning: String::new(),
1624                    enum_name: None,
1625                    bo4e_value: Some(mapped.to_string()),
1626                    ahb_status: None,
1627                })
1628                .collect(),
1629            ref_type: Bo4eRefType::Unknown,
1630        }
1631    }
1632
1633    /// Geschaeftspartner fed by two NAD variants: Z03 (address, no name) and
1634    /// Z07 (name, no address), shaped like PID 55042 (issue #104).
1635    fn multi_variant_requirements() -> PidRequirements {
1636        let z03 = ("Z03", "messlokationsadresse");
1637        let z07 = ("Z07", "kundeMsb");
1638        PidRequirements {
1639            pid: "55042".to_string(),
1640            beschreibung: String::new(),
1641            entities: vec![EntityRequirement {
1642                entity: "Geschaeftspartner".to_string(),
1643                ref_type: Bo4eRefType::Object {
1644                    type_name: "Geschaeftspartner".to_string(),
1645                    cardinality: Cardinality {
1646                        min: 1,
1647                        max: Some(99),
1648                    },
1649                },
1650                ahb_status: "Muss".to_string(),
1651                // Entity-level union, as built from the merged schema groups.
1652                fields: vec![
1653                    field("adresse.ort", "X", &[]),
1654                    field("name1", "X", &[]),
1655                    field("partnerrolle", "X", &[z03, z07]),
1656                ],
1657                map_key: None,
1658                scope: EntityScope::Transaction,
1659                variants: vec![
1660                    EntityVariantRequirement {
1661                        discriminator_field: "partnerrolle".to_string(),
1662                        code: "Z03".to_string(),
1663                        bo4e_value: Some("messlokationsadresse".to_string()),
1664                        source_paths: vec!["sg4.sg12_z03".to_string()],
1665                        fields: vec![
1666                            field("adresse.ort", "X", &[]),
1667                            field("partnerrolle", "X", &[z03]),
1668                        ],
1669                    },
1670                    EntityVariantRequirement {
1671                        discriminator_field: "partnerrolle".to_string(),
1672                        code: "Z07".to_string(),
1673                        bo4e_value: Some("kundeMsb".to_string()),
1674                        source_paths: vec!["sg4.sg12_z07".to_string()],
1675                        fields: vec![field("name1", "X", &[]), field("partnerrolle", "X", &[z07])],
1676                    },
1677                ],
1678                groups: vec![],
1679                nested: Vec::new(),
1680            }],
1681        }
1682    }
1683
1684    /// `Marktlokation` fed by LOC+Z16 and LOC+Z22, as in FV2604 UTILMD_Strom.
1685    fn multi_group_requirements(z22_status: &str) -> PidRequirements {
1686        let group = |path: &str, status: &str, fields: &[&str]| EntityGroupRequirement {
1687            source_path: path.to_string(),
1688            ahb_status: status.to_string(),
1689            fields: fields.iter().map(|f| f.to_string()).collect(),
1690        };
1691        PidRequirements {
1692            pid: "55043".to_string(),
1693            beschreibung: String::new(),
1694            entities: vec![EntityRequirement {
1695                entity: "Marktlokation".to_string(),
1696                ref_type: Bo4eRefType::Object {
1697                    type_name: "Marktlokation".to_string(),
1698                    cardinality: Cardinality::REQUIRED,
1699                },
1700                ahb_status: "Muss".to_string(),
1701                fields: vec![
1702                    field("marktlokationsId", "X", &[]),
1703                    field("ruhendeMarktlokationsId", "X", &[]),
1704                    field("ruhendeMarktlokationZeitraumId", "Kann", &[]),
1705                ],
1706                map_key: None,
1707                scope: EntityScope::Transaction,
1708                variants: vec![],
1709                groups: vec![
1710                    group("sg4.sg5_z16", "Muss", &["marktlokationsId"]),
1711                    group(
1712                        "sg4.sg5_z22",
1713                        z22_status,
1714                        &["ruhendeMarktlokationsId", "ruhendeMarktlokationZeitraumId"],
1715                    ),
1716                ],
1717                nested: Vec::new(),
1718            }],
1719        }
1720    }
1721
1722    fn missing_fields(errors: &[PidValidationError]) -> Vec<&str> {
1723        errors
1724            .iter()
1725            .filter_map(|e| match e {
1726                PidValidationError::MissingField { field, .. } => Some(field.as_str()),
1727                _ => None,
1728            })
1729            .collect()
1730    }
1731
1732    #[test]
1733    fn an_absent_optional_groups_fields_are_not_demanded() {
1734        let reqs = multi_group_requirements("Soll [2003]");
1735        let errors = validate_pid_json(&json!({ "marktlokation": {} }), &reqs);
1736        // The Z16 group is required, so its fields are; Z22's are not.
1737        assert_eq!(missing_fields(&errors), vec!["marktlokationsId"]);
1738    }
1739
1740    #[test]
1741    fn a_filled_groups_fields_are_demanded() {
1742        let reqs = multi_group_requirements("Soll [2003]");
1743        let json = json!({ "marktlokation": {
1744            "marktlokationsId": "51238696781",
1745            "ruhendeMarktlokationZeitraumId": "1"
1746        }});
1747        let errors = validate_pid_json(&json, &reqs);
1748        assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
1749    }
1750
1751    #[test]
1752    fn an_absent_required_groups_fields_are_demanded() {
1753        let reqs = multi_group_requirements("Muss");
1754        let json = json!({ "marktlokation": { "marktlokationsId": "51238696781" } });
1755        let errors = validate_pid_json(&json, &reqs);
1756        assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
1757    }
1758
1759    #[test]
1760    fn multi_variant_entity_uses_the_elements_own_variant() {
1761        let reqs = multi_variant_requirements();
1762        // Every spelling of the qualifier: raw code / enum_map name, string / object.
1763        let json = json!({
1764            "geschaeftspartner": [
1765                { "partnerrolle": "Z03", "adresse": { "ort": "Berlin" } },
1766                { "partnerrolle": "kundeMsb", "name1": "Muster" },
1767                { "partnerrolle": { "code": "messlokationsadresse", "meaning": "x" },
1768                  "adresse": { "ort": "Köln" } },
1769                { "partnerrolle": { "code": "Z07" }, "name1": "Beispiel" },
1770            ]
1771        });
1772        let errors = validate_pid_json(&json, &reqs);
1773        assert!(errors.is_empty(), "{}", ValidationReport(errors));
1774    }
1775
1776    #[test]
1777    fn multi_variant_entity_reports_variant_required_fields() {
1778        let reqs = multi_variant_requirements();
1779        let json = json!({ "geschaeftspartner": [{ "partnerrolle": "kundeMsb" }] });
1780        let errors = validate_pid_json(&json, &reqs);
1781        assert_eq!(errors.len(), 1, "{}", ValidationReport(errors));
1782        assert!(matches!(
1783            &errors[0],
1784            PidValidationError::MissingField { field, .. } if field == "name1"
1785        ));
1786    }
1787
1788    #[test]
1789    fn multi_variant_entity_unknown_qualifier_is_invalid_code_only() {
1790        let reqs = multi_variant_requirements();
1791        for bad in [json!("Z99"), json!("bogus"), json!({ "code": "Z99" })] {
1792            let json = json!({ "geschaeftspartner": [{ "partnerrolle": bad }] });
1793            let errors = validate_pid_json(&json, &reqs);
1794            // No variant matches: variant fields become optional, codes are unioned.
1795            assert_eq!(errors.len(), 1, "{bad}: {}", ValidationReport(errors));
1796            match &errors[0] {
1797                PidValidationError::InvalidCode {
1798                    field,
1799                    valid_values,
1800                    ..
1801                } => {
1802                    assert_eq!(field, "partnerrolle");
1803                    let codes: Vec<&str> = valid_values.iter().map(|(c, _)| c.as_str()).collect();
1804                    assert_eq!(codes, ["Z03", "Z07"]);
1805                }
1806                other => panic!("expected InvalidCode, got {other:?}"),
1807            }
1808        }
1809    }
1810
1811    #[test]
1812    fn code_objects_and_enum_mapped_names_are_code_checked() {
1813        let f = field("partnerrolle", "X", &[("Z07", "kundeMsb")]);
1814        assert_eq!(invalid_code_value(&json!("Z07"), &f), None);
1815        assert_eq!(invalid_code_value(&json!("kundeMsb"), &f), None);
1816        assert_eq!(invalid_code_value(&json!({ "code": "kundeMsb" }), &f), None);
1817        assert_eq!(invalid_code_value(&json!({ "code": "Z07" }), &f), None);
1818        assert_eq!(
1819            invalid_code_value(&json!({ "code": "Z99", "meaning": null }), &f),
1820            Some("Z99".to_string())
1821        );
1822        assert_eq!(
1823            invalid_code_value(&json!("kundeLf"), &f),
1824            Some("kundeLf".to_string())
1825        );
1826        // Non-code values (numbers, objects without code) are not code-checked.
1827        assert_eq!(invalid_code_value(&json!(7), &f), None);
1828        assert_eq!(invalid_code_value(&json!({ "meaning": "x" }), &f), None);
1829    }
1830}