edifact 0.20.0

EDIFACT (ISO 9735) for Rust: zero-copy parser, envelope-computing writer, typed derive, layered validation, DTM dates and CONTRL
Documentation
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
//! Integration tests for group-scoped validation.
//!
//! These tests verify that [`ProfileRulePack`] group rules:
//! - Only fire for the group they are scoped to.
//! - Do **not** cross-fire when the same segment tag appears in a different group.
//! - Correctly auto-stamp `ValidationIssue::segment_group`.
//! - Work through [`ValidationContext::validate_grouped`], for segments from
//!   either parsing path.
//! - Honour `max_issues_per_rule` across the whole tree walk, not per group.

use edifact::{
    ProfileRulePack, ValidationContext, ValidationIssue, ValidationSeverity,
    group::{GroupDef, group_segments_indexed},
};

// ── Schema shared across tests ────────────────────────────────────────────────

/// Minimal multi-level schema:
///
/// ```text
/// ROOT
///   SG1 (trigger: RFF) — reference group
///     (no children)
///   SG5 (trigger: LOC) — location group
///     SG6 (trigger: QTY) — quantity sub-group
/// ```
static SG6: &[GroupDef] = &[GroupDef::new("SG6", "QTY")];
static SCHEMA: &[GroupDef] = &[
    GroupDef::new("SG1", "RFF"),
    GroupDef::with_children("SG5", "LOC", SG6),
];

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Parse ASCII EDIFACT snippet into owned segments.
fn owned_segs(input: &[u8]) -> Vec<edifact::OwnedSegment> {
    edifact::from_reader(std::io::Cursor::new(input))
        .collect::<Result<_, _>>()
        .expect("fixture should parse")
}

/// Parse ASCII EDIFACT snippet into borrowed segments (from a String so we own the buffer).
fn parse_segs(input: &str) -> Vec<edifact::Segment<'static>> {
    // Leak the string so we get 'static lifetime — acceptable in tests only.
    let s: &'static str = Box::leak(input.to_owned().into_boxed_str());
    edifact::from_bytes(s.as_bytes())
        .collect::<Result<_, _>>()
        .expect("fixture should parse")
}

// ── group rule fires only for the scoped group ───────────────────────────────

/// A rule scoped to "SG5" DOES fire when DTM is absent from SG5, even though it
/// appears in SG1. Cross-group contamination must not suppress the missing-segment
/// error for SG5.
#[test]
fn group_rule_fires_when_required_segment_absent_from_scoped_group() {
    // DTM is in SG1 (after RFF), not in SG5 (LOC).  Rule: DTM must be in SG5.
    let input = "UNH+1+ORDERS:D:04B:UN'RFF+Z13:REF1'DTM+137:20230101:102'LOC+172+LOC1'UNT+5+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    // DTM is present in SG1 but NOT in SG5, so the rule should fire.
    assert!(
        report.has_errors(),
        "expected error: DTM missing from SG5 — got: {report}"
    );
    let issue = report.errors().first().expect("at least one error");
    assert_eq!(issue.segment_group.as_deref(), Some("SG5"));
    assert_eq!(issue.rule_id.as_deref(), Some("SG5-DTM-M"));
}

/// A rule scoped to "SG5" must NOT fire when DTM is present in SG5.
#[test]
fn group_rule_does_not_fire_when_segment_present_in_scoped_group() {
    // DTM inside SG5 (after LOC).
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+LOC1'DTM+137:20230101:102'UNT+3+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    assert!(
        report.is_valid(),
        "expected no errors (DTM is present in SG5): {report}"
    );
}

// ── forbid_segment_in_group ──────────────────────────────────────────────────

#[test]
fn forbid_segment_in_group_fires_when_segment_present() {
    // UNS must not appear in SG5.
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+LOC1'UNS+D'UNT+3+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").forbid_segment_in_group("SG5", "UNS", "SG5-UNS-F");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    assert!(report.has_errors(), "expected error: UNS in SG5 — {report}");
    let issue = report.errors().first().unwrap();
    assert_eq!(issue.segment_group.as_deref(), Some("SG5"));
}

