automapper-validation 0.20.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
//! Conditions are evaluated in the scope of the group instance their field
//! belongs to, at every nesting level.
//!
//! The validator used to scope only the top-level group (the SG4), so "in
//! dieser SG8" could not be told apart from "in der Nachricht": 55043's [420]
//! ("RFF+Z14 in dieser SG8") saw another meter's Smartmeter-Gateway and
//! demanded `konfigurationsId` of an OBIS group without one.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use automapper_validation::eval::{
    ConditionEvaluator, ConditionResult, EvaluationContext, GroupScope, MapExternalProvider,
    NoOpExternalProvider,
};
use automapper_validation::validator::validate::{AhbFieldRule, AhbWorkflow};
use automapper_validation::{build_validated_tree, EdifactValidator, ValidationLevel};
use mig_assembly::assembler::{
    AssembledGroup, AssembledGroupInstance, AssembledSegment, AssembledTree,
};
use mig_assembly::navigator::AssembledTreeNavigator;
use mig_types::segment::OwnedSegment;

fn seg(tag: &str, mig: &str, elements: &[&[&str]]) -> AssembledSegment {
    AssembledSegment {
        tag: tag.to_string(),
        elements: elements
            .iter()
            .map(|e| e.iter().map(|c| c.to_string()).collect())
            .collect(),
        mig_number: Some(mig.to_string()),
        segment_number: None,
    }
}

fn instance(
    segments: Vec<AssembledSegment>,
    child_groups: Vec<AssembledGroup>,
) -> AssembledGroupInstance {
    AssembledGroupInstance {
        segments,
        child_groups,
        entry_mig_number: None,
        variant_mig_numbers: vec![],
        skipped_segments: vec![],
        skipped_positions: Vec::new(),
    }
}

fn group(id: &str, repetitions: Vec<AssembledGroupInstance>) -> AssembledGroup {
    AssembledGroup {
        group_id: id.to_string(),
        repetitions,
    }
}

/// SG4[0]: one meter SG8 (no SMGW).
/// SG4[1]: SG8[0] a meter without SMGW, SG8[1] a meter naming SMGW (RFF+Z14)
/// with an SG10 CCI.
fn tree() -> AssembledTree {
    let seq = || seg("SEQ", "001", &[&["Z03"]]);
    AssembledTree {
        segments: vec![],
        groups: vec![group(
            "SG4",
            vec![
                instance(
                    vec![seg("IDE", "000", &[&["24", "TX0"]])],
                    vec![group("SG8", vec![instance(vec![seq()], vec![])])],
                ),
                instance(
                    vec![seg("IDE", "000", &[&["24", "TX1"]])],
                    vec![group(
                        "SG8",
                        vec![
                            instance(vec![seq()], vec![]),
                            instance(
                                vec![seq(), seg("RFF", "002", &[&["Z14", "1ESG0000000018"]])],
                                vec![group(
                                    "SG10",
                                    vec![instance(
                                        vec![seg("CCI", "003", &[&[""], &[], &["E13"]])],
                                        vec![],
                                    )],
                                )],
                            ),
                        ],
                    )],
                ),
            ],
        )],
        post_group_start: 0,
        inter_group_segments: BTreeMap::new(),
    }
}

type Path = Vec<(String, usize)>;

/// Records the scope each condition is evaluated in; every condition holds.
#[derive(Default)]
struct RecordingEvaluator {
    seen: Arc<Mutex<Vec<(u32, Option<Path>)>>>,
}

impl ConditionEvaluator for RecordingEvaluator {
    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        let path = ctx
            .scope
            .map(|s| s.path.iter().map(|(id, i)| (id.to_string(), *i)).collect());
        self.seen.lock().unwrap().push((condition, path));
        ConditionResult::True
    }
    fn is_external(&self, _: u32) -> bool {
        false
    }
    fn message_type(&self) -> &str {
        "UTILMD"
    }
    fn format_version(&self) -> &str {
        "FV2604"
    }
}

