automapper-validation 0.31.0

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
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
//! Core condition evaluation traits.

use super::context::EvaluationContext;

/// Three-valued result of evaluating a single condition.
///
/// Unlike the C# implementation which uses `bool`, we use three-valued logic
/// to support partial evaluation when external conditions are unavailable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConditionResult {
    /// The condition is satisfied.
    True,
    /// The condition is not satisfied.
    False,
    /// The condition cannot be determined (e.g., external condition without a provider).
    Unknown,
}

impl ConditionResult {
    /// Returns `true` if this is `ConditionResult::True`.
    pub fn is_true(self) -> bool {
        matches!(self, ConditionResult::True)
    }

    /// Returns `true` if this is `ConditionResult::False`.
    pub fn is_false(self) -> bool {
        matches!(self, ConditionResult::False)
    }

    /// Returns `true` if this is `ConditionResult::Unknown`.
    pub fn is_unknown(self) -> bool {
        matches!(self, ConditionResult::Unknown)
    }

    /// Three-valued AND: `False` if either is, `True` if both are, else `Unknown`.
    pub fn and(self, other: ConditionResult) -> ConditionResult {
        match (self, other) {
            (ConditionResult::False, _) | (_, ConditionResult::False) => ConditionResult::False,
            (ConditionResult::True, ConditionResult::True) => ConditionResult::True,
            _ => ConditionResult::Unknown,
        }
    }

    /// Three-valued OR: `True` if either is, `False` if both are, else `Unknown`.
    pub fn or(self, other: ConditionResult) -> ConditionResult {
        match (self, other) {
            (ConditionResult::True, _) | (_, ConditionResult::True) => ConditionResult::True,
            (ConditionResult::False, ConditionResult::False) => ConditionResult::False,
            _ => ConditionResult::Unknown,
        }
    }

    /// Three-valued NOT.
    pub fn negate(self) -> ConditionResult {
        match self {
            ConditionResult::True => ConditionResult::False,
            ConditionResult::False => ConditionResult::True,
            ConditionResult::Unknown => ConditionResult::Unknown,
        }
    }

    /// Converts to `Option<bool>`: True -> Some(true), False -> Some(false), Unknown -> None.
    pub fn to_option(self) -> Option<bool> {
        match self {
            ConditionResult::True => Some(true),
            ConditionResult::False => Some(false),
            ConditionResult::Unknown => None,
        }
    }
}

impl From<bool> for ConditionResult {
    fn from(value: bool) -> Self {
        if value {
            ConditionResult::True
        } else {
            ConditionResult::False
        }
    }
}

impl std::fmt::Display for ConditionResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConditionResult::True => write!(f, "True"),
            ConditionResult::False => write!(f, "False"),
            ConditionResult::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Evaluates individual AHB conditions by number.
///
/// Implementations are typically generated from AHB XML schemas (one per
/// message type and format version). Each condition number maps to a
/// specific business rule check.
pub trait ConditionEvaluator: Send + Sync {
    /// Evaluate a single condition by number.
    ///
    /// Returns `ConditionResult::Unknown` for unrecognized condition numbers
    /// or conditions that require unavailable external context.
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult;

    /// Returns `true` if the given condition requires external context
    /// (i.e., cannot be determined from the EDIFACT message alone).
    fn is_external(&self, condition: u32) -> bool;

    /// Returns `true` if this evaluator has an implementation for the given
    /// condition number (whether internal or external). Conditions that fall
    /// through to the `_ => Unknown` wildcard return `false`.
    ///
    /// This allows distinguishing "implemented but returned Unknown because
    /// the relevant data isn't present in the message" from "not implemented
    /// at all".
    fn is_known(&self, _condition: u32) -> bool {
        false
    }

    /// Returns the message type this evaluator handles (e.g., "UTILMD").
    fn message_type(&self) -> &str;

    /// Returns the format version this evaluator handles (e.g., "FV2510").
    fn format_version(&self) -> &str;
}

impl<T: ConditionEvaluator + ?Sized> ConditionEvaluator for std::sync::Arc<T> {
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        (**self).evaluate(condition, ctx)
    }

    fn is_external(&self, condition: u32) -> bool {
        (**self).is_external(condition)
    }

    fn is_known(&self, condition: u32) -> bool {
        (**self).is_known(condition)
    }

    fn message_type(&self) -> &str {
        (**self).message_type()
    }

    fn format_version(&self) -> &str {
        (**self).format_version()
    }
}