#[test]
fn forbid_segment_in_group_does_not_fire_when_segment_absent() {
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+LOC1'DTM+137:20230101:102'UNT+3+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").forbid_segment_in_group("SG5", "UNS", "SG5-UNS-F");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    assert!(ctx.validate_grouped(&tree, &segs).is_valid());
}

// ── cross-group non-contamination ────────────────────────────────────────────

/// The same segment tag in two different groups must produce independent issues:
/// a rule on SG5/DTM must not mark the SG1/DTM occurrence and vice-versa.
#[test]
fn group_rules_for_different_groups_do_not_cross_contaminate() {
    // DTM in SG1 (after RFF) but not in SG5 (after LOC), and QTY in SG6 (after QTY trigger).
    let input =
        "UNH+1+ORDERS:D:04B:UN'RFF+Z13:R1'DTM+137:20230101:102'LOC+172+L1'QTY+220:100'UNT+5+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    // SG1 rule: require DTM (present → no error)
    // SG5 rule: require DTM (absent in SG5 → error)
    let pack = ProfileRulePack::new("TEST")
        .require_segment_in_group("SG1", "DTM", "SG1-DTM-M")
        .require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    // Exactly one error (SG5 missing DTM), not two.
    assert_eq!(report.errors().len(), 1, "expected 1 error; got {report}");
    assert_eq!(
        report.errors()[0].rule_id.as_deref(),
        Some("SG5-DTM-M"),
        "the error must be for SG5, not SG1"
    );
}

// ── segment_group auto-stamped ───────────────────────────────────────────────

#[test]
fn group_rule_issues_are_auto_stamped_with_group_name() {
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+L1'UNT+2+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").require_segment_in_group("SG5", "QTY", "SG5-QTY-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    assert!(report.has_errors());
    // Auto-stamp: segment_group must equal the group definition name.
    for issue in report.errors() {
        assert_eq!(
            issue.segment_group.as_deref(),
            Some("SG5"),
            "issue must be auto-stamped with SG5"
        );
    }
}

// ── validate_lenient_grouped_owned ───────────────────────────────────────────

#[test]
fn validate_lenient_grouped_owned_works_with_owned_segments() {
    let input = b"UNH+1+ORDERS:D:04B:UN'LOC+172+L1'DTM+137:20230101:102'UNT+3+1'";
    let owned = owned_segs(input);
    let tree = group_segments_indexed(&owned, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &owned);
    assert!(
        report.is_valid(),
        "DTM present in SG5 — no errors expected: {report}"
    );
}

// ── multiple group occurrences (repetition) ──────────────────────────────────

/// When SG5 repeats, the rule fires per-occurrence.
#[test]
fn group_rule_fires_per_occurrence_when_group_repeats() {
    // Two SG5 groups: first has DTM, second does not.
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+L1'DTM+137:20230101:102'LOC+172+L2'UNT+4+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    // One SG5 is missing DTM → exactly one error.
    assert_eq!(
        report.errors().len(),
        1,
        "exactly one SG5 missing DTM: {report}"
    );
}

// ── with_scoped_group_rule_fn custom closure ─────────────────────────────────

#[test]
fn custom_scoped_group_rule_fn_fires_and_sets_segment_group() {
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+L1'QTY+220:0'UNT+3+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST").with_scoped_group_rule_fn(
        "SG6",
        "SG6-QTY-NONZERO",
        |_group, group_segs, _ctx, issues| {
            for s in group_segs.iter().filter(|s| s.tag == "QTY") {
                let qty_val = s
                    .get_element(0)
                    .and_then(|e| e.get_component(1))
                    .unwrap_or("0");
                if qty_val == "0" {
                    issues.push(
                        ValidationIssue::new(
                            ValidationSeverity::Warning,
                            "QTY value is zero in SG6",
                        )
                        .with_segment("QTY")
                        .with_rule_id("SG6-QTY-NONZERO"),
                    );
                }
            }
        },
    );
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    assert!(!report.warnings().is_empty(), "expected zero-qty warning");
    assert_eq!(
        report.warnings()[0].segment_group.as_deref(),
        Some("SG6"),
        "warning must be auto-stamped with SG6"
    );
}