fn rule(path: &str, status: &str, mig: &str) -> AhbFieldRule {
    AhbFieldRule {
        segment_path: path.to_string(),
        name: path.to_string(),
        ahb_status: status.to_string(),
        element_index: Some(0),
        component_index: Some(0),
        mig_number: Some(mig.to_string()),
        ..Default::default()
    }
}

fn p(steps: &[(&str, usize)]) -> Option<Path> {
    Some(steps.iter().map(|(id, i)| (id.to_string(), *i)).collect())
}

#[test]
fn each_field_is_evaluated_in_its_own_nested_instance() {
    let tree = tree();
    let workflow = AhbWorkflow {
        pruefidentifikator: "55043".to_string(),
        description: String::new(),
        communication_direction: None,
        fields: vec![
            rule("SG4/SG8/SEQ/1229", "Muss [1]", "001"),
            rule("SG4/SG8/SG10/CCI/7059", "Muss [2]", "003"),
        ],
        ub_definitions: BTreeMap::new(),
    };
    let validated = build_validated_tree(&workflow, &tree);
    let evaluator = RecordingEvaluator::default();
    let seen = Arc::clone(&evaluator.seen);
    let validator = EdifactValidator::new(evaluator);
    let navigator = AssembledTreeNavigator::new(&tree);
    validator.validate_tree(
        &validated,
        &[],
        &NoOpExternalProvider,
        ValidationLevel::Conditions,
        Some(&navigator),
    );

    let seen = seen.lock().unwrap().clone();
    let scopes_of = |condition: u32| -> Vec<Option<Path>> {
        seen.iter()
            .filter(|(c, _)| *c == condition)
            .map(|(_, path)| path.clone())
            .collect()
    };
    assert_eq!(
        scopes_of(1),
        [
            p(&[("SG4", 0), ("SG8", 0)]),
            p(&[("SG4", 1), ("SG8", 0)]),
            p(&[("SG4", 1), ("SG8", 1)]),
        ]
    );
    assert_eq!(scopes_of(2), [p(&[("SG4", 1), ("SG8", 1), ("SG10", 0)])]);
}

#[test]
fn a_condition_reads_the_enclosing_instance_of_the_group_it_names() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    // The flat message, for lookups that fall back to message-wide.
    let flat = [OwnedSegment {
        id: "RFF".to_string(),
        elements: vec![vec!["Z14".to_string(), "1ESG0000000018".to_string()]],
        segment_number: 7,
    }];
    let ctx = EvaluationContext::with_navigator("55043", &external, &flat, &navigator);
    let rff_z14 = |ctx: &EvaluationContext, group: &str| {
        ctx.scoped_find_segments_in(group, "RFF")
            .iter()
            .any(|s| s.get_element(0) == "Z14")
    };

    // An SG10 field asking about "dieser SG8" sees its own SG8's RFF+Z14 ...
    let in_sg10 = [("SG4", 1), ("SG8", 1), ("SG10", 0)];
    assert!(rff_z14(
        &ctx.with_scope(GroupScope { path: &in_sg10 }),
        "SG8"
    ));
    // ... and a meter's SG8 without one does not see the other meter's.
    let other_meter = [("SG4", 1), ("SG8", 0)];
    assert!(!rff_z14(
        &ctx.with_scope(GroupScope { path: &other_meter }),
        "SG8"
    ));
    let other_transaction = [("SG4", 0), ("SG8", 0)];
    assert!(!rff_z14(
        &ctx.with_scope(GroupScope {
            path: &other_transaction
        }),
        "SG8"
    ));

    // The current instance includes its nested groups: the SG8 sees its SG10's CCI.
    let meter = [("SG4", 1), ("SG8", 1)];
    assert_eq!(
        ctx.with_scope(GroupScope { path: &meter })
            .scoped_find_segments("CCI")
            .len(),
        1
    );

    // No enclosing SG8 (a transaction-level field): the whole message, as unscoped.
    let transaction = [("SG4", 0)];
    assert!(rff_z14(
        &ctx.with_scope(GroupScope { path: &transaction }),
        "SG8"
    ));
}