/// Provider for external conditions that depend on context outside the EDIFACT message.
///
/// External conditions are things like:
/// - [1] "Wenn Aufteilung vorhanden" (message splitting status)
/// - [14] "Wenn Datum bekannt" (whether a date is known)
/// - [30] "Wenn Antwort auf Aktivierung" (response to activation)
///
/// These cannot be determined from the EDIFACT content alone and require
/// business context from the calling system.
pub trait ExternalConditionProvider: Send + Sync {
    /// Evaluate an external condition by name.
    ///
    /// The `condition_name` corresponds to the speaking name from the
    /// generated external conditions constants (e.g., "MessageSplitting",
    /// "DateKnown").
    fn evaluate(&self, condition_name: &str) -> ConditionResult;
}

/// A no-op external condition provider that returns `Unknown` for everything.
///
/// Useful when no external context is available — conditions will propagate
/// as `Unknown` through the expression evaluator.
pub struct NoOpExternalProvider;

impl ExternalConditionProvider for NoOpExternalProvider {
    fn evaluate(&self, _condition_name: &str) -> ConditionResult {
        ConditionResult::Unknown
    }
}

/// The number of a message type's bare "Wenn vorhanden" condition, if it has one.
///
/// The condition is self-referential: its value is whether the element or
/// group it annotates is present. `Soll [166]` on a group means "send it if
/// you have it", which only the sender knows, so an absent group annotated
/// with it is never missing. The generated evaluators answer it with `True`
/// ("the rule applies wherever it is evaluated"), which is right for a present
/// element and wrong for an absent one — see [`AbsentTarget`].
///
/// The numbers are stable across every format version in
/// `xml-migs-and-ahbs/` (FV2410–FV2610); keyed by [`ConditionEvaluator::message_type`]
/// rather than by evaluator so aliased and regenerated evaluators need no edit.
pub fn presence_condition(message_type: &str) -> Option<u32> {
    match message_type {
        "UTILMD_Strom" | "UTILMD_Gas" => Some(166),
        "INVOIC" => Some(22),
        "ORDERS" => Some(12),
        _ => None,
    }
}

/// Every condition of a message type that answers "does the annotated thing
/// exist?", which an absent element or group answers with no.
///
/// The [`presence_condition`], plus conditions that ask for one repetition per
/// real-world object the message cannot see. UTILMD_Strom [2003] ("Einmal für
/// jede ruhende Marktlokation, die der Marktlokation »Kundenanlage« …
/// untergeordnet ist", FV2504–FV2610, absent in Gas) is `Soll` on the ruhende
/// Marktlokation: zero ruhende MaLos means zero groups, and only the sender
/// knows how many exist. The generated evaluators cannot decide it and answer
/// `Unknown`, which reported every message without a ruhende MaLo.
pub fn presence_conditions(message_type: &str) -> &'static [u32] {
    match message_type {
        "UTILMD_Strom" => &[166, 2003],
        "UTILMD_Gas" => &[166],
        "INVOIC" => &[22],
        "ORDERS" => &[12],
        _ => &[],
    }
}

/// The condition of a message type that allows a group or segment once per
/// transaction, and the transaction group: UTILMD's `[2061]` "Segment bzw.
/// Segmentgruppe ist genau einmal je SG4 IDE (Vorgang) anzugeben" (Strom and
/// Gas, FV2504–FV2610). The conditions evaluate it as `True` wherever there is
/// a transaction, so what it limits — the count — is checked on its own; see
/// [`binds_once`].
pub fn once_per_transaction(message_type: &str) -> Option<(u32, &'static str)> {
    transaction_group(message_type).map(|group| (2061, group))
}

/// The group a message type repeats once per transaction, whose conditions the
/// AHB states per transaction: UTILMD's SG4 (`IDE+24`, Vorgang). The validator
/// evaluates each repetition against the message as that transaction sees it
/// (`mig_assembly::transaction_view`, #337).
pub fn transaction_group(message_type: &str) -> Option<&'static str> {
    match message_type {
        "UTILMD_Strom" | "UTILMD_Gas" => Some("SG4"),
        _ => None,
    }
}