// ── message-type scoping works with group rules ──────────────────────────────

#[test]
fn group_rules_respect_message_type_scoping() {
    // Pack scoped to ORDERS; message is INVOIC → no group rules should fire.
    let input = "UNH+1+INVOIC:D:96A:UN'LOC+172+L1'UNT+2+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("ORDERS-ONLY")
        .for_message_type("ORDERS")
        .require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    assert!(
        report.is_valid(),
        "INVOIC message: ORDERS-scoped group rules must not fire: {report}"
    );
}

// ── flat + group phases both run ─────────────────────────────────────────────

#[test]
fn flat_and_group_validation_both_run_in_grouped_mode() {
    // Flat rule: BGM must be present (it's absent).
    // Group rule: DTM must be in SG5 (also absent).
    let input = "UNH+1+ORDERS:D:04B:UN'LOC+172+L1'UNT+2+1'";
    let segs = parse_segs(input);
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("TEST")
        .require_segment("BGM", "BGM-M")
        .require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);
    // Both a flat error and a group error should appear.
    let rule_ids: Vec<Option<&str>> = report
        .errors()
        .iter()
        .map(|i| i.rule_id.as_deref())
        .collect();
    assert!(
        rule_ids.contains(&Some("BGM-M")),
        "flat rule BGM-M must fire: {report}"
    );
    assert!(
        rule_ids.contains(&Some("SG5-DTM-M")),
        "group rule SG5-DTM-M must fire: {report}"
    );
}

// ── segment_occurrence semantics: occurrence among matching segments, not absolute ─

#[test]
fn forbid_segment_segment_occurrence_is_relative_not_absolute() {
    // Three QTY segments at absolute positions 1, 2, 3 in the message.
    // forbid_segment fires for each; occurrences must be 0, 1, 2 (relative).
    let segs = parse_segs("UNH+1+ORDERS:D:96A:UN'QTY+21:10'QTY+21:20'QTY+21:30'UNT+4+1'");
    let pack = ProfileRulePack::new("TEST").forbid_segment("QTY", "TEST-FORBID-QTY");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();
    let report = ctx.validate(&segs);
    let mut occurrences: Vec<u32> = report
        .errors()
        .iter()
        .filter_map(|i| i.segment_occurrence)
        .collect();
    occurrences.sort_unstable();
    assert_eq!(
        occurrences,
        vec![0, 1, 2],
        "segment_occurrence must be 0-based relative to matching segments, not absolute positions"
    );
}

#[test]
fn forbid_segment_in_group_occurrence_is_relative_not_absolute() {
    // SG5 group (trigger: LOC) with two QTY segments at positions 1 and 2 within the group.
    // LOC is at absolute 0 within the group slice; occurrences for QTY must be 0 and 1.
    let segs = parse_segs("UNH+1+ORDERS:D:04B:UN'LOC+172+L1'QTY+21:10'QTY+21:20'UNT+4+1'");
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");
    let pack = ProfileRulePack::new("TEST").forbid_segment_in_group("SG5", "QTY", "TEST-SG5-QTY");
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();
    let report = ctx.validate_grouped(&tree, &segs);
    let mut occurrences: Vec<u32> = report
        .errors()
        .iter()
        .filter_map(|i| i.segment_occurrence)
        .collect();
    occurrences.sort_unstable();
    assert_eq!(
        occurrences,
        vec![0, 1],
        "segment_occurrence in group must count only matching segments, not absolute group slice position"
    );
}