#[test]
fn a_qualified_lookup_reads_the_enclosing_instance_too() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    let ctx = EvaluationContext::with_navigator("55043", &external, &[], &navigator);
    let z14 = |path: &[(&str, usize)]| {
        ctx.with_scope(GroupScope { path })
            .scoped_find_segments_in_with_qualifier("SG8", "RFF", 0, "Z14")
            .len()
    };
    assert_eq!(z14(&[("SG4", 1), ("SG8", 1), ("SG10", 0)]), 1);
    assert_eq!(z14(&[("SG4", 1), ("SG8", 0)]), 0);
}

/// The `this_group_*` helpers read the enclosing instance of the group their
/// path names ("in dieser SG8"), and fall back to their `any_group_*`
/// counterparts without a scope reaching it.
#[test]
fn this_group_helpers_read_the_enclosing_instance() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    let flat = [OwnedSegment {
        id: "RFF".to_string(),
        elements: vec![vec!["Z14".to_string(), "1ESG0000000018".to_string()]],
        segment_number: 7,
    }];
    let ctx = EvaluationContext::with_navigator("55043", &external, &flat, &navigator);
    let in_scope = |path: &[(&str, usize)]| {
        let scoped = ctx.with_scope(GroupScope { path });
        (
            scoped.this_group_has_qualifier("RFF", 0, "Z14", &["SG4", "SG8"]),
            scoped.this_group_has_any_qualifier("RFF", 0, &["Z14", "Z15"], &["SG8"]),
            scoped.this_group_has_qualified_value(
                "RFF",
                0,
                "Z14",
                0,
                1,
                &["1ESG0000000018"],
                &["SG8"],
            ),
            scoped.this_group_values("RFF", 0, 1, &["SG8"]),
        )
    };
    let with_smgw = in_scope(&[("SG4", 1), ("SG8", 1), ("SG10", 0)]);
    assert_eq!(
        (with_smgw.0, with_smgw.1, with_smgw.2),
        (
            ConditionResult::True,
            ConditionResult::True,
            ConditionResult::True
        )
    );
    assert_eq!(with_smgw.3, vec![(0, "1ESG0000000018".to_string())]);
    let without = in_scope(&[("SG4", 1), ("SG8", 0)]);
    assert_eq!(
        (without.0, without.1, without.2),
        (
            ConditionResult::False,
            ConditionResult::False,
            ConditionResult::False
        )
    );
    assert!(without.3.is_empty());
    // No SG8 in the scope: the `any_group_*` answer (here: the flat message).
    assert_eq!(
        ctx.with_scope(GroupScope {
            path: &[("SG4", 0)]
        })
        .this_group_has_qualifier("RFF", 0, "Z14", &["SG8"]),
        ctx.any_group_has_qualifier("RFF", 0, "Z14", &["SG8"])
    );
}

/// Scoped counterparts of `any_group_has_qualifier_without` ("in derselben
/// SG8 … nicht vorhanden", UTILMD [316]) and `filtered_parent_child_has_qualifier`
/// ("in dieser SG8 SEQ+… SG10 CCI…", [106]): the enclosing SG8 only.
#[test]
fn scoped_pattern_helpers_read_the_enclosing_instance() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    let ctx = EvaluationContext::with_navigator("55043", &external, &[], &navigator);
    let in_sg8 = |i: usize| [("SG4", 1), ("SG8", i)];

    let without = |path: &[(&str, usize)]| {
        ctx.with_scope(GroupScope { path })
            .this_group_has_qualifier_without("SEQ", 0, "Z03", "RFF", 0, "Z14", &["SG4", "SG8"])
    };
    assert_eq!(
        without(&in_sg8(0)),
        ConditionResult::True,
        "a meter without SMGW"
    );
    assert_eq!(
        without(&in_sg8(1)),
        ConditionResult::False,
        "the meter naming one"
    );

    let parent_child = |path: &[(&str, usize)]| {
        ctx.with_scope(GroupScope { path })
            .this_group_parent_child_has_qualifier(
                &["SG4", "SG8"],
                "SEQ",
                0,
                "Z03",
                "SG10",
                "CCI",
                2,
                "E13",
            )
    };
    assert_eq!(parent_child(&in_sg8(1)), ConditionResult::True);
    assert_eq!(parent_child(&in_sg8(0)), ConditionResult::False);

    let deep = [("SG4", 1), ("SG8", 1), ("SG10", 0)];
    assert_eq!(
        ctx.with_scope(GroupScope { path: &deep })
            .enclosing_scope("SG8"),
        Some(&deep[..2])
    );
}