/// Whether `status` limits what it annotates to once per transaction: the
/// condition `once` is a conjunct of every line (`Muss [483] ∧ [2061]`). Where
/// it sits in one branch only (`Soll [165] ∧ (([2061] ∧ [583]) ∨ [584])`), the
/// other branch allows more.
pub fn binds_once(status: &str, once: u32) -> bool {
    fn conjunct(expr: &crate::expr::ConditionExpr, once: u32) -> bool {
        match expr {
            crate::expr::ConditionExpr::Ref(id) => *id == once,
            crate::expr::ConditionExpr::And(exprs) => exprs.iter().any(|e| conjunct(e, once)),
            _ => false,
        }
    }
    let lines: Vec<&str> = status
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();
    !lines.is_empty()
        && lines.iter().all(|line| {
            matches!(
                crate::expr::ConditionParser::parse(line),
                Ok(Some(expr)) if conjunct(&expr, once)
            )
        })
}

/// Evaluates conditions for an element or group that is known to be absent.
///
/// Identical to the wrapped evaluator except that the message type's
/// [`presence_conditions`] are `False`: whatever the condition annotates is not
/// there. Use it wherever a status is evaluated to decide whether something
/// missing is required.
pub struct AbsentTarget<'a, E: ConditionEvaluator + ?Sized>(pub &'a E);

impl<E: ConditionEvaluator + ?Sized> ConditionEvaluator for AbsentTarget<'_, E> {
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        if presence_conditions(self.0.message_type()).contains(&condition) {
            return ConditionResult::False;
        }
        self.0.evaluate(condition, ctx)
    }

    fn is_external(&self, condition: u32) -> bool {
        self.0.is_external(condition)
    }

    fn is_known(&self, condition: u32) -> bool {
        self.0.is_known(condition)
    }

    fn message_type(&self) -> &str {
        self.0.message_type()
    }

    fn format_version(&self) -> &str {
        self.0.format_version()
    }
}

/// Evaluates conditions for an element or group that is known to be present,
/// to decide whether it is allowed there.
///
/// The message type's [`presence_conditions`] are `True`: whatever the
/// condition annotates is there. Only the AHB's conditions proper (`[1]` to
/// `[499]`) decide; notes (`[500]`–`[899]`), formats (`[900]`–`[999]`) and
/// repetition rules (`[2000]` and up: "genau einmal je SG8 …") say nothing about
/// whether something may be sent, and are `Unknown` — so `[197] ∧ [2308]` is
/// false when `[197]` is, and `[2317] ⊻ [2318]` is never.
pub struct PresentTarget<'a, E: ConditionEvaluator + ?Sized>(pub &'a E);

impl<E: ConditionEvaluator + ?Sized> ConditionEvaluator for PresentTarget<'_, E> {
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        if presence_conditions(self.0.message_type()).contains(&condition) {
            return ConditionResult::True;
        }
        if !(1..500).contains(&condition) {
            return ConditionResult::Unknown;
        }
        self.0.evaluate(condition, ctx)
    }

    fn is_external(&self, condition: u32) -> bool {
        self.0.is_external(condition)
    }

    fn is_known(&self, condition: u32) -> bool {
        self.0.is_known(condition)
    }

    fn message_type(&self) -> &str {
        self.0.message_type()
    }

    fn format_version(&self) -> &str {
        self.0.format_version()
    }
}

/// Whether something present under `status` is not allowed where `ctx` is: a
/// `Muss`/`X` status with a condition that evaluates to false through
/// [`PresentTarget`]. `Soll`/`Kann`, an unconditional status, an undecidable
/// condition, a package (`[19P1..1]`, judged by its own check) and a status of
/// several lines refuse nothing.
pub fn refuses_presence<E: ConditionEvaluator + ?Sized>(
    status: &str,
    evaluator: &E,
    ctx: &EvaluationContext,
    ub_definitions: &std::collections::BTreeMap<String, crate::expr::ConditionExpr>,
) -> bool {
    refuses(status, &PresentTarget(evaluator), ctx, ub_definitions)
}

/// The repetition conditions of a message type whose evaluators count what
/// they limit in the group they name, so that a false one means "sent too
/// often there": ORDERS `[2005]` / `[2006]`, "Pro SG29 LIN ist die SG34
/// RFF+Z09 (Gerätenummer) genau einmal / bis zu dreimal anzugeben". Most
/// `[2000]`+ evaluators still count over the whole message; a condition joins
/// this list once its evaluator is verified to count per instance.
pub fn counted_repetitions(message_type: &str) -> &'static [u32] {
    match message_type {
        "ORDERS" => &[2005, 2006],
        _ => &[],
    }
}