// ── bail_on_first_error: child traversal must not stop on pre-existing errors ─

#[test]
fn bail_on_first_error_does_not_skip_sibling_groups_due_to_earlier_flat_errors() {
    // Two SG5 groups (LOC+L1 and LOC+L2), each missing DTM.
    // The flat pass also fires an error (BGM missing).
    // With bail_on_first_error the group pass should stop after the FIRST group
    // error it introduces — not skip all group rules because the flat pass
    // already put errors in the report before the group pass started.
    let segs = parse_segs(
        "UNH+1+ORDERS:D:04B:UN'\
         LOC+172+L1'LOC+172+L2'UNT+3+1'",
    );
    let tree = group_segments_indexed(&segs, SCHEMA, "ROOT");

    // A pack with bail_on_first_error that requires DTM in every SG5.
    // Also require BGM (flat) — this fires first and puts an error in the report.
    let pack = ProfileRulePack::new("TEST")
        .require_segment("BGM", "BGM-M")
        .require_segment_in_group("SG5", "DTM", "SG5-DTM-M")
        .with_bail_on_first_error(true);
    let ctx = ValidationContext::builder().with_profile_pack(pack).build();

    let report = ctx.validate_grouped(&tree, &segs);

    // We must have at least the flat BGM error AND at least one group error.
    // (bail_on_first_error stops after the first group error from THIS pass,
    // not because the flat pass already populated errors.)
    assert!(report.has_errors(), "expected errors in report: {report}");
    let rule_ids: Vec<&str> = report
        .errors()
        .iter()
        .filter_map(|i| i.rule_id.as_deref())
        .collect();
    assert!(
        rule_ids.contains(&"BGM-M"),
        "flat error BGM-M must be present: {report}"
    );
    assert!(
        rule_ids.contains(&"SG5-DTM-M"),
        "group error SG5-DTM-M must not be skipped by pre-existing flat errors: {report}"
    );
}

// ── Runtime-loaded schemas ────────────────────────────────────────────────────

/// A MIG loaded at startup cannot produce `&'static str`. The builder owns its
/// strings (shared behind `Arc`), so a run-time schema needs neither a
/// borrowed arena nor `Box::leak`.
#[test]
fn a_schema_built_at_runtime_groups_identically_to_a_static_one() {
    // Stand-in for names parsed out of a MIG file at startup.
    let names: Vec<String> = vec![
        "SG1".to_owned(),
        "RFF".to_owned(),
        "SG5".to_owned(),
        "LOC".to_owned(),
        "SG6".to_owned(),
        "QTY".to_owned(),
    ];
    let owned =
        |name: &str, trigger: &str| GroupDef::builder(name, edifact::SegmentPlace::owned(trigger));
    let runtime_schema = vec![
        owned(&names[0], &names[1]).build().expect("valid group"),
        owned(&names[2], &names[3])
            .group(owned(&names[4], &names[5]).build().expect("valid group"))
            .build()
            .expect("valid group"),
    ];
    drop(names);

    let input =
        b"UNH+1+ORDERS:D:96A:UN'RFF+ON:1'LOC+172+DE1'DTM+163:20260101:102'QTY+220:5'UNT+6+1'";
    let segs: Vec<_> = edifact::from_bytes(input)
        .collect::<Result<Vec<_>, _>>()
        .expect("parse");

    let from_static = group_segments_indexed(&segs, SCHEMA, "ROOT");
    let from_runtime = group_segments_indexed(&segs, &runtime_schema, "ROOT");

    fn shape(g: &edifact::SegmentGroupIndexed<'_>) -> Vec<(String, std::ops::Range<usize>)> {
        let mut out = vec![(g.definition.to_owned(), g.total_span.clone())];
        for child in &g.children {
            out.extend(shape(child));
        }
        out
    }
    assert_eq!(shape(&from_static), shape(&from_runtime));
    assert!(shape(&from_runtime).iter().any(|(n, _)| n == "SG6"));
}

