automapper-validation 0.30.1

AHB condition expression parsing, evaluation, and EDIFACT validation
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
//! EBD answer-code cluster lookup.
//!
//! Resolves UTILMD/ORDRSP/IFTSTA conditions that classify STS response
//! codes by "Cluster Zustimmung" or "Cluster Ablehnung". The cluster is
//! a per-EBD attribute — the same A-code can sit in a different cluster
//! depending on which EBD (C556/1131 qualifier) it belongs to.
//!
//! Data source: extracted from `mako_prozesse` (YAML per EBD) via
//! `scripts/extract_ebd_clusters.py`.

use super::context::EvaluationContext;
use super::evaluator::ConditionResult;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::OnceLock;

const EMBEDDED_JSON: &str = include_str!("../../data/ebd_cluster_map.json");

#[derive(Debug, Deserialize)]
struct RawFile {
    ebds: HashMap<String, HashMap<String, String>>,
}

/// Cluster classifier derived from the `Cluster:` hint in an EBD YAML.
///
/// Primary clusters (Zustimmung, Ablehnung) and the three Ablehnung
/// sub-levels referenced by REMADV/INVOIC conditions have named
/// variants; anything else (Änderung, Korrekturliste, Abweisung, ...)
/// falls into `Other` preserving the raw label for future match-ups.
///
/// `is_ablehnung` returns true for both the plain `Ablehnung` variant
/// and all three sub-level variants, so UTILMD_Strom conditions like
/// `[359]` keep matching sub-level codes transparently.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cluster {
    Zustimmung,
    Ablehnung,
    AblehnungKopfebene,
    AblehnungPositionsebene,
    AblehnungSummenebene,
    /// Preserves the raw cluster label (e.g. "Korrekturliste wegen Ablehnung",
    /// "Änderung der Daten", "Abweisung") so future conditions can match
    /// on it without regenerating the data file.
    Other(String),
}

impl Cluster {
    pub fn from_token(token: &str) -> Self {
        match token {
            "Zustimmung" => Cluster::Zustimmung,
            "Ablehnung" => Cluster::Ablehnung,
            "Ablehnung auf Kopfebene" => Cluster::AblehnungKopfebene,
            "Ablehnung auf Positionsebene" => Cluster::AblehnungPositionsebene,
            "Ablehnung auf Summenebene" => Cluster::AblehnungSummenebene,
            _ => Cluster::Other(token.to_owned()),
        }
    }

    pub fn is_zustimmung(&self) -> bool {
        matches!(self, Cluster::Zustimmung)
    }

    /// Any Ablehnung variant — plain or Kopf/Positions/Summenebene.
    pub fn is_ablehnung(&self) -> bool {
        matches!(
            self,
            Cluster::Ablehnung
                | Cluster::AblehnungKopfebene
                | Cluster::AblehnungPositionsebene
                | Cluster::AblehnungSummenebene
        )
    }

    pub fn is_ablehnung_kopfebene(&self) -> bool {
        matches!(self, Cluster::AblehnungKopfebene)
    }

    pub fn is_ablehnung_positionsebene(&self) -> bool {
        matches!(self, Cluster::AblehnungPositionsebene)
    }

    pub fn is_ablehnung_summenebene(&self) -> bool {
        matches!(self, Cluster::AblehnungSummenebene)
    }
}

#[derive(Debug)]
pub struct EbdClusterLookup {
    clusters: HashMap<(String, String), Cluster>,
}

impl EbdClusterLookup {
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        let raw: RawFile = serde_json::from_str(json)?;
        let clusters = raw
            .ebds
            .into_iter()
            .flat_map(|(ebd, codes)| {
                codes
                    .into_iter()
                    .map(move |(code, token)| ((ebd.clone(), code), Cluster::from_token(&token)))
            })
            .collect();
        Ok(Self { clusters })
    }

    pub fn embedded() -> &'static Self {
        static CELL: OnceLock<EbdClusterLookup> = OnceLock::new();
        CELL.get_or_init(|| {
            EbdClusterLookup::from_json(EMBEDDED_JSON)
                .expect("embedded ebd_cluster_map.json is malformed")
        })
    }

    /// Looks up the cluster for `code` within `ebd`. Returns `None` when
    /// the EBD isn't in the data set or the code isn't an answer-code
    /// leaf of that EBD.
    pub fn cluster(&self, ebd: &str, code: &str) -> Option<&Cluster> {
        self.clusters.get(&(ebd.to_owned(), code.to_owned()))
    }
}