/// The repetition conditions of a message type that set how often a segment
/// is sent in its group instance where they apply, as `(condition, min,
/// max)`: UTILMD Strom `[2317]` "… CAV+MIW/MPW/MUW vorhanden, ist das Segment
/// mindestens zweimal anzugeben" and `[2318]` "… CAV+MBW vorhanden, … genau
/// einmal" on the Wandler's CAV+Z30. Their evaluators say whether one applies
/// there (which also makes the segment required); the count is judged by
/// [`breaks_repetition_limit`].
pub fn repetition_limits(message_type: &str) -> &'static [(u32, usize, Option<usize>)] {
    match message_type {
        "UTILMD_Strom" => &[(2317, 2, None), (2318, 1, Some(1))],
        _ => &[],
    }
}

/// Whether `count` segments under `status` break a [`repetition_limits`]
/// condition the status names and that applies where `ctx` is.
pub fn breaks_repetition_limit<E: ConditionEvaluator + ?Sized>(
    status: &str,
    evaluator: &E,
    ctx: &EvaluationContext,
    count: usize,
) -> bool {
    repetition_limits(evaluator.message_type())
        .iter()
        .filter(|(id, _, _)| status.contains(&format!("[{id}]")))
        .any(|&(id, min, max)| {
            evaluator.evaluate(id, ctx) == ConditionResult::True
                && (count < min || max.is_some_and(|max| count > max))
        })
}

/// [`PresentTarget`], except that the message type's
/// [`counted_repetitions`] are evaluated.
struct CountTarget<'a, E: ConditionEvaluator + ?Sized>(&'a E);

impl<E: ConditionEvaluator + ?Sized> ConditionEvaluator for CountTarget<'_, E> {
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        if counted_repetitions(self.0.message_type()).contains(&condition) {
            return self.0.evaluate(condition, ctx);
        }
        PresentTarget(self.0).evaluate(condition, ctx)
    }

    fn is_external(&self, condition: u32) -> bool {
        self.0.is_external(condition)
    }

    fn is_known(&self, condition: u32) -> bool {
        self.0.is_known(condition)
    }

    fn message_type(&self) -> &str {
        self.0.message_type()
    }

    fn format_version(&self) -> &str {
        self.0.format_version()
    }
}

/// Whether something present under `status` is sent more often than it allows
/// where `ctx` is: [`refuses_presence`] does not refuse it, but does once the
/// message type's [`counted_repetitions`] are evaluated. ORDERS 17009's SG34
/// `Muss ([102] ∧ [2006]) ⊻ ([103] ∧ [2005])` holds for the second RFF+Z09
/// of a Zähleinrichtung as far as presence goes; `[2005]` refuses it.
pub fn refuses_count<E: ConditionEvaluator + ?Sized>(
    status: &str,
    evaluator: &E,
    ctx: &EvaluationContext,
    ub_definitions: &std::collections::BTreeMap<String, crate::expr::ConditionExpr>,
) -> bool {
    let counted = counted_repetitions(evaluator.message_type());
    let names_one = status.split('[').skip(1).any(|term| {
        term.split(']')
            .next()
            .and_then(|id| id.parse::<u32>().ok())
            .is_some_and(|id| counted.contains(&id))
    });
    names_one
        && !refuses_presence(status, evaluator, ctx, ub_definitions)
        && refuses(status, &CountTarget(evaluator), ctx, ub_definitions)
}

/// Whether a `Muss`/`X` `status` evaluates to false through `target`; see
/// [`refuses_presence`] for what refuses nothing.
fn refuses<E: ConditionEvaluator>(
    status: &str,
    target: &E,
    ctx: &EvaluationContext,
    ub_definitions: &std::collections::BTreeMap<String, crate::expr::ConditionExpr>,
) -> bool {
    let status = status.trim();
    let package = status.split('[').skip(1).any(|term| {
        term.trim_start_matches(|c: char| c.is_ascii_digit())
            .starts_with('P')
    });
    if status.contains('\n') || !status.contains('[') || package {
        return false;
    }
    let keyword = &status[..status
        .find(|c: char| !c.is_alphabetic())
        .unwrap_or(status.len())];
    if !matches!(keyword, "Muss" | "X") {
        return false;
    }
    super::ConditionExprEvaluator::new(target).evaluate_status_with_ub(status, ctx, ub_definitions)
        == ConditionResult::False
}