/// `max_issues_per_rule` documents itself as applying "per rule per call".
///
/// The group walk applied it per rule per *group occurrence*, so a rule firing
/// in twenty groups emitted twenty times the cap — and a group rule is the most
/// likely to flood a report, which is the case the cap exists for.
#[test]
fn max_issues_per_rule_caps_a_group_rule_across_the_whole_tree() {
    // Twenty SG1 occurrences, each triggering the rule once.
    let mut input = String::from("UNH+1+ORDERS:D:96A:UN'");
    for i in 0..20 {
        input.push_str(&format!("RFF+ON:{i}'"));
    }
    input.push_str("UNT+22+1'");
    let segments = parse_segs(&input);
    let tree = group_segments_indexed(&segments, SCHEMA, "ROOT");

    let pack = ProfileRulePack::new("CAP")
        .with_max_issues_per_rule(3)
        .with_scoped_group_rule_fn("SG1", "CAP-SG1", |_group, _segs, _ctx, issues| {
            issues.push(ValidationIssue::new(
                ValidationSeverity::Error,
                "one issue per SG1 occurrence",
            ));
        });

    let report = ValidationContext::builder()
        .with_profile_pack(pack)
        .build()
        .validate_grouped(&tree, &segments);

    assert_eq!(
        report.total_issues(),
        3,
        "the cap is per rule per call, so twenty group occurrences must still \
         yield at most three issues, not twenty",
    );
}

/// The `UTILMD` shape: SG2 (message-level parties) and SG12 (a Vorgang's
/// parties, inside SG4) both trigger on `NAD`.
static SG12: &[GroupDef] = &[GroupDef::new("SG12", "NAD")];
static UTILMD_LIKE: &[GroupDef] = &[
    GroupDef::new("SG2", "NAD"),
    GroupDef::with_children("SG4", "IDE", SG12),
];

/// A group-scoped rule must see the group the message structure assigns, not the
/// one the traversal happened to reopen.
///
/// Before the traversal preferred a nested definition over an ancestor's
/// sibling, every `NAD` after the first `IDE` reopened a top-level SG2 — so an
/// SG2-scoped rule fired on a Vorgang's parties, and an SG12-scoped rule never
/// fired at all. That made a group-scoped `NAD` rule unsound on any message
/// carrying an SG12, and forced downstream profiles to express the constraint on
/// the flat `NAD` rule instead.
#[test]
fn a_group_scoped_nad_rule_fires_on_the_group_the_structure_assigns() {
    let input = "UNH+1+UTILMD:D:11A:UN'BGM+E01+1+9'                 NAD+MS+SENDER::293'NAD+MR+RECEIVER::293'                 IDE+24+VORGANG1'NAD+Z09+KUNDE::293'DTM+92:20260101:102'NAD+VY+PARTY::293'";
    let segments = parse_segs(input);
    let tree = group_segments_indexed(&segments, UTILMD_LIKE, "ROOT");

    // One rule per group, each recording the qualifiers it was shown.
    let pack = ProfileRulePack::new("UTILMD-LIKE")
        .with_scoped_group_rule_fn("SG2", "SG2-NAD", |_group, segs, _ctx, issues| {
            for qualifier in segs
                .iter()
                .filter(|s| s.tag == "NAD")
                .filter_map(|s| s.element_str(0))
            {
                issues.push(
                    ValidationIssue::new(ValidationSeverity::Info, qualifier).with_rule_id("SG2"),
                );
            }
        })
        .with_scoped_group_rule_fn("SG12", "SG12-NAD", |_group, segs, _ctx, issues| {
            for qualifier in segs
                .iter()
                .filter(|s| s.tag == "NAD")
                .filter_map(|s| s.element_str(0))
            {
                issues.push(
                    ValidationIssue::new(ValidationSeverity::Info, qualifier).with_rule_id("SG12"),
                );
            }
        });

    let report = ValidationContext::builder()
        .with_profile_pack(pack)
        .build()
        .validate_grouped(&tree, &segments);

    let seen = |rule: &str| -> Vec<String> {
        report
            .infos()
            .iter()
            .filter(|i| i.rule_id.as_deref() == Some(rule))
            .map(|i| i.message.clone())
            .collect()
    };

    assert_eq!(
        seen("SG2"),
        ["MS", "MR"],
        "SG2 sees only the message-level parties",
    );
    assert_eq!(
        seen("SG12"),
        ["Z09", "VY"],
        "SG12 sees the Vorgang's parties — and is reachable at all",
    );
}