// -----------------------------------------------------------------------
// Shared evaluator helpers for cluster conditions.
//
// These sit on the ctx + cluster lookup and are used by per-message
// generated condition files (UTILMD_Strom, ORDRSP, UTILTS, REMADV).
// Putting them here keeps the HAND-EDITED hot spots in one place so the
// codegen prompt (Task B6) only needs to learn about this one module.

/// STS+E01 layout helper: extract `(code, ebd)` from element[2].
/// Returns None when either component is missing or empty.
fn sts_e01_code_ebd(seg: &mig_types::segment::OwnedSegment) -> Option<(&str, &str)> {
    let c556 = seg.elements.get(2)?;
    let code = c556.first().filter(|v| !v.is_empty())?.as_str();
    let ebd = c556.get(1).filter(|v| !v.is_empty())?.as_str();
    Some((code, ebd))
}

/// AJT layout helper (REMADV): extract `(code, ebd)` from `AJT`.
/// AJT has DE4465 at element[0][0] and DE1082 (EBD qualifier like
/// `E_0403`) at element[1][0].
fn ajt_code_ebd(seg: &mig_types::segment::OwnedSegment) -> Option<(&str, &str)> {
    let code = seg
        .elements
        .first()?
        .first()
        .filter(|v| !v.is_empty())?
        .as_str();
    let ebd = seg
        .elements
        .get(1)?
        .first()
        .filter(|v| !v.is_empty())?
        .as_str();
    Some((code, ebd))
}

/// The STS answers a cluster condition judges: the answer the validator is
/// visiting, when it is one of `qualifier` — or else every STS+`qualifier`
/// of the enclosing SG4 (message-wide without a scope) that carries a code.
/// `(code, ebd)`; the EBD is empty when the segment names none.
fn sts_answers(ctx: &EvaluationContext, qualifier: &str) -> Vec<(String, String)> {
    let answer = |elements: &[Vec<String>]| {
        let c556 = elements.get(2)?;
        let code = c556.first().filter(|v| !v.is_empty())?;
        Some((code.clone(), c556.get(1).cloned().unwrap_or_default()))
    };
    if let (Some(value), Some(segment)) = (ctx.resolved_value, ctx.resolved_segment) {
        let own = segment.first().and_then(|e| e.first()).map(String::as_str);
        if own == Some(qualifier) && !value.is_empty() {
            let ebd = segment
                .get(2)
                .and_then(|c| c.get(1))
                .cloned()
                .unwrap_or_default();
            return vec![(value.to_string(), ebd)];
        }
    }
    ctx.scoped_find_segments_in_with_qualifier("SG4", "STS", 0, qualifier)
        .iter()
        .filter_map(|s| answer(&s.elements))
        .collect()
}

/// Whether every answer passes `judge`: `False` when one fails, `Unknown`
/// when none fails but one cannot be told, `True` otherwise — no answer
/// included. A missing answer is the business of the field's requirement, not
/// of a condition on what the answer may be.
fn every_answer(
    answers: &[(String, String)],
    judge: impl Fn(&str, &str) -> ConditionResult,
) -> ConditionResult {
    let mut result = ConditionResult::True;
    for (code, ebd) in answers {
        match judge(code, ebd) {
            ConditionResult::False => return ConditionResult::False,
            ConditionResult::Unknown => result = ConditionResult::Unknown,
            ConditionResult::True => {}
        }
    }
    result
}

