automapper-validation 0.22.2

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
//! 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],
        _ => &[],
    }
}

/// 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 {
    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;
    }
    let present = PresentTarget(evaluator);
    super::ConditionExprEvaluator::new(&present).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 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);
    }
}