/// The reader side of the same shape: enumerating a Vorgang's parties.
#[test]
fn every_nested_party_group_is_enumerable_from_the_tree() {
    let input = "NAD+MS+SENDER::293'                 IDE+24+V1'NAD+Z09+KUNDE::293'                 IDE+24+V2'NAD+VY+PARTY::293'NAD+DP+DELIVERY::293'";
    let segments = parse_segs(input);
    let tree = group_segments_indexed(&segments, UTILMD_LIKE, "ROOT");

    // Per Vorgang, in document order.
    let per_vorgang: Vec<Vec<&str>> = tree
        .find("SG4")
        .map(|sg4| {
            sg4.find("SG12")
                .filter_map(|sg12| sg12.segments(&segments).first())
                .filter_map(|nad| nad.element_str(0))
                .collect()
        })
        .collect();

    assert_eq!(per_vorgang, [vec!["Z09"], vec!["VY", "DP"]]);
}

// ── group occurrence paths ───────────────────────────────────────────────────

/// `ROOT > SG4#0 > SG8#0, SG8#1`, plus a second `SG4` so occurrences are
/// visibly counted per parent.
static SG8: &[GroupDef] = &[GroupDef::new("SG8", "SEQ")];
static PATH_SCHEMA: &[GroupDef] = &[GroupDef::with_children("SG4", "IDE", SG8)];

#[test]
fn group_path_is_stamped() {
    use edifact::{FindingKind, GroupPath, GroupStep};

    let segs = parse_segs(
        "UNH+1+UTILMD:D:11A:UN'BGM+E01'IDE+24+A'SEQ+Z01'SEQ+Z02'IDE+24+B'SEQ+Z01'UNT+8+1'",
    );
    let tree = group_segments_indexed(&segs, PATH_SCHEMA, "ROOT");
    let pack = ProfileRulePack::new("AHB-UTILMD")
        // Fails in every SG8: no RFF anywhere.
        .require_segment_in_group("SG8", "RFF", "SG8-RFF-M")
        // A rule that sets its own path keeps it.
        .with_scoped_group_rule_fn("SG4", "SG4-OWN-PATH", |_group, _segs, _ctx, issues| {
            issues.push(
                ValidationIssue::new(ValidationSeverity::Warning, "own path")
                    .with_group_path(GroupPath::new(GroupStep::new("CUSTOM", 7)).unwrap()),
            );
        })
        // Root-level rules get no path.
        .with_scoped_group_rule_fn("ROOT", "ROOT-RULE", |_group, _segs, _ctx, issues| {
            issues.push(ValidationIssue::new(ValidationSeverity::Info, "at root"));
        });
    let report = ValidationContext::builder()
        .with_profile_pack(pack)
        .build()
        .validate_grouped(&tree, &segs);

    let paths: Vec<String> = report
        .issues_for_rule_id("SG8-RFF-M")
        .map(|issue| {
            assert_eq!(issue.segment_group(), Some("SG8"));
            assert_eq!(issue.kind(), Some(FindingKind::Missing));
            assert_eq!(issue.pack(), Some("AHB-UTILMD"));
            issue.group_path().expect("path").to_string()
        })
        .collect();
    assert_eq!(paths, ["SG4[0]/SG8[0]", "SG4[0]/SG8[1]", "SG4[1]/SG8[0]"]);

    let own: Vec<String> = report
        .warnings()
        .iter()
        .map(|issue| issue.group_path().expect("path").to_string())
        .collect();
    assert_eq!(own, ["CUSTOM[7]", "CUSTOM[7]"]);

    let root = &report.infos()[0];
    assert_eq!(root.message, "at root");
    assert_eq!(root.group_path(), None);
    assert_eq!(root.segment_group(), Some("ROOT"));

    // The deterministic rendering shows the path with the segment tag.
    assert!(
        report
            .render_deterministic()
            .contains("[path=SG4[0]/SG8[1]/RFF]"),
        "{}",
        report.render_deterministic()
    );
}