/// `[UTILMD_Strom 359/360]` — every `STS+E01` answer is a code whose cluster
/// under its referenced EBD matches `predicate` ("Es sind nur Antwortcodes aus
/// dem Cluster Zustimmung erlaubt"). A code the EBD does not hold (`Q99`) is in
/// no cluster and fails; an answer naming no EBD cannot be told.
pub fn all_sts_e01_in_cluster(
    ctx: &EvaluationContext,
    predicate: impl Fn(&Cluster) -> bool,
) -> ConditionResult {
    every_answer(&sts_answers(ctx, "E01"), |code, ebd| {
        if ebd.is_empty() {
            return ConditionResult::Unknown;
        }
        ConditionResult::from(ctx.ebd_clusters.cluster(ebd, code).is_some_and(&predicate))
    })
}

/// `[UTILMD_Strom 366/368]` — every `STS+qualifier` answer is a code of
/// `required_ebd` in the cluster Ablehnung, other than `excluded_codes` ("Bis
/// auf den Code A30 sind alle Codes aus EBD E_0624 im Cluster Ablehnung
/// erlaubt"). The conditions sit on STS+Z35, the third party's answer; the
/// STS+E01 beside it names another EBD. An answer naming no EBD is read as
/// naming `required_ebd`, the only one its AHB allows.
pub fn ebd_ablehnung_except(
    ctx: &EvaluationContext,
    qualifier: &str,
    required_ebd: &str,
    excluded_codes: &[&str],
) -> ConditionResult {
    every_answer(&sts_answers(ctx, qualifier), |code, ebd| {
        let ebd = if ebd.is_empty() { required_ebd } else { ebd };
        ConditionResult::from(
            ebd == required_ebd
                && !excluded_codes.contains(&code)
                && ctx
                    .ebd_clusters
                    .cluster(ebd, code)
                    .is_some_and(Cluster::is_ablehnung),
        )
    })
}

/// `[UTILTS 61]` — any `STS+E01` carries an Ablehnung-cluster code.
/// Existential rather than universal — matches the AHB wording
/// "Wenn in einem STS+E01 ... ein Antwortcode aus dem Cluster Ablehnung
/// vorhanden ist". Returns `False` rather than `Unknown` when no
/// `STS+E01` is present (the premise is absent).
pub fn any_sts_e01_in_cluster(
    ctx: &EvaluationContext,
    predicate: impl Fn(&Cluster) -> bool,
) -> ConditionResult {
    let sts_segs = ctx.find_segments_with_qualifier("STS", 0, "E01");
    let found = sts_segs.iter().any(|s| {
        sts_e01_code_ebd(s)
            .is_some_and(|(code, ebd)| ctx.ebd_clusters.cluster(ebd, code).is_some_and(&predicate))
    });
    ConditionResult::from(found)
}

/// `[ORDRSP 17/18]` — resolved STS code is in the given cluster under
/// the same segment's referenced EBD. Uses `ctx.resolved_value` +
/// `ctx.resolved_segment` which are populated by the tree validator
/// when visiting a specific field.
///
/// Returns `Unknown` when the resolved context is absent — so bulk
/// `evaluate(17, ctx)` calls without a resolved field get a safe
/// three-valued answer.
pub fn resolved_sts_code_in_cluster(
    ctx: &EvaluationContext,
    predicate: impl Fn(&Cluster) -> bool,
) -> ConditionResult {
    let (Some(code), Some(segment)) = (ctx.resolved_value, ctx.resolved_segment) else {
        return ConditionResult::Unknown;
    };
    if code.is_empty() {
        return ConditionResult::Unknown;
    }
    let ebd = segment
        .get(2)
        .and_then(|e| e.get(1))
        .map(|s| s.as_str())
        .filter(|s| !s.is_empty());
    let Some(ebd) = ebd else {
        return ConditionResult::Unknown;
    };
    ctx.ebd_clusters
        .cluster(ebd, code)
        .map(|c| ConditionResult::from(predicate(c)))
        .unwrap_or(ConditionResult::Unknown)
}

