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