// ── placement findings ───────────────────────────────────────────────────────

mod placement_findings {
    use super::parse_segs;
    use edifact::group::{Discriminator, Entry, GroupDef, GroupSchema, SegmentPlace};
    use edifact::{
        FindingKind, PlacementValidator, ValidationContext, ValidationIssue, ValidationLayer,
    };
    use std::sync::Arc;

    /// `UNH BGM SG4[IDE, DTM(max 1), SG5(LOC, min 1)] UNT`, ordered throughout.
    fn schema() -> GroupSchema {
        let sg5 = GroupDef::builder("SG5", SegmentPlace::new("LOC").with_id("00047"))
            .id("SG5-MALO")
            .ordered()
            .min(1)
            .max(1)
            .build()
            .unwrap();
        let sg4 = GroupDef::builder(
            "SG4",
            SegmentPlace::new("IDE").when(Discriminator::one_of(0, 0, ["24"])),
        )
        .segment(SegmentPlace::new("DTM").with_id("00020").with_max(1))
        .group(sg5)
        .build()
        .unwrap();
        GroupSchema::ordered(
            "UTILMD",
            [
                Entry::Segment(SegmentPlace::new("UNH").with_min(1).with_max(1)),
                Entry::Segment(SegmentPlace::new("BGM").with_min(1).with_max(1)),
                Entry::Group(sg4),
                Entry::Segment(SegmentPlace::new("UNT").with_min(1).with_max(1)),
            ],
        )
        .unwrap()
    }

