1use 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#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Severity {
18 Error,
20 Warning,
22}
23
24#[derive(Debug, Clone)]
26pub enum PidValidationError {
27 MissingEntity {
29 entity: String,
30 ahb_status: String,
31 severity: Severity,
32 },
33 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 InvalidCode {
44 entity: String,
45 field: String,
46 value: String,
47 valid_values: Vec<(String, String)>,
48 },
49 NotAllowed {
55 entity: String,
56 field: String,
57 value: Option<String>,
58 ahb_status: String,
59 severity: Severity,
60 },
61 ConditionNotSatisfied {
67 entity: String,
68 field: String,
69 value: String,
70 ahb_status: String,
71 },
72 RepeatedInTransaction {
75 entity: String,
76 count: usize,
77 ahb_status: String,
78 },
79 NotANumber {
82 entity: String,
83 field: String,
84 value: String,
85 format: String,
86 },
87 TooLong {
90 entity: String,
91 field: String,
92 length: usize,
93 format: String,
94 },
95}
96
97impl PidValidationError {
98 pub fn severity(&self) -> &Severity {
99 match self {
100 Self::MissingEntity { severity, .. } => severity,
101 Self::MissingField { severity, .. } => severity,
102 Self::NotAllowed { severity, .. } => severity,
103 Self::InvalidCode { .. }
104 | Self::TooLong { .. }
105 | Self::ConditionNotSatisfied { .. }
106 | Self::RepeatedInTransaction { .. }
107 | Self::NotANumber { .. } => &Severity::Error,
108 }
109 }
110
111 pub fn is_error(&self) -> bool {
112 matches!(self.severity(), Severity::Error)
113 }
114}
115
116impl fmt::Display for PidValidationError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 match self {
119 PidValidationError::MissingEntity {
120 entity,
121 ahb_status,
122 severity,
123 } => {
124 let label = severity_label(severity);
125 write!(
126 f,
127 "{label}: missing entity '{entity}' (required: {ahb_status})"
128 )
129 }
130 PidValidationError::MissingField {
131 entity,
132 field,
133 ahb_status,
134 rust_type,
135 valid_values,
136 severity,
137 } => {
138 let label = severity_label(severity);
139 write!(
140 f,
141 "{label}: missing {entity}.{field} (required: {ahb_status})"
142 )?;
143 if let Some(rt) = rust_type {
144 write!(f, "\n → type: {rt}")?;
145 }
146 if !valid_values.is_empty() {
147 let codes: Vec<String> = valid_values
148 .iter()
149 .map(|(code, meaning)| {
150 if meaning.is_empty() {
151 code.clone()
152 } else {
153 format!("{code} ({meaning})")
154 }
155 })
156 .collect();
157 write!(f, "\n → valid: {}", codes.join(", "))?;
158 }
159 Ok(())
160 }
161 PidValidationError::NotANumber {
162 entity,
163 field,
164 value,
165 format,
166 } => write!(
167 f,
168 "INVALID: {entity}.{field} = \"{value}\" is not a number\n → format: {format}"
169 ),
170 PidValidationError::TooLong {
171 entity,
172 field,
173 length,
174 format,
175 } => write!(
176 f,
177 "INVALID: {entity}.{field} has {length} characters\n → format: {format}"
178 ),
179 PidValidationError::InvalidCode {
180 entity,
181 field,
182 value,
183 valid_values,
184 } => {
185 write!(f, "INVALID: {entity}.{field} = \"{value}\"")?;
186 if !valid_values.is_empty() {
187 let codes: Vec<String> = valid_values.iter().map(|(c, _)| c.clone()).collect();
188 write!(f, "\n → valid: {}", codes.join(", "))?;
189 }
190 Ok(())
191 }
192 PidValidationError::RepeatedInTransaction {
193 entity,
194 count,
195 ahb_status,
196 } => write!(
197 f,
198 "ERROR: {entity} is sent {count} times in one transaction; its condition allows it once ({ahb_status})"
199 ),
200 PidValidationError::ConditionNotSatisfied {
201 entity,
202 field,
203 value,
204 ahb_status,
205 } => write!(
206 f,
207 "ERROR: {entity}.{field} = \"{value}\" does not satisfy its condition ({ahb_status})"
208 ),
209 PidValidationError::NotAllowed {
210 entity,
211 field,
212 value,
213 ahb_status,
214 severity,
215 } => {
216 write!(f, "{}: {entity}", severity_label(severity))?;
217 if !field.is_empty() {
218 write!(f, ".{field}")?;
219 }
220 if let Some(value) = value {
221 write!(f, " = \"{value}\"")?;
222 }
223 write!(
224 f,
225 " present although its condition does not hold ({ahb_status})"
226 )
227 }
228 }
229 }
230}
231
232fn severity_label(severity: &Severity) -> &'static str {
233 match severity {
234 Severity::Error => "ERROR",
235 Severity::Warning => "WARNING",
236 }
237}
238
239pub struct ValidationReport(pub Vec<PidValidationError>);
241
242impl ValidationReport {
243 pub fn has_errors(&self) -> bool {
245 self.0.iter().any(|e| e.is_error())
246 }
247
248 pub fn errors(&self) -> Vec<&PidValidationError> {
250 self.0.iter().filter(|e| e.is_error()).collect()
251 }
252
253 pub fn is_empty(&self) -> bool {
255 self.0.is_empty()
256 }
257
258 pub fn len(&self) -> usize {
260 self.0.len()
261 }
262}
263
264impl fmt::Display for ValidationReport {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 for (i, err) in self.0.iter().enumerate() {
267 if i > 0 {
268 writeln!(f)?;
269 }
270 write!(f, "{err}")?;
271 }
272 Ok(())
273 }
274}
275
276pub fn validate_pid_json(json: &Value, requirements: &PidRequirements) -> Vec<PidValidationError> {
288 validate_entities(json, &requirements.entities, None)
289}
290
291pub fn validate_pid_json_transaction(
297 json: &Value,
298 requirements: &PidRequirements,
299) -> Vec<PidValidationError> {
300 validate_entities(json, &requirements.entities, Some(EntityScope::Transaction))
301}
302
303fn validate_entities(
305 json: &Value,
306 entities: &[EntityRequirement],
307 scope_filter: Option<EntityScope>,
308) -> Vec<PidValidationError> {
309 let mut errors = Vec::new();
310
311 for entity_req in entities {
312 if let Some(ref scope) = scope_filter {
314 if &entity_req.scope != scope {
315 continue;
316 }
317 }
318
319 let key = to_camel_case(&entity_req.entity);
320
321 match json.get(&key) {
322 None | Some(serde_json::Value::Null) => {
323 if is_unconditionally_required(&entity_req.ahb_status) {
324 errors.push(PidValidationError::MissingEntity {
325 entity: entity_req.entity.clone(),
326 ahb_status: entity_req.ahb_status.clone(),
327 severity: Severity::Error,
328 });
329 }
330 }
331 Some(val) => {
332 if let Some(arr) = val.as_array() {
335 for element in arr {
336 validate_entity_fields(element, entity_req, &mut errors);
337 }
338 } else {
339 validate_entity_fields(val, entity_req, &mut errors);
340 }
341 }
342 }
343 }
344
345 errors
346}
347
348pub fn get_nested<'a>(json: &'a Value, path: &str) -> Option<&'a Value> {
351 if let Some((list, rest)) = path.split_once("[].") {
354 return get_nested(json, list)?
355 .as_array()?
356 .iter()
357 .find_map(|item| get_nested(item, rest).filter(|v| !v.is_null()));
358 }
359 let mut current = json;
360 for part in path.split('.') {
361 current = current.get(part).or_else(|| {
362 if part.contains('_') {
363 current.get(snake_to_camel_case(part))
364 } else {
365 None
366 }
367 })?;
368 }
369 Some(current)
370}
371
372fn validate_entity_fields(
374 entity_json: &Value,
375 entity_req: &EntityRequirement,
376 errors: &mut Vec<PidValidationError>,
377) {
378 let fields = effective_field_requirements(entity_req, entity_json);
379 let exempt =
380 fields_of_unrequired_absent_groups(entity_req, entity_json, is_unconditionally_required);
381 for field_req in fields.iter() {
382 let val = get_nested(entity_json, &field_req.bo4e_name);
385
386 let val = val.filter(|v| !v.is_null());
388
389 match val {
390 None if exempt.contains(field_req.bo4e_name.as_str()) => {}
391 None => {
392 if is_unconditionally_required(&field_req.ahb_status) {
393 errors.push(PidValidationError::MissingField {
394 entity: entity_req.entity.clone(),
395 field: field_req.bo4e_name.clone(),
396 ahb_status: field_req.ahb_status.clone(),
397 rust_type: field_req.enum_name.clone(),
398 valid_values: code_values_to_tuples(&field_req.valid_codes),
399 severity: Severity::Error,
400 });
401 }
402 }
403 Some(val) => {
404 validate_code_value(val, entity_req, field_req, errors);
405 }
406 }
407 }
408 validate_nested_lists(
409 &entity_req.entity,
410 entity_json,
411 &entity_req.nested,
412 "",
413 &|status, _| is_unconditionally_required(status).then_some(Severity::Error),
414 &|_| None,
415 &|_, _| false,
417 errors,
418 );
419}
420
421pub fn validate_nested_lists(
431 entity: &str,
432 element: &Value,
433 lists: &[NestedListRequirement],
434 prefix: &str,
435 required: &dyn Fn(&str, &[(String, usize)]) -> Option<Severity>,
436 variant_holds: &dyn Fn(&VariantQualifier) -> Option<bool>,
437 forbidden: &dyn Fn(&str, &[(String, usize)]) -> bool,
438 errors: &mut Vec<PidValidationError>,
439) {
440 nested_lists_at(
441 entity,
442 element,
443 lists,
444 prefix,
445 &mut Vec::new(),
446 required,
447 variant_holds,
448 forbidden,
449 errors,
450 );
451}
452
453#[allow(clippy::too_many_arguments)]
455fn nested_lists_at(
456 entity: &str,
457 element: &Value,
458 lists: &[NestedListRequirement],
459 prefix: &str,
460 position: &mut Vec<(String, usize)>,
461 required: &dyn Fn(&str, &[(String, usize)]) -> Option<Severity>,
462 variant_holds: &dyn Fn(&VariantQualifier) -> Option<bool>,
463 forbidden: &dyn Fn(&str, &[(String, usize)]) -> bool,
464 errors: &mut Vec<PidValidationError>,
465) {
466 let applies = |kind: &NestedElementKind| {
469 kind.transaction_variant
470 .as_ref()
471 .map_or(Some(true), variant_holds)
472 };
473 let mut fields: Vec<&str> = lists.iter().map(|l| l.field.as_str()).collect();
476 fields.sort_unstable();
477 fields.dedup();
478 for field in fields {
479 let candidates: Vec<&NestedListRequirement> = lists
482 .iter()
483 .filter(|l| l.field == field)
484 .filter(|l| {
485 l.parent_selector
486 .iter()
487 .all(|selector| selector_matches(selector, element))
488 })
489 .collect();
490 if candidates.is_empty() {
491 continue;
492 }
493 let items: &[Value] = get_nested(element, field)
494 .and_then(|v| v.as_array())
495 .map_or(&[], |a| a.as_slice());
496 let label = format!("{prefix}{field}");
497 let alone = candidates.len() == 1;
498
499 let chosen = match &candidates[..] {
503 [only] => Some(*only),
504 _ if items.is_empty() => None,
505 _ => {
506 let fitting: Vec<&&NestedListRequirement> = candidates
507 .iter()
508 .filter(|l| items.iter().all(|item| kind_of(l, item, false).is_some()))
509 .collect();
510 match fitting[..] {
511 [one] => Some(*one),
512 _ => None,
513 }
514 }
515 };
516
517 if let Some(list) = chosen {
518 for kind in &list.kinds {
519 if applies(kind) != Some(true) {
520 continue;
521 }
522 let present = if alone && list.kinds.len() == 1 {
523 !items.is_empty()
524 } else {
525 items.iter().any(|item| kind_matches(kind, item))
526 };
527 if present {
528 continue;
529 }
530 if let Some(severity) = required(&kind.ahb_status, position) {
531 let codes = kind.selector.first().map_or(&[][..], |s| &s.codes[..]);
532 let name = if alone && list.kinds.len() == 1 {
535 String::new()
536 } else {
537 codes
538 .first()
539 .map(|c| c.bo4e_value.clone().unwrap_or_else(|| c.code.clone()))
540 .unwrap_or_default()
541 };
542 errors.push(PidValidationError::MissingField {
543 entity: entity.to_string(),
544 field: format!("{label}[{name}]"),
545 ahb_status: kind.ahb_status.clone(),
546 rust_type: None,
547 valid_values: code_values_to_tuples(codes),
548 severity,
549 });
550 }
551 }
552 }
553
554 for (index, item) in items.iter().enumerate() {
555 position.push((field.to_string(), index));
556 let here = position.clone();
557 let required_here = |status: &str| required(status, &here);
558 let matching: Vec<(&NestedListRequirement, &NestedElementKind)> = match chosen {
559 Some(list) => kind_of(list, item, alone)
560 .filter(|k| applies(k) != Some(false))
561 .map(|k| (list, k))
562 .into_iter()
563 .collect(),
564 None => candidates
565 .iter()
566 .flat_map(|l| {
567 l.kinds
568 .iter()
569 .filter(|k| applies(k) != Some(false))
570 .filter(|k| kind_matches(k, item))
571 .map(move |k| (*l, k))
572 })
573 .collect(),
574 };
575 let best = matching
579 .iter()
580 .map(|(l, k)| {
581 (
582 *l,
583 *k,
584 element_findings(entity, &label, k, item, &required_here),
585 )
586 })
587 .min_by_key(|(_, k, f)| (f.len(), k.selector.is_empty()));
588 if let Some((list, kind, findings)) = best {
589 errors.extend(findings);
590 let forbidden_here = |status: &str| forbidden(status, &here);
593 if forbidden_here(&kind.ahb_status) {
594 let name = kind
595 .selector
596 .first()
597 .and_then(|s| s.codes.first())
598 .map(|c| c.bo4e_value.clone().unwrap_or_else(|| c.code.clone()))
599 .unwrap_or_default();
600 errors.push(PidValidationError::NotAllowed {
601 entity: entity.to_string(),
602 field: format!("{label}[{name}]"),
603 value: None,
604 ahb_status: kind.ahb_status.clone(),
605 severity: Severity::Warning,
606 });
607 } else {
608 errors.extend(not_allowed_codes(
609 entity,
610 &format!("{label}[]."),
611 &kind.fields,
612 item,
613 &forbidden_here,
614 ));
615 }
616 nested_lists_at(
617 entity,
618 item,
619 &list.nested,
620 &format!("{label}[]."),
621 position,
622 required,
623 variant_holds,
624 forbidden,
625 errors,
626 );
627 }
628 position.pop();
629 }
630 }
631}
632
633fn kind_of<'l>(
637 list: &'l NestedListRequirement,
638 item: &Value,
639 alone: bool,
640) -> Option<&'l NestedElementKind> {
641 match &list.kinds[..] {
642 [only] if alone => Some(only),
643 kinds => kinds.iter().find(|k| kind_matches(k, item)),
644 }
645}
646
647fn kind_matches(kind: &NestedElementKind, item: &Value) -> bool {
650 kind.selector
651 .iter()
652 .all(|selector| selector_matches(selector, item))
653}
654
655fn selector_matches(selector: &KindSelector, item: &Value) -> bool {
657 get_nested(item, &selector.field)
658 .and_then(code_field_value)
659 .is_some_and(|value| {
660 selector
661 .codes
662 .iter()
663 .any(|c| c.code == value || c.bo4e_value.as_deref() == Some(value))
664 })
665}
666
667pub fn not_allowed_codes(
675 entity: &str,
676 label: &str,
677 fields: &[FieldRequirement],
678 element: &Value,
679 forbidden: &dyn Fn(&str) -> bool,
680) -> Vec<PidValidationError> {
681 let mut out = Vec::new();
682 for field_req in fields {
683 let values = all_nested(element, &field_req.bo4e_name);
684 if values.is_empty() {
685 continue;
686 }
687 let name = format!("{label}{}", field_req.bo4e_name);
688 for value in values {
689 let Some(code) = code_field_value(value) else {
690 continue;
691 };
692 let status = field_req
693 .valid_codes
694 .iter()
695 .find(|cv| cv.code == code || cv.bo4e_value.as_deref() == Some(code))
696 .and_then(|cv| cv.ahb_status.as_deref());
697 if let Some(status) = status.filter(|s| forbidden(s)) {
698 out.push(PidValidationError::NotAllowed {
699 entity: entity.to_string(),
700 field: name.clone(),
701 value: Some(code.to_string()),
702 ahb_status: status.to_string(),
703 severity: Severity::Warning,
704 });
705 }
706 }
707 }
708 out
709}
710
711fn element_findings(
714 entity: &str,
715 label: &str,
716 kind: &NestedElementKind,
717 item: &Value,
718 required: &dyn Fn(&str) -> Option<Severity>,
719) -> Vec<PidValidationError> {
720 let mut out = Vec::new();
721 for field_req in &kind.fields {
722 let name = format!("{label}[].{}", field_req.bo4e_name);
723 let values = all_nested(item, &field_req.bo4e_name);
724 if values.is_empty() {
725 if let Some(severity) = required(&field_req.ahb_status) {
726 out.push(PidValidationError::MissingField {
727 entity: entity.to_string(),
728 field: name,
729 ahb_status: field_req.ahb_status.clone(),
730 rust_type: field_req.enum_name.clone(),
731 valid_values: code_values_to_tuples(&field_req.valid_codes),
732 severity,
733 });
734 }
735 continue;
736 }
737 for value in values {
738 out.extend(too_long(entity, &name, value, field_req));
739 out.extend(not_a_number(entity, &name, value, field_req));
740 if let Some(value) = invalid_code_value(value, field_req) {
741 out.push(PidValidationError::InvalidCode {
742 entity: entity.to_string(),
743 field: name.clone(),
744 value,
745 valid_values: code_values_to_tuples(&field_req.valid_codes),
746 });
747 }
748 }
749 }
750 out
751}
752
753fn all_nested<'a>(json: &'a Value, path: &str) -> Vec<&'a Value> {
756 if let Some((list, rest)) = path.split_once("[].") {
757 return get_nested(json, list)
758 .and_then(|v| v.as_array())
759 .map(|items| {
760 items
761 .iter()
762 .flat_map(|item| all_nested(item, rest))
763 .collect()
764 })
765 .unwrap_or_default();
766 }
767 get_nested(json, path)
768 .filter(|v| !v.is_null())
769 .into_iter()
770 .collect()
771}
772
773pub fn not_a_number(
778 entity: &str,
779 field: &str,
780 val: &Value,
781 field_req: &FieldRequirement,
782) -> Option<PidValidationError> {
783 if !field_req.valid_codes.is_empty() {
784 return None;
785 }
786 let format = field_req.format.as_deref()?;
787 let text = val.as_str()?;
788 if !format.trim().starts_with('n')
789 || text.is_empty()
790 || field_req
791 .free_data_codes
792 .iter()
793 .any(|c| c.code == text || c.bo4e_value.as_deref() == Some(text))
794 {
795 return None;
796 }
797 let unsigned = text.strip_prefix('-').unwrap_or(text);
798 let digits = unsigned.chars().filter(char::is_ascii_digit).count();
799 let marks = unsigned.chars().filter(|c| matches!(c, '.' | ',')).count();
800 let number = digits > 0 && marks <= 1 && digits + marks == unsigned.chars().count();
801 (!number).then(|| PidValidationError::NotANumber {
802 entity: entity.to_string(),
803 field: field.to_string(),
804 value: text.to_string(),
805 format: format.to_string(),
806 })
807}
808
809pub fn too_long(
813 entity: &str,
814 field: &str,
815 val: &Value,
816 field_req: &FieldRequirement,
817) -> Option<PidValidationError> {
818 if !field_req.valid_codes.is_empty() {
821 return None;
822 }
823 let format = field_req.format.as_deref()?;
824 let text = val.as_str()?;
825 if field_req
829 .free_data_codes
830 .iter()
831 .any(|c| c.code == text || c.bo4e_value.as_deref() == Some(text))
832 {
833 return None;
834 }
835 let digits = format
836 .trim()
837 .strip_prefix("an")
838 .or_else(|| format.trim().strip_prefix('a'))
839 .or_else(|| format.trim().strip_prefix('n'))?;
840 let max: usize = digits.strip_prefix("..").unwrap_or(digits).parse().ok()?;
841 let length = if format.trim().starts_with('n') {
844 text.chars()
845 .filter(|c| !matches!(c, '.' | ',' | '-'))
846 .count()
847 } else {
848 text.chars().count()
849 };
850 (length > max).then(|| PidValidationError::TooLong {
851 entity: entity.to_string(),
852 field: field.to_string(),
853 length,
854 format: format.to_string(),
855 })
856}
857
858fn validate_code_value(
860 val: &Value,
861 entity_req: &EntityRequirement,
862 field_req: &FieldRequirement,
863 errors: &mut Vec<PidValidationError>,
864) {
865 if let Some(value) = invalid_code_value(val, field_req) {
866 errors.push(PidValidationError::InvalidCode {
867 entity: entity_req.entity.clone(),
868 field: field_req.bo4e_name.clone(),
869 value,
870 valid_values: code_values_to_tuples(&field_req.valid_codes),
871 });
872 }
873 errors.extend(too_long(
874 &entity_req.entity,
875 &field_req.bo4e_name,
876 val,
877 field_req,
878 ));
879 errors.extend(not_a_number(
880 &entity_req.entity,
881 &field_req.bo4e_name,
882 val,
883 field_req,
884 ));
885}
886
887pub fn code_field_value(val: &Value) -> Option<&str> {
890 val.as_str()
891 .or_else(|| val.get("code").and_then(|c| c.as_str()))
892}
893
894pub fn invalid_code_value(val: &Value, field_req: &FieldRequirement) -> Option<String> {
901 if field_req.valid_codes.is_empty() {
902 return None;
903 }
904 let value = code_field_value(val)?;
905 let is_valid = field_req
906 .valid_codes
907 .iter()
908 .any(|cv| cv.code == value || cv.bo4e_value.as_deref() == Some(value));
909 (!is_valid).then(|| value.to_string())
910}
911
912pub fn variant_statuses<'a>(entity_req: &'a EntityRequirement, element: &Value) -> Vec<&'a str> {
916 let mut out: Vec<&'a str> = Vec::new();
917 for v in &entity_req.variants {
918 if v.ahb_status.is_empty() {
919 continue;
920 }
921 let value = get_nested(element, &v.discriminator_field).and_then(code_field_value);
922 if value.is_some_and(|s| v.code == s || v.bo4e_value.as_deref() == Some(s))
923 && !out.contains(&v.ahb_status.as_str())
924 {
925 out.push(v.ahb_status.as_str());
926 }
927 }
928 out
929}
930
931pub fn effective_field_requirements<'a>(
946 entity_req: &'a EntityRequirement,
947 element: &Value,
948) -> Cow<'a, [FieldRequirement]> {
949 if entity_req.variants.is_empty() {
950 return Cow::Borrowed(&entity_req.fields);
951 }
952
953 let mut by_field: BTreeMap<&str, Vec<&EntityVariantRequirement>> = BTreeMap::new();
955 for v in &entity_req.variants {
956 by_field
957 .entry(v.discriminator_field.as_str())
958 .or_default()
959 .push(v);
960 }
961 let mut candidates: Vec<&EntityVariantRequirement> = Vec::new();
962 for (field, group) in by_field {
963 let value = get_nested(element, field).and_then(code_field_value);
964 let matched: Vec<&EntityVariantRequirement> = group
965 .iter()
966 .copied()
967 .filter(|v| value.is_some_and(|s| v.code == s || v.bo4e_value.as_deref() == Some(s)))
968 .collect();
969 candidates.extend(if matched.is_empty() { group } else { matched });
970 }
971
972 let mut owned: Vec<&str> = Vec::new();
974 let mut owned_set: BTreeSet<&str> = BTreeSet::new();
975 for v in &entity_req.variants {
976 for f in &v.fields {
977 if owned_set.insert(f.bo4e_name.as_str()) {
978 owned.push(f.bo4e_name.as_str());
979 }
980 }
981 }
982
983 let mut combined: BTreeMap<&str, FieldRequirement> = BTreeMap::new();
984 for name in owned {
985 let reqs: Vec<&FieldRequirement> = candidates
986 .iter()
987 .filter_map(|v| v.fields.iter().find(|f| f.bo4e_name == name))
988 .collect();
989 let Some((first, rest)) = reqs.split_first() else {
990 continue; };
992 let mut field = (*first).clone();
993 let mut statuses_agree = reqs.len() == candidates.len();
994 for r in rest {
995 if r.ahb_status != field.ahb_status {
996 statuses_agree = false;
997 }
998 for cv in &r.valid_codes {
999 if !field.valid_codes.iter().any(|c| c.code == cv.code) {
1000 field.valid_codes.push(cv.clone());
1001 }
1002 }
1003 }
1004 if !statuses_agree {
1005 field.ahb_status = String::new();
1006 }
1007 combined.insert(name, field);
1008 }
1009
1010 let mut result: Vec<FieldRequirement> = Vec::with_capacity(entity_req.fields.len());
1011 for f in &entity_req.fields {
1012 if owned_set.contains(f.bo4e_name.as_str()) {
1013 if let Some(c) = combined.remove(f.bo4e_name.as_str()) {
1014 result.push(c);
1015 }
1016 } else {
1017 result.push(f.clone());
1018 }
1019 }
1020 result.extend(combined.into_values());
1021 Cow::Owned(result)
1022}
1023
1024pub fn absent_groups<'a>(
1027 entity_req: &'a EntityRequirement,
1028 element: &'a Value,
1029) -> impl Iterator<Item = &'a EntityGroupRequirement> + 'a {
1030 entity_req.groups.iter().filter(move |g| {
1031 !g.fields
1032 .iter()
1033 .any(|f| get_nested(element, f).is_some_and(|v| !v.is_null()))
1034 })
1035}
1036
1037pub fn fields_of_unrequired_absent_groups<'a>(
1046 entity_req: &'a EntityRequirement,
1047 element: &'a Value,
1048 mut group_required: impl FnMut(&str) -> bool,
1049) -> BTreeSet<&'a str> {
1050 let exempt: Vec<&EntityGroupRequirement> = absent_groups(entity_req, element)
1051 .filter(|g| !group_required(&g.ahb_status))
1052 .collect();
1053 let mut fields = BTreeSet::new();
1054 for g in &exempt {
1055 for f in &g.fields {
1056 let kept_elsewhere = entity_req.groups.iter().any(|other| {
1059 other.fields.contains(f) && !exempt.iter().any(|e| std::ptr::eq(*e, other))
1060 });
1061 if !kept_elsewhere {
1062 fields.insert(f.as_str());
1063 }
1064 }
1065 }
1066 fields
1067}
1068
1069fn code_values_to_tuples(codes: &[CodeValue]) -> Vec<(String, String)> {
1071 codes
1072 .iter()
1073 .map(|cv| (cv.code.clone(), cv.meaning.clone()))
1074 .collect()
1075}
1076
1077fn to_camel_case(s: &str) -> String {
1083 if s.is_empty() {
1084 return String::new();
1085 }
1086 let mut chars = s.chars();
1087 let first = chars.next().unwrap();
1088 let mut result = first.to_lowercase().to_string();
1089 result.extend(chars);
1090 result
1091}
1092
1093fn snake_to_camel_case(s: &str) -> String {
1104 let mut result = String::with_capacity(s.len());
1105 let mut capitalize_next = false;
1106 for ch in s.chars() {
1107 if ch == '_' {
1108 capitalize_next = true;
1109 } else if capitalize_next {
1110 result.extend(ch.to_uppercase());
1111 capitalize_next = false;
1112 } else {
1113 result.push(ch);
1114 }
1115 }
1116 result
1117}
1118
1119fn is_unconditionally_required(ahb_status: &str) -> bool {
1121 matches!(ahb_status, "X" | "Muss" | "Soll")
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126
1127 #[test]
1132 fn a_numeric_field_holds_a_number() {
1133 let field = FieldRequirement {
1134 bo4e_name: "geplantesPaket".to_string(),
1135 ahb_status: "X [914] ∧ [937]".to_string(),
1136 field_type: "data".to_string(),
1137 format: Some("n..10".to_string()),
1138 enum_name: None,
1139 free_data_codes: vec![],
1140 element_status: String::new(),
1141 segment: None,
1142 valid_codes: vec![],
1143 ref_type: crate::pid_requirements::Bo4eRefType::Unknown,
1144 };
1145 let check = |v: &str| not_a_number("Prozessdaten", "geplantesPaket", &json!(v), &field);
1146 assert!(check("O5D2DXBG1A").is_some());
1147 assert!(check("1e3").is_some());
1148 assert!(check("1.2.3").is_some());
1149 assert!(check("12").is_none());
1150 assert!(check("-0,5").is_none());
1151 assert!(check("").is_none());
1152 }
1153
1154 #[test]
1155 fn too_long_skips_codes_of_a_free_data_field() {
1156 let field = FieldRequirement {
1157 bo4e_name: "merkmal.code".to_string(),
1158 ahb_status: "X".to_string(),
1159 field_type: "data".to_string(),
1160 format: Some("an..3".to_string()),
1161 enum_name: None,
1162 free_data_codes: vec![CodeValue {
1163 code: "ZA9".to_string(),
1164 meaning: "Übertragungsnetzbetreiber".to_string(),
1165 enum_name: None,
1166 bo4e_value: Some("uebertragungsnetzbetreiber".to_string()),
1167 ahb_status: None,
1168 }],
1169 element_status: String::new(),
1170 segment: None,
1171 valid_codes: vec![],
1172 ref_type: crate::pid_requirements::Bo4eRefType::Unknown,
1173 };
1174 let check = |v: &str| too_long("E", "zuordnungen[].merkmal.code", &json!(v), &field);
1175 assert!(check("uebertragungsnetzbetreiber").is_none());
1176 assert!(check("ZA9").is_none());
1177 assert!(check("Z1").is_none());
1178 assert!(matches!(
1179 check("ZDNBNAPG56ZM"),
1180 Some(PidValidationError::TooLong { length: 12, .. })
1181 ));
1182 }
1183 use super::*;
1184
1185 #[test]
1189 fn a_variant_bound_kind_is_demanded_only_in_its_variant() {
1190 use crate::pid_requirements::{NestedElementKind, NestedListRequirement, VariantQualifier};
1191 let lists = vec![NestedListRequirement {
1192 field: "zuordnungen".to_string(),
1193 bo4e_type: "Zuordnung".to_string(),
1194 source_path: "sg4.sg8_z22.sg10".to_string(),
1195 kinds: vec![NestedElementKind {
1196 ahb_status: "Muss".to_string(),
1197 selector: vec![],
1198 fields: vec![],
1199 transaction_variant: Some(VariantQualifier {
1200 group: "SG4".to_string(),
1201 segment: "IDE".to_string(),
1202 codes: vec!["24".to_string()],
1203 }),
1204 }],
1205 parent_selector: vec![],
1206 nested: vec![],
1207 }];
1208 let demanded = |holds: Option<bool>| {
1209 let mut errors = Vec::new();
1210 validate_nested_lists(
1211 "SummenzeitreihenDaten",
1212 &serde_json::json!({}),
1213 &lists,
1214 "",
1215 &|_, _| Some(Severity::Error),
1216 &|_| holds,
1217 &|_, _| false,
1218 &mut errors,
1219 );
1220 errors.len()
1221 };
1222 assert_eq!(demanded(Some(true)), 1);
1223 assert_eq!(demanded(Some(false)), 0);
1224 assert_eq!(demanded(None), 0);
1225 }
1226 use crate::pid_requirements::{
1227 Bo4eRefType, Cardinality, CodeValue, EntityRequirement, FieldRequirement, PidRequirements,
1228 };
1229 use serde_json::json;
1230
1231 fn sample_requirements() -> PidRequirements {
1232 PidRequirements {
1233 transaktion_wiederholbar: false,
1234 pid: "55001".to_string(),
1235 beschreibung: "Anmeldung verb. MaLo".to_string(),
1236 entities: vec![
1237 EntityRequirement {
1238 entity: "Prozessdaten".to_string(),
1239 ref_type: Bo4eRefType::Object {
1240 type_name: "Prozessdaten".to_string(),
1241
1242 cardinality: Cardinality::REQUIRED,
1243 },
1244
1245 ahb_status: "Muss".to_string(),
1246 map_key: None,
1247 scope: EntityScope::Transaction,
1248 variants: vec![],
1249 groups: vec![],
1250 fields: vec![
1251 FieldRequirement {
1252 bo4e_name: "vorgangId".to_string(),
1253 ahb_status: "X".to_string(),
1254 field_type: "data".to_string(),
1255 format: None,
1256 enum_name: None,
1257 free_data_codes: Vec::new(),
1258 element_status: String::new(),
1259 segment: None,
1260 valid_codes: vec![],
1261 ref_type: Bo4eRefType::Unknown,
1262 },
1263 FieldRequirement {
1264 bo4e_name: "transaktionsgrund".to_string(),
1265 ahb_status: "X".to_string(),
1266 field_type: "code".to_string(),
1267 format: None,
1268 enum_name: Some("Transaktionsgrund".to_string()),
1269 free_data_codes: Vec::new(),
1270 element_status: String::new(),
1271 segment: None,
1272 valid_codes: vec![
1273 CodeValue {
1274 code: "E01".to_string(),
1275 meaning: "Ein-/Auszug (Einzug)".to_string(),
1276 enum_name: None,
1277 bo4e_value: None,
1278 ahb_status: None,
1279 },
1280 CodeValue {
1281 code: "E03".to_string(),
1282 meaning: "Wechsel".to_string(),
1283 enum_name: None,
1284 bo4e_value: None,
1285 ahb_status: None,
1286 },
1287 ],
1288 ref_type: Bo4eRefType::Unknown,
1289 },
1290 ],
1291 nested: Vec::new(),
1292 },
1293 EntityRequirement {
1294 entity: "Marktlokation".to_string(),
1295 ref_type: Bo4eRefType::Object {
1296 type_name: "Marktlokation".to_string(),
1297
1298 cardinality: Cardinality::REQUIRED,
1299 },
1300
1301 ahb_status: "Muss".to_string(),
1302 map_key: None,
1303 scope: EntityScope::Transaction,
1304 variants: vec![],
1305 groups: vec![],
1306 fields: vec![
1307 FieldRequirement {
1308 bo4e_name: "marktlokationsId".to_string(),
1309 ahb_status: "X".to_string(),
1310 field_type: "data".to_string(),
1311 format: None,
1312 enum_name: None,
1313 free_data_codes: Vec::new(),
1314 element_status: String::new(),
1315 segment: None,
1316 valid_codes: vec![],
1317 ref_type: Bo4eRefType::Unknown,
1318 },
1319 FieldRequirement {
1320 bo4e_name: "haushaltskunde".to_string(),
1321 ahb_status: "X".to_string(),
1322 field_type: "code".to_string(),
1323 format: None,
1324 enum_name: Some("Haushaltskunde".to_string()),
1325 free_data_codes: Vec::new(),
1326 element_status: String::new(),
1327 segment: None,
1328 valid_codes: vec![
1329 CodeValue {
1330 code: "Z15".to_string(),
1331 meaning: "Ja".to_string(),
1332 enum_name: None,
1333 bo4e_value: None,
1334 ahb_status: None,
1335 },
1336 CodeValue {
1337 code: "Z18".to_string(),
1338 meaning: "Nein".to_string(),
1339 enum_name: None,
1340 bo4e_value: None,
1341 ahb_status: None,
1342 },
1343 ],
1344 ref_type: Bo4eRefType::Unknown,
1345 },
1346 ],
1347 nested: Vec::new(),
1348 },
1349 EntityRequirement {
1350 entity: "Geschaeftspartner".to_string(),
1351 ref_type: Bo4eRefType::Object {
1352 type_name: "Geschaeftspartner".to_string(),
1353
1354 cardinality: Cardinality {
1355 min: 1,
1356 max: Some(7),
1357 },
1358 },
1359
1360 ahb_status: "Muss".to_string(),
1361 map_key: None,
1362 scope: EntityScope::Transaction,
1363 variants: vec![],
1364 groups: vec![],
1365 fields: vec![FieldRequirement {
1366 bo4e_name: "identifikation".to_string(),
1367 ahb_status: "X".to_string(),
1368 field_type: "data".to_string(),
1369 format: None,
1370 enum_name: None,
1371 free_data_codes: Vec::new(),
1372 element_status: String::new(),
1373 segment: None,
1374 valid_codes: vec![],
1375 ref_type: Bo4eRefType::Unknown,
1376 }],
1377 nested: Vec::new(),
1378 },
1379 ],
1380 }
1381 }
1382
1383 #[test]
1384 fn test_validate_complete_json() {
1385 let reqs = sample_requirements();
1386 let json = json!({
1387 "prozessdaten": {
1388 "vorgangId": "ABC123",
1389 "transaktionsgrund": "E01"
1390 },
1391 "marktlokation": {
1392 "marktlokationsId": "51234567890",
1393 "haushaltskunde": "Z15"
1394 },
1395 "geschaeftspartner": [
1396 { "identifikation": "9900000000003" }
1397 ]
1398 });
1399
1400 let errors = validate_pid_json(&json, &reqs);
1401 assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
1402 }
1403
1404 #[test]
1405 fn test_validate_missing_entity() {
1406 let reqs = sample_requirements();
1407 let json = json!({
1408 "prozessdaten": {
1409 "vorgangId": "ABC123",
1410 "transaktionsgrund": "E01"
1411 },
1412 "geschaeftspartner": [
1413 { "identifikation": "9900000000003" }
1414 ]
1415 });
1416 let errors = validate_pid_json(&json, &reqs);
1419 assert_eq!(errors.len(), 1);
1420 match &errors[0] {
1421 PidValidationError::MissingEntity {
1422 entity,
1423 ahb_status,
1424 severity,
1425 } => {
1426 assert_eq!(entity, "Marktlokation");
1427 assert_eq!(ahb_status, "Muss");
1428 assert_eq!(severity, &Severity::Error);
1429 }
1430 other => panic!("Expected MissingEntity, got: {other:?}"),
1431 }
1432
1433 let msg = errors[0].to_string();
1435 assert!(msg.contains("ERROR"));
1436 assert!(msg.contains("Marktlokation"));
1437 assert!(msg.contains("Muss"));
1438 }
1439
1440 #[test]
1441 fn test_validate_missing_field() {
1442 let reqs = sample_requirements();
1443 let json = json!({
1444 "prozessdaten": {
1445 "transaktionsgrund": "E01"
1446 },
1448 "marktlokation": {
1449 "marktlokationsId": "51234567890",
1450 "haushaltskunde": "Z15"
1451 },
1452 "geschaeftspartner": [
1453 { "identifikation": "9900000000003" }
1454 ]
1455 });
1456
1457 let errors = validate_pid_json(&json, &reqs);
1458 assert_eq!(errors.len(), 1);
1459 match &errors[0] {
1460 PidValidationError::MissingField {
1461 entity,
1462 field,
1463 ahb_status,
1464 severity,
1465 ..
1466 } => {
1467 assert_eq!(entity, "Prozessdaten");
1468 assert_eq!(field, "vorgangId");
1469 assert_eq!(ahb_status, "X");
1470 assert_eq!(severity, &Severity::Error);
1471 }
1472 other => panic!("Expected MissingField, got: {other:?}"),
1473 }
1474
1475 let msg = errors[0].to_string();
1476 assert!(msg.contains("ERROR"));
1477 assert!(msg.contains("Prozessdaten.vorgangId"));
1478 }
1479
1480 #[test]
1481 fn test_validate_invalid_code() {
1482 let reqs = sample_requirements();
1483 let json = json!({
1484 "prozessdaten": {
1485 "vorgangId": "ABC123",
1486 "transaktionsgrund": "E01"
1487 },
1488 "marktlokation": {
1489 "marktlokationsId": "51234567890",
1490 "haushaltskunde": "Z99" },
1492 "geschaeftspartner": [
1493 { "identifikation": "9900000000003" }
1494 ]
1495 });
1496
1497 let errors = validate_pid_json(&json, &reqs);
1498 assert_eq!(errors.len(), 1);
1499 match &errors[0] {
1500 PidValidationError::InvalidCode {
1501 entity,
1502 field,
1503 value,
1504 valid_values,
1505 } => {
1506 assert_eq!(entity, "Marktlokation");
1507 assert_eq!(field, "haushaltskunde");
1508 assert_eq!(value, "Z99");
1509 assert_eq!(valid_values.len(), 2);
1510 assert!(valid_values.iter().any(|(c, _)| c == "Z15"));
1511 assert!(valid_values.iter().any(|(c, _)| c == "Z18"));
1512 }
1513 other => panic!("Expected InvalidCode, got: {other:?}"),
1514 }
1515
1516 let msg = errors[0].to_string();
1517 assert!(msg.contains("INVALID"));
1518 assert!(msg.contains("Z99"));
1519 assert!(msg.contains("Z15"));
1520 }
1521
1522 #[test]
1523 fn test_validate_array_entity() {
1524 let reqs = sample_requirements();
1525 let json = json!({
1526 "prozessdaten": {
1527 "vorgangId": "ABC123",
1528 "transaktionsgrund": "E01"
1529 },
1530 "marktlokation": {
1531 "marktlokationsId": "51234567890",
1532 "haushaltskunde": "Z15"
1533 },
1534 "geschaeftspartner": [
1535 { "identifikation": "9900000000003" },
1536 { } ]
1538 });
1539
1540 let errors = validate_pid_json(&json, &reqs);
1541 assert_eq!(errors.len(), 1);
1542 match &errors[0] {
1543 PidValidationError::MissingField { entity, field, .. } => {
1544 assert_eq!(entity, "Geschaeftspartner");
1545 assert_eq!(field, "identifikation");
1546 }
1547 other => panic!("Expected MissingField, got: {other:?}"),
1548 }
1549 }
1550
1551 #[test]
1552 fn test_to_camel_case() {
1553 assert_eq!(to_camel_case("Prozessdaten"), "prozessdaten");
1554 assert_eq!(
1555 to_camel_case("RuhendeMarktlokation"),
1556 "ruhendeMarktlokation"
1557 );
1558 assert_eq!(to_camel_case("Marktlokation"), "marktlokation");
1559 assert_eq!(to_camel_case(""), "");
1560 }
1561
1562 #[test]
1563 fn test_snake_to_camel_case() {
1564 assert_eq!(snake_to_camel_case("code_codepflege"), "codeCodepflege");
1565 assert_eq!(snake_to_camel_case("vorgang_id"), "vorgangId");
1566 assert_eq!(snake_to_camel_case("marktlokation"), "marktlokation");
1567 assert_eq!(snake_to_camel_case(""), "");
1568 assert_eq!(snake_to_camel_case("a_b_c"), "aBC");
1569 }
1570
1571 #[test]
1574 fn test_camel_case_fallback_for_snake_case_bo4e_name() {
1575 let reqs = PidRequirements {
1576 transaktion_wiederholbar: false,
1577 pid: "55077".to_string(),
1578 beschreibung: "Test camelCase fallback".to_string(),
1579 entities: vec![EntityRequirement {
1580 entity: "Zuordnung".to_string(),
1581 ref_type: Bo4eRefType::Object {
1582 type_name: "Zuordnung".to_string(),
1583
1584 cardinality: Cardinality::REQUIRED,
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![
1593 FieldRequirement {
1594 bo4e_name: "code_codepflege".to_string(),
1596 ahb_status: "X".to_string(),
1597 field_type: "data".to_string(),
1598 format: None,
1599 enum_name: None,
1600 free_data_codes: Vec::new(),
1601 element_status: String::new(),
1602 segment: None,
1603 valid_codes: vec![],
1604 ref_type: Bo4eRefType::Unknown,
1605 },
1606 FieldRequirement {
1607 bo4e_name: "codeliste".to_string(),
1608 ahb_status: "X".to_string(),
1609 field_type: "data".to_string(),
1610 format: None,
1611 enum_name: None,
1612 free_data_codes: Vec::new(),
1613 element_status: String::new(),
1614 segment: None,
1615 valid_codes: vec![],
1616 ref_type: Bo4eRefType::Unknown,
1617 },
1618 ],
1619 nested: Vec::new(),
1620 }],
1621 };
1622
1623 let json_camel = json!({
1626 "zuordnung": {
1627 "codeCodepflege": "DE_BDEW",
1628 "codeliste": "6"
1629 }
1630 });
1631
1632 let errors = validate_pid_json(&json_camel, &reqs);
1633 assert!(
1634 errors.is_empty(),
1635 "Expected no errors when field is present under camelCase key, got: {errors:?}"
1636 );
1637
1638 let json_snake = json!({
1640 "zuordnung": {
1641 "code_codepflege": "DE_BDEW",
1642 "codeliste": "6"
1643 }
1644 });
1645
1646 let errors = validate_pid_json(&json_snake, &reqs);
1647 assert!(
1648 errors.is_empty(),
1649 "Expected no errors when field is present under snake_case key, got: {errors:?}"
1650 );
1651
1652 let json_missing = json!({
1654 "zuordnung": {
1655 "codeliste": "6"
1656 }
1657 });
1658
1659 let errors = validate_pid_json(&json_missing, &reqs);
1660 assert_eq!(errors.len(), 1);
1661 match &errors[0] {
1662 PidValidationError::MissingField { field, .. } => {
1663 assert_eq!(field, "code_codepflege");
1664 }
1665 other => panic!("Expected MissingField, got: {other:?}"),
1666 }
1667 }
1668
1669 #[test]
1670 fn test_is_unconditionally_required() {
1671 assert!(is_unconditionally_required("X"));
1672 assert!(is_unconditionally_required("Muss"));
1673 assert!(is_unconditionally_required("Soll"));
1674 assert!(!is_unconditionally_required("Kann"));
1675 assert!(!is_unconditionally_required("[1]"));
1676 assert!(!is_unconditionally_required(""));
1677 }
1678
1679 #[test]
1680 fn test_validation_report_display() {
1681 let errors = vec![
1682 PidValidationError::MissingEntity {
1683 entity: "Marktlokation".to_string(),
1684 ahb_status: "Muss".to_string(),
1685 severity: Severity::Error,
1686 },
1687 PidValidationError::MissingField {
1688 entity: "Prozessdaten".to_string(),
1689 field: "vorgangId".to_string(),
1690 ahb_status: "X".to_string(),
1691 rust_type: None,
1692 valid_values: vec![],
1693 severity: Severity::Error,
1694 },
1695 ];
1696 let report = ValidationReport(errors);
1697 assert!(report.has_errors());
1698 assert_eq!(report.len(), 2);
1699 assert!(!report.is_empty());
1700
1701 let display = report.to_string();
1702 assert!(display.contains("missing entity 'Marktlokation'"));
1703 assert!(display.contains("missing Prozessdaten.vorgangId"));
1704 }
1705
1706 #[test]
1707 fn test_missing_field_with_type_and_values_display() {
1708 let err = PidValidationError::MissingField {
1709 entity: "Marktlokation".to_string(),
1710 field: "haushaltskunde".to_string(),
1711 ahb_status: "Muss".to_string(),
1712 rust_type: Some("Haushaltskunde".to_string()),
1713 valid_values: vec![
1714 ("Z15".to_string(), "Ja".to_string()),
1715 ("Z18".to_string(), "Nein".to_string()),
1716 ],
1717 severity: Severity::Error,
1718 };
1719 let msg = err.to_string();
1720 assert!(msg.contains("type: Haushaltskunde"));
1721 assert!(msg.contains("valid: Z15 (Ja), Z18 (Nein)"));
1722 }
1723
1724 #[test]
1725 fn test_optional_fields_not_flagged() {
1726 let reqs = PidRequirements {
1727 transaktion_wiederholbar: false,
1728 pid: "99999".to_string(),
1729 beschreibung: "Test".to_string(),
1730 entities: vec![EntityRequirement {
1731 entity: "Test".to_string(),
1732 ref_type: Bo4eRefType::Object {
1733 type_name: "Test".to_string(),
1734
1735 cardinality: Cardinality::OPTIONAL,
1736 },
1737
1738 ahb_status: "Kann".to_string(),
1739 map_key: None,
1740 scope: EntityScope::Transaction,
1741 variants: vec![],
1742 groups: vec![],
1743 fields: vec![FieldRequirement {
1744 bo4e_name: "optionalField".to_string(),
1745 ahb_status: "Kann".to_string(),
1746 field_type: "data".to_string(),
1747 format: None,
1748 enum_name: None,
1749 free_data_codes: Vec::new(),
1750 element_status: String::new(),
1751 segment: None,
1752 valid_codes: vec![],
1753 ref_type: Bo4eRefType::Unknown,
1754 }],
1755 nested: Vec::new(),
1756 }],
1757 };
1758
1759 let errors = validate_pid_json(&json!({}), &reqs);
1761 assert!(errors.is_empty());
1762
1763 let errors = validate_pid_json(&json!({ "test": {} }), &reqs);
1765 assert!(errors.is_empty());
1766 }
1767
1768 #[test]
1771 fn test_nested_dot_path_fields_not_falsely_missing() {
1772 let reqs = PidRequirements {
1773 transaktion_wiederholbar: false,
1774 pid: "55001".to_string(),
1775 beschreibung: "Test nested paths".to_string(),
1776 entities: vec![EntityRequirement {
1777 entity: "ProduktpaketDaten".to_string(),
1778 ref_type: Bo4eRefType::Object {
1779 type_name: "ProduktpaketDaten".to_string(),
1780
1781 cardinality: Cardinality {
1782 min: 1,
1783 max: Some(99999),
1784 },
1785 },
1786
1787 ahb_status: "Muss".to_string(),
1788 map_key: None,
1789 scope: EntityScope::Transaction,
1790 variants: vec![],
1791 groups: vec![],
1792 fields: vec![
1793 FieldRequirement {
1794 bo4e_name: "produktIdentifikation.funktion".to_string(),
1795 ahb_status: "X".to_string(),
1796 field_type: "code".to_string(),
1797 format: None,
1798 enum_name: Some("Produktidentifikation".to_string()),
1799 free_data_codes: Vec::new(),
1800 element_status: String::new(),
1801 segment: None,
1802 valid_codes: vec![CodeValue {
1803 code: "5".to_string(),
1804 meaning: "Produktidentifikation".to_string(),
1805 enum_name: None,
1806 bo4e_value: None,
1807 ahb_status: None,
1808 }],
1809 ref_type: Bo4eRefType::Unknown,
1810 },
1811 FieldRequirement {
1812 bo4e_name: "produktMerkmal.code".to_string(),
1813 ahb_status: "X".to_string(),
1814 field_type: "code".to_string(),
1815 format: None,
1816 enum_name: None,
1817 free_data_codes: Vec::new(),
1818 element_status: String::new(),
1819 segment: None,
1820 valid_codes: vec![],
1821 ref_type: Bo4eRefType::Unknown,
1822 },
1823 ],
1824 nested: Vec::new(),
1825 }],
1826 };
1827
1828 let json = json!({
1830 "produktpaketDaten": [{
1831 "produktIdentifikation": { "funktion": "5", "id": "9991000002082", "typ": "Z11" },
1832 "produktMerkmal": { "code": "ZH9" }
1833 }]
1834 });
1835
1836 let errors = validate_pid_json(&json, &reqs);
1837 assert!(
1838 errors.is_empty(),
1839 "Nested dot-path fields should be found (issue #48), got: {errors:?}"
1840 );
1841 }
1842
1843 #[test]
1844 fn test_nested_dot_path_truly_missing() {
1845 let reqs = PidRequirements {
1846 transaktion_wiederholbar: false,
1847 pid: "55001".to_string(),
1848 beschreibung: "Test nested paths missing".to_string(),
1849 entities: vec![EntityRequirement {
1850 entity: "ProduktpaketDaten".to_string(),
1851 ref_type: Bo4eRefType::Object {
1852 type_name: "ProduktpaketDaten".to_string(),
1853
1854 cardinality: Cardinality {
1855 min: 1,
1856 max: Some(99999),
1857 },
1858 },
1859
1860 ahb_status: "Muss".to_string(),
1861 map_key: None,
1862 scope: EntityScope::Transaction,
1863 variants: vec![],
1864 groups: vec![],
1865 fields: vec![FieldRequirement {
1866 bo4e_name: "produktIdentifikation.funktion".to_string(),
1867 ahb_status: "X".to_string(),
1868 field_type: "data".to_string(),
1869 format: None,
1870 enum_name: None,
1871 free_data_codes: Vec::new(),
1872 element_status: String::new(),
1873 segment: None,
1874 valid_codes: vec![],
1875 ref_type: Bo4eRefType::Unknown,
1876 }],
1877 nested: Vec::new(),
1878 }],
1879 };
1880
1881 let json = json!({
1883 "produktpaketDaten": [{
1884 "produktIdentifikation": { "id": "123" }
1885 }]
1886 });
1887
1888 let errors = validate_pid_json(&json, &reqs);
1889 assert_eq!(errors.len(), 1, "Should report missing nested field");
1890 match &errors[0] {
1891 PidValidationError::MissingField { field, .. } => {
1892 assert_eq!(field, "produktIdentifikation.funktion");
1893 }
1894 other => panic!("Expected MissingField, got: {other:?}"),
1895 }
1896 }
1897
1898 fn field(name: &str, status: &str, codes: &[(&str, &str)]) -> FieldRequirement {
1899 FieldRequirement {
1900 bo4e_name: name.to_string(),
1901 ahb_status: status.to_string(),
1902 field_type: if codes.is_empty() { "data" } else { "code" }.to_string(),
1903 format: None,
1904 enum_name: None,
1905 free_data_codes: Vec::new(),
1906 element_status: String::new(),
1907 segment: None,
1908 valid_codes: codes
1909 .iter()
1910 .map(|(code, mapped)| CodeValue {
1911 code: code.to_string(),
1912 meaning: String::new(),
1913 enum_name: None,
1914 bo4e_value: Some(mapped.to_string()),
1915 ahb_status: None,
1916 })
1917 .collect(),
1918 ref_type: Bo4eRefType::Unknown,
1919 }
1920 }
1921
1922 fn multi_variant_requirements() -> PidRequirements {
1925 let z03 = ("Z03", "messlokationsadresse");
1926 let z07 = ("Z07", "kundeMsb");
1927 PidRequirements {
1928 transaktion_wiederholbar: false,
1929 pid: "55042".to_string(),
1930 beschreibung: String::new(),
1931 entities: vec![EntityRequirement {
1932 entity: "Geschaeftspartner".to_string(),
1933 ref_type: Bo4eRefType::Object {
1934 type_name: "Geschaeftspartner".to_string(),
1935 cardinality: Cardinality {
1936 min: 1,
1937 max: Some(99),
1938 },
1939 },
1940 ahb_status: "Muss".to_string(),
1941 fields: vec![
1943 field("adresse.ort", "X", &[]),
1944 field("name1", "X", &[]),
1945 field("partnerrolle", "X", &[z03, z07]),
1946 ],
1947 map_key: None,
1948 scope: EntityScope::Transaction,
1949 variants: vec![
1950 EntityVariantRequirement {
1951 discriminator_field: "partnerrolle".to_string(),
1952 code: "Z03".to_string(),
1953 bo4e_value: Some("messlokationsadresse".to_string()),
1954 source_paths: vec!["sg4.sg12_z03".to_string()],
1955 fields: vec![
1956 field("adresse.ort", "X", &[]),
1957 field("partnerrolle", "X", &[z03]),
1958 ],
1959 ahb_status: String::new(),
1960 },
1961 EntityVariantRequirement {
1962 discriminator_field: "partnerrolle".to_string(),
1963 code: "Z07".to_string(),
1964 bo4e_value: Some("kundeMsb".to_string()),
1965 source_paths: vec!["sg4.sg12_z07".to_string()],
1966 fields: vec![field("name1", "X", &[]), field("partnerrolle", "X", &[z07])],
1967 ahb_status: String::new(),
1968 },
1969 ],
1970 groups: vec![],
1971 nested: Vec::new(),
1972 }],
1973 }
1974 }
1975
1976 fn multi_group_requirements(z22_status: &str) -> PidRequirements {
1978 let group = |path: &str, status: &str, fields: &[&str]| EntityGroupRequirement {
1979 source_path: path.to_string(),
1980 ahb_status: status.to_string(),
1981 fields: fields.iter().map(|f| f.to_string()).collect(),
1982 };
1983 PidRequirements {
1984 transaktion_wiederholbar: false,
1985 pid: "55043".to_string(),
1986 beschreibung: String::new(),
1987 entities: vec![EntityRequirement {
1988 entity: "Marktlokation".to_string(),
1989 ref_type: Bo4eRefType::Object {
1990 type_name: "Marktlokation".to_string(),
1991 cardinality: Cardinality::REQUIRED,
1992 },
1993 ahb_status: "Muss".to_string(),
1994 fields: vec![
1995 field("marktlokationsId", "X", &[]),
1996 field("ruhendeMarktlokationsId", "X", &[]),
1997 field("ruhendeMarktlokationZeitraumId", "Kann", &[]),
1998 ],
1999 map_key: None,
2000 scope: EntityScope::Transaction,
2001 variants: vec![],
2002 groups: vec![
2003 group("sg4.sg5_z16", "Muss", &["marktlokationsId"]),
2004 group(
2005 "sg4.sg5_z22",
2006 z22_status,
2007 &["ruhendeMarktlokationsId", "ruhendeMarktlokationZeitraumId"],
2008 ),
2009 ],
2010 nested: Vec::new(),
2011 }],
2012 }
2013 }
2014
2015 fn missing_fields(errors: &[PidValidationError]) -> Vec<&str> {
2016 errors
2017 .iter()
2018 .filter_map(|e| match e {
2019 PidValidationError::MissingField { field, .. } => Some(field.as_str()),
2020 _ => None,
2021 })
2022 .collect()
2023 }
2024
2025 #[test]
2026 fn an_absent_optional_groups_fields_are_not_demanded() {
2027 let reqs = multi_group_requirements("Soll [2003]");
2028 let errors = validate_pid_json(&json!({ "marktlokation": {} }), &reqs);
2029 assert_eq!(missing_fields(&errors), vec!["marktlokationsId"]);
2031 }
2032
2033 #[test]
2034 fn a_filled_groups_fields_are_demanded() {
2035 let reqs = multi_group_requirements("Soll [2003]");
2036 let json = json!({ "marktlokation": {
2037 "marktlokationsId": "51238696781",
2038 "ruhendeMarktlokationZeitraumId": "1"
2039 }});
2040 let errors = validate_pid_json(&json, &reqs);
2041 assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
2042 }
2043
2044 #[test]
2045 fn an_absent_required_groups_fields_are_demanded() {
2046 let reqs = multi_group_requirements("Muss");
2047 let json = json!({ "marktlokation": { "marktlokationsId": "51238696781" } });
2048 let errors = validate_pid_json(&json, &reqs);
2049 assert_eq!(missing_fields(&errors), vec!["ruhendeMarktlokationsId"]);
2050 }
2051
2052 #[test]
2053 fn multi_variant_entity_uses_the_elements_own_variant() {
2054 let reqs = multi_variant_requirements();
2055 let json = json!({
2057 "geschaeftspartner": [
2058 { "partnerrolle": "Z03", "adresse": { "ort": "Berlin" } },
2059 { "partnerrolle": "kundeMsb", "name1": "Muster" },
2060 { "partnerrolle": { "code": "messlokationsadresse", "meaning": "x" },
2061 "adresse": { "ort": "Köln" } },
2062 { "partnerrolle": { "code": "Z07" }, "name1": "Beispiel" },
2063 ]
2064 });
2065 let errors = validate_pid_json(&json, &reqs);
2066 assert!(errors.is_empty(), "{}", ValidationReport(errors));
2067 }
2068
2069 #[test]
2070 fn multi_variant_entity_reports_variant_required_fields() {
2071 let reqs = multi_variant_requirements();
2072 let json = json!({ "geschaeftspartner": [{ "partnerrolle": "kundeMsb" }] });
2073 let errors = validate_pid_json(&json, &reqs);
2074 assert_eq!(errors.len(), 1, "{}", ValidationReport(errors));
2075 assert!(matches!(
2076 &errors[0],
2077 PidValidationError::MissingField { field, .. } if field == "name1"
2078 ));
2079 }
2080
2081 #[test]
2082 fn multi_variant_entity_unknown_qualifier_is_invalid_code_only() {
2083 let reqs = multi_variant_requirements();
2084 for bad in [json!("Z99"), json!("bogus"), json!({ "code": "Z99" })] {
2085 let json = json!({ "geschaeftspartner": [{ "partnerrolle": bad }] });
2086 let errors = validate_pid_json(&json, &reqs);
2087 assert_eq!(errors.len(), 1, "{bad}: {}", ValidationReport(errors));
2089 match &errors[0] {
2090 PidValidationError::InvalidCode {
2091 field,
2092 valid_values,
2093 ..
2094 } => {
2095 assert_eq!(field, "partnerrolle");
2096 let codes: Vec<&str> = valid_values.iter().map(|(c, _)| c.as_str()).collect();
2097 assert_eq!(codes, ["Z03", "Z07"]);
2098 }
2099 other => panic!("expected InvalidCode, got {other:?}"),
2100 }
2101 }
2102 }
2103
2104 #[test]
2105 fn code_objects_and_enum_mapped_names_are_code_checked() {
2106 let f = field("partnerrolle", "X", &[("Z07", "kundeMsb")]);
2107 assert_eq!(invalid_code_value(&json!("Z07"), &f), None);
2108 assert_eq!(invalid_code_value(&json!("kundeMsb"), &f), None);
2109 assert_eq!(invalid_code_value(&json!({ "code": "kundeMsb" }), &f), None);
2110 assert_eq!(invalid_code_value(&json!({ "code": "Z07" }), &f), None);
2111 assert_eq!(
2112 invalid_code_value(&json!({ "code": "Z99", "meaning": null }), &f),
2113 Some("Z99".to_string())
2114 );
2115 assert_eq!(
2116 invalid_code_value(&json!("kundeLf"), &f),
2117 Some("kundeLf".to_string())
2118 );
2119 assert_eq!(invalid_code_value(&json!(7), &f), None);
2121 assert_eq!(invalid_code_value(&json!({ "meaning": "x" }), &f), None);
2122 }
2123}