/// `[REMADV 14/15/16]` — resolved AJT DE4465 code is in the given
/// cluster under the segment's referenced EBD (DE1082, element[1][0]).
pub fn resolved_ajt_code_in_cluster(
    ctx: &EvaluationContext,
    predicate: impl Fn(&Cluster) -> bool,
) -> ConditionResult {
    let (Some(code), Some(segment)) = (ctx.resolved_value, ctx.resolved_segment) else {
        return ConditionResult::Unknown;
    };
    if code.is_empty() {
        return ConditionResult::Unknown;
    }
    let ebd = segment
        .get(1)
        .and_then(|e| e.first())
        .map(|s| s.as_str())
        .filter(|s| !s.is_empty());
    let Some(ebd) = ebd else {
        return ConditionResult::Unknown;
    };
    ctx.ebd_clusters
        .cluster(ebd, code)
        .map(|c| ConditionResult::from(predicate(c)))
        .unwrap_or(ConditionResult::Unknown)
}

/// `[REMADV 517/518]` — any AJT "in dieser SG5" (the enclosing SG5 and its
/// SG7s; message-wide when no scope is attached) carries a code whose
/// cluster matches `predicate` and whose A-code is not in
/// `excluded_codes`.
pub fn any_scoped_ajt_in_cluster(
    ctx: &EvaluationContext,
    excluded_codes: &[&str],
    predicate: impl Fn(&Cluster) -> bool,
) -> ConditionResult {
    let ajt_segs = ctx.scoped_find_segments_in("SG5", "AJT");
    let found = ajt_segs.iter().any(|s| {
        ajt_code_ebd(s).is_some_and(|(code, ebd)| {
            !excluded_codes.contains(&code)
                && ctx.ebd_clusters.cluster(ebd, code).is_some_and(&predicate)
        })
    });
    ConditionResult::from(found)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::eval::NoOpExternalProvider;
    use mig_types::segment::OwnedSegment;

    fn sts(qualifier: &str, code: &str, ebd: &str) -> OwnedSegment {
        OwnedSegment {
            id: "STS".into(),
            elements: vec![
                vec![qualifier.into()],
                vec![],
                vec![code.into(), ebd.into()],
            ],
            segment_number: 0,
        }
    }

    fn judge(
        segments: &[OwnedSegment],
        f: impl Fn(&EvaluationContext) -> ConditionResult,
    ) -> ConditionResult {
        let external = NoOpExternalProvider;
        let ctx = EvaluationContext::new("55003", &external, segments);
        f(&ctx)
    }

    /// `[360]`: an Ablehnung code, or a code no list holds, is not a
    /// Zustimmung (mako-twin: 55002 passed with A50 and with Q99).
    #[test]
    fn only_zustimmung_answers_hold_360() {
        let zustimmung = |segs: &[OwnedSegment]| {
            judge(segs, |ctx| {
                all_sts_e01_in_cluster(ctx, Cluster::is_zustimmung)
            })
        };
        assert_eq!(
            zustimmung(&[sts("E01", "A51", "E_0623")]),
            ConditionResult::True
        );
        assert_eq!(
            zustimmung(&[sts("E01", "A50", "E_0623")]),
            ConditionResult::False
        );
        assert_eq!(
            zustimmung(&[sts("E01", "Q99", "E_0623")]),
            ConditionResult::False
        );
        // Nothing answered: nothing breaks the rule; whether an answer is
        // missing is the requirement's business.
        assert_eq!(zustimmung(&[]), ConditionResult::True);
    }

    /// `[366]`/`[368]` judge the third party's answer, STS+Z35 against
    /// E_0624 — not the STS+E01, which names another EBD.
    #[test]
    fn the_third_partys_answer_is_judged_by_366_and_368() {
        let e01 = sts("E01", "A50", "E_0623");
        let r366 = |z35: &str| {
            judge(&[e01.clone(), sts("Z35", z35, "E_0624")], |ctx| {
                ebd_ablehnung_except(ctx, "Z35", "E_0624", &["A30"])
            })
        };
        assert_eq!(r366("A32"), ConditionResult::True, "A32 is an Ablehnung");
        assert_eq!(r366("A30"), ConditionResult::False, "bis auf A30");
        assert_eq!(r366("A31"), ConditionResult::False, "A31 is a Zustimmung");
        let r368 = |z35: &str| {
            judge(&[e01.clone(), sts("Z35", z35, "E_0624")], |ctx| {
                ebd_ablehnung_except(ctx, "Z35", "E_0624", &["A41"])
            })
        };
        assert_eq!(r368("A30"), ConditionResult::True);
        assert_eq!(r368("A41"), ConditionResult::False);
        // No STS+Z35: nothing breaks the rule.
        assert_eq!(
            judge(std::slice::from_ref(&e01), |ctx| ebd_ablehnung_except(
                ctx,
                "Z35",
                "E_0624",
                &["A41"]
            )),
            ConditionResult::True
        );
    }

    /// The validator visiting the answer itself judges that answer, not
    /// every STS of the message.
    #[test]
    fn a_resolved_answer_is_judged_alone() {
        let segments = [sts("Z35", "A30", "E_0624"), sts("Z35", "A41", "E_0624")];
        let external = NoOpExternalProvider;
        let ctx = EvaluationContext::new("55080", &external, &segments);
        let first = ctx.with_resolved(Some("A30"), Some(&segments[0].elements));
        assert_eq!(
            ebd_ablehnung_except(&first, "Z35", "E_0624", &["A41"]),
            ConditionResult::True
        );
        let second = ctx.with_resolved(Some("A41"), Some(&segments[1].elements));
        assert_eq!(
            ebd_ablehnung_except(&second, "Z35", "E_0624", &["A41"]),
            ConditionResult::False
        );
    }

    #[test]
    fn a36_in_e0624_is_zustimmung() {
        let lookup = EbdClusterLookup::embedded();
        assert_eq!(lookup.cluster("E_0624", "A36"), Some(&Cluster::Zustimmung));
    }

    #[test]
    fn a30_in_e0624_is_ablehnung() {
        let lookup = EbdClusterLookup::embedded();
        assert_eq!(lookup.cluster("E_0624", "A30"), Some(&Cluster::Ablehnung));
    }

    #[test]
    fn unknown_code_returns_none() {
        let lookup = EbdClusterLookup::embedded();
        assert_eq!(lookup.cluster("E_0624", "Z99"), None);
    }

    #[test]
    fn unknown_ebd_returns_none() {
        let lookup = EbdClusterLookup::embedded();
        assert_eq!(lookup.cluster("E_9999", "A01"), None);
    }

    #[test]
    fn same_code_can_differ_across_ebds() {
        // A01 is a common outcome code across many EBDs; at minimum make
        // sure the (ebd, code) key shape works — both should resolve.
        let lookup = EbdClusterLookup::embedded();
        assert!(lookup.cluster("E_0014", "A01").is_some());
        assert!(lookup.cluster("E_0049", "A01").is_some());
    }

    #[test]
    fn korrekturliste_wegen_ablehnung_is_preserved_as_other() {
        let lookup = EbdClusterLookup::embedded();
        // E_0014 A04 has hint "Cluster: Korrekturliste wegen Ablehnung ...".
        // Not in the named enum variants, so it stays in Other with the
        // full multi-word label.
        match lookup.cluster("E_0014", "A04") {
            Some(Cluster::Other(s)) => assert_eq!(s, "Korrekturliste wegen Ablehnung"),
            other => {
                panic!("expected Cluster::Other(\"Korrekturliste wegen Ablehnung\"), got {other:?}")
            }
        }
    }

    #[test]
    fn sub_level_ablehnung_variants_still_count_as_ablehnung() {
        assert!(Cluster::Ablehnung.is_ablehnung());
        assert!(Cluster::AblehnungKopfebene.is_ablehnung());
        assert!(Cluster::AblehnungPositionsebene.is_ablehnung());
        assert!(Cluster::AblehnungSummenebene.is_ablehnung());
        assert!(!Cluster::Zustimmung.is_ablehnung());
        assert!(!Cluster::Other("Abweisung".into()).is_ablehnung());
    }
}