    fn only<'a>(issues: &'a [ValidationIssue], code: &str) -> Vec<&'a ValidationIssue> {
        issues
            .iter()
            .filter(|i| i.error_code() == Some(code))
            .collect()
    }

    #[test]
    fn placement_findings_unplaced() {
        let segs = parse_segs(
            "UNH+1+UTILMD:D:11A:UN'BGM+E01'IDE+24+A'LOC+Z16'IDE+24+B'LOC+Z16'IDE+24+C'LOC+Z16'FTX+ACB'UNT+10+1'",
        );
        let schema = schema();
        let resolution = schema.resolve(&segs);
        let findings = resolution.findings(&segs);
        let unplaced = only(&findings, "E068");
        assert_eq!(unplaced.len(), 1, "{findings:#?}");
        let issue = unplaced[0];
        assert_eq!(issue.kind(), Some(FindingKind::Placement));
        assert_eq!(issue.layer(), Some(ValidationLayer::Structure));
        assert_eq!(issue.segment_tag(), Some("FTX"));
        assert_eq!(issue.span(), Some(segs[8].span));
        assert_eq!(issue.segment_position(), Some(9));
        assert_eq!(
            issue.group_path().map(ToString::to_string).as_deref(),
            Some("SG4[2]/SG5[0]"),
            "the instance it was skipped in",
        );
        assert_eq!(findings.len(), 1, "nothing else is wrong: {findings:#?}");
    }

    #[test]
    fn placement_findings_count() {
        let segs = parse_segs(
            "UNH+1+UTILMD:D:11A:UN'BGM+E01'IDE+24+A'DTM+92:1'DTM+93:2'LOC+Z16'LOC+Z17'UNT+8+1'",
        );
        let schema = schema();
        let findings = schema.resolve(&segs).findings(&segs);

        let dtm = only(&findings, "E069");
        assert_eq!(dtm.len(), 1, "{findings:#?}");
        assert_eq!(dtm[0].kind(), Some(FindingKind::Count));
        assert_eq!(dtm[0].span(), Some(segs[4].span));
        assert_eq!(dtm[0].segment_position(), Some(5));
        assert_eq!(dtm[0].context_get("place"), Some("00020"));
        assert_eq!(
            dtm[0].group_path().map(ToString::to_string).as_deref(),
            Some("SG4[0]")
        );

        let sg5 = only(&findings, "E070");
        assert_eq!(sg5.len(), 1, "{findings:#?}");
        assert_eq!(sg5[0].kind(), Some(FindingKind::Count));
        assert_eq!(sg5[0].span(), Some(segs[6].span));
        assert_eq!(sg5[0].context_get("place"), Some("SG5-MALO"));
        assert_eq!(
            sg5[0].group_path().map(ToString::to_string).as_deref(),
            Some("SG4[0]/SG5[1]")
        );
        assert_eq!(findings.len(), 2, "{findings:#?}");
    }

    #[test]
    fn placement_findings_missing() {
        let segs = parse_segs("UNH+1+UTILMD:D:11A:UN'BGM+E01'IDE+24+A'UNT+4+1'");
        let schema = schema();
        let findings = schema.resolve(&segs).findings(&segs);
        assert_eq!(findings.len(), 1, "{findings:#?}");
        let issue = &findings[0];
        assert_eq!(issue.error_code(), Some("E015"));
        assert_eq!(issue.kind(), Some(FindingKind::Missing));
        assert_eq!(issue.layer(), Some(ValidationLayer::Structure));
        assert_eq!(issue.segment_tag(), Some("LOC"), "the group's trigger tag");
        assert_eq!(
            issue.group_path().map(ToString::to_string).as_deref(),
            Some("SG4[0]")
        );
        assert_eq!(issue.context_get("place"), Some("SG5-MALO"));
        assert_eq!(issue.span(), None, "nothing to point at");

        // A missing root place has no path.
        let segs = parse_segs("UNH+1+UTILMD:D:11A:UN'UNT+2+1'");
        let findings = schema.resolve(&segs).findings(&segs);
        assert_eq!(findings.len(), 1, "{findings:#?}");
        assert_eq!(findings[0].segment_tag(), Some("BGM"));
        assert!(findings[0].group_path().is_none());
    }

    #[test]
    fn placement_findings_through_a_validation_context() {
        let segs =
            parse_segs("UNH+1+UTILMD:D:11A:UN'BGM+E01'IDE+24+A'DTM+92:1'DTM+93:2'FTX+ACB'UNT+7+1'");
        let schema = Arc::new(schema());
        let direct = schema.resolve(&segs).findings(&segs);
        let report = ValidationContext::builder()
            .with_validator(
                ValidationLayer::Structure,
                PlacementValidator::new(Arc::clone(&schema)),
            )
            .build()
            .validate(&segs);

        let codes = |issues: Vec<&ValidationIssue>| -> Vec<String> {
            let mut codes: Vec<String> = issues
                .iter()
                .map(|i| format!("{:?}@{:?}", i.error_code(), i.segment_position()))
                .collect();
            codes.sort();
            codes
        };
        assert_eq!(
            codes(report.iter_issues().collect()),
            codes(direct.iter().collect()),
        );
        assert!(
            report
                .iter_issues()
                .all(|i| i.layer() == Some(ValidationLayer::Structure))
        );
        assert_eq!(report.total_issues(), 3, "{report}");
    }
}