/// The child groups of the enclosing instance, each with its segments: "SG10
/// CCI+++E13 CAV+EHZ in dieser SG8" pairs a CCI and a CAV of one SG10.
#[test]
fn the_child_groups_of_the_enclosing_instance() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    let ctx = EvaluationContext::with_navigator("55043", &external, &[], &navigator);
    let sg10s = |path: &[(&str, usize)]| {
        ctx.with_scope(GroupScope { path })
            .enclosing_child_segments("SG8", "SG10", &["CCI", "CAV"])
            .map(|groups| {
                groups
                    .iter()
                    .map(|segs| segs.iter().map(|s| s.id.clone()).collect::<Vec<_>>())
                    .collect::<Vec<_>>()
            })
    };
    assert_eq!(
        sg10s(&[("SG4", 1), ("SG8", 1), ("SG10", 0)]),
        Some(vec![vec!["CCI".to_string()]])
    );
    assert_eq!(sg10s(&[("SG4", 1), ("SG8", 0)]), Some(vec![]));
    assert_eq!(sg10s(&[("SG4", 1)]), None, "no enclosing SG8");
}

/// Every instance of a group under the enclosing parent — "eine SG8 SEQ+Z01"
/// asked from one SG8 (or SG6) of an SG4 — and the child groups at any path.
#[test]
fn the_instances_under_the_enclosing_parent() {
    let tree = tree();
    let navigator = AssembledTreeNavigator::new(&tree);
    let external = MapExternalProvider::new(Default::default());
    let ctx = EvaluationContext::with_navigator("55043", &external, &[], &navigator);
    let under = |path: &[(&str, usize)]| {
        ctx.with_scope(GroupScope { path })
            .scopes_under("SG4", "SG8")
            .map(|paths| {
                paths
                    .iter()
                    .map(|p| {
                        p.iter()
                            .map(|(id, i)| format!("{id}:{i}"))
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>()
            })
    };
    assert_eq!(
        under(&[("SG4", 1), ("SG8", 1), ("SG10", 0)]),
        Some(vec![
            vec!["SG4:1".to_string(), "SG8:0".to_string()],
            vec!["SG4:1".to_string(), "SG8:1".to_string()],
        ])
    );
    assert_eq!(
        under(&[("SG4", 0)]),
        Some(vec![vec!["SG4:0".to_string(), "SG8:0".to_string()]])
    );
    assert_eq!(under(&[]), None, "no enclosing SG4");

    let ids = |groups: Vec<Vec<OwnedSegment>>| {
        groups
            .iter()
            .map(|segs| segs.iter().map(|s| s.id.clone()).collect::<Vec<_>>())
            .collect::<Vec<_>>()
    };
    assert_eq!(
        ids(ctx.child_segments_at(&[("SG4", 1), ("SG8", 1)], "SG10", &["CCI", "CAV"])),
        vec![vec!["CCI".to_string()]]
    );
    assert!(ctx
        .child_segments_at(&[("SG4", 1), ("SG8", 0)], "SG10", &["CCI"])
        .is_empty());
}