#[cfg(test)]
mod tests {
    use super::*;

    struct AlwaysTrue(&'static str);

    impl ConditionEvaluator for AlwaysTrue {
        fn evaluate(&self, _: u32, _: &EvaluationContext) -> ConditionResult {
            ConditionResult::True
        }
        fn is_external(&self, _: u32) -> bool {
            false
        }
        fn message_type(&self) -> &str {
            self.0
        }
        fn format_version(&self) -> &str {
            "FV2604"
        }
    }

    #[test]
    fn once_per_transaction_binds_where_every_line_has_it() {
        assert!(binds_once("Muss [483] ∧ [2061]", 2061));
        assert!(binds_once("Muss [2061]", 2061));
        assert!(binds_once(
            "Muss ([77] ∧ [78]) ∧ [347] ∧ [2061]\r\nKann [2061]",
            2061
        ));
        assert!(!binds_once("Soll [165] ∧ (([2061] ∧ [583]) ∨ [584])", 2061));
        assert!(!binds_once(
            "Muss ([32] ∧ [2061] ∧ [651]) ⊻ ([200] ∧ [601])",
            2061
        ));
        assert!(!binds_once("Muss [483]", 2061));
        assert!(!binds_once("", 2061));
    }

    #[test]
    fn absent_target_answers_only_the_presence_condition_with_false() {
        let external = NoOpExternalProvider;
        let ctx = EvaluationContext::new("55043", &external, &[]);
        let inner = AlwaysTrue("UTILMD_Strom");
        let absent = AbsentTarget(&inner);
        assert_eq!(absent.evaluate(166, &ctx), ConditionResult::False);
        assert_eq!(absent.evaluate(674, &ctx), ConditionResult::True);
        // [2003]: one group per ruhende Marktlokation the sender knows of.
        assert_eq!(absent.evaluate(2003, &ctx), ConditionResult::False);

        // [166] of another message type is an unrelated condition.
        let invoic = AlwaysTrue("INVOIC");
        assert_eq!(
            AbsentTarget(&invoic).evaluate(166, &ctx),
            ConditionResult::True
        );
        assert_eq!(
            AbsentTarget(&invoic).evaluate(22, &ctx),
            ConditionResult::False
        );
    }

    #[test]
    fn test_condition_result_is_methods() {
        assert!(ConditionResult::True.is_true());
        assert!(!ConditionResult::True.is_false());
        assert!(!ConditionResult::True.is_unknown());

        assert!(!ConditionResult::False.is_true());
        assert!(ConditionResult::False.is_false());

        assert!(ConditionResult::Unknown.is_unknown());
    }

    #[test]
    fn three_valued_and_or_not() {
        use ConditionResult::{False as F, True as T, Unknown as U};
        assert_eq!(T.and(T), T);
        assert_eq!(T.and(U), U);
        assert_eq!(U.and(F), F);
        assert_eq!(F.or(F), F);
        assert_eq!(F.or(U), U);
        assert_eq!(U.or(T), T);
        assert_eq!(U.negate(), U);
        assert_eq!(T.negate(), F);
    }

    #[test]
    fn test_condition_result_to_option() {
        assert_eq!(ConditionResult::True.to_option(), Some(true));
        assert_eq!(ConditionResult::False.to_option(), Some(false));
        assert_eq!(ConditionResult::Unknown.to_option(), None);
    }

    #[test]
    fn test_condition_result_from_bool() {
        assert_eq!(ConditionResult::from(true), ConditionResult::True);
        assert_eq!(ConditionResult::from(false), ConditionResult::False);
    }

    #[test]
    fn test_condition_result_display() {
        assert_eq!(format!("{}", ConditionResult::True), "True");
        assert_eq!(format!("{}", ConditionResult::False), "False");
        assert_eq!(format!("{}", ConditionResult::Unknown), "Unknown");
    }

    #[test]
    fn test_noop_external_provider() {
        let provider = NoOpExternalProvider;
        assert_eq!(
            provider.evaluate("MessageSplitting"),
            ConditionResult::Unknown
        );
        assert_eq!(provider.evaluate("anything"), ConditionResult::Unknown);
    }
}