automapper-validation 0.1.53

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
//! Format validation helpers for AHB 900-series conditions.
//!
//! These validate the FORMAT of data element values (decimal places, numeric ranges,
//! time patterns, ID formats, etc.). They operate on string values extracted from
//! EDIFACT segments and return `ConditionResult`.

use super::evaluator::ConditionResult;

// Re-export timezone helpers so generated code can use `use crate::eval::format_validators::*`
pub use super::timezone::{is_mesz_utc, is_mez_utc};

// --- Decimal/digit place validation ---

/// Validate that a numeric string has at most `max` decimal places.
///
/// Returns `True` if the value has <= max decimal places (or no decimal point),
/// `False` if it has more, `Unknown` if the value is empty.
///
/// Example: `validate_max_decimal_places("123.45", 2)` → True
/// Example: `validate_max_decimal_places("123.456", 2)` → False
/// Example: `validate_max_decimal_places("123", 2)` → True (no decimal → 0 places)
pub fn validate_max_decimal_places(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let decimal_places = match value.find('.') {
        Some(pos) => value.len() - pos - 1,
        None => 0,
    };
    ConditionResult::from(decimal_places <= max)
}

/// Validate that a numeric string has at most `max` integer digits (before decimal point).
///
/// Ignores leading minus sign.
pub fn validate_max_integer_digits(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let s = value.strip_prefix('-').unwrap_or(value);
    let integer_part = match s.find('.') {
        Some(pos) => &s[..pos],
        None => s,
    };
    ConditionResult::from(integer_part.len() <= max)
}

// --- Numeric range validation ---

/// Validate a numeric value against a comparison.
///
/// `op` is one of: "==", "!=", ">", ">=", "<", "<="
/// Returns `Unknown` if the value cannot be parsed as a number.
///
/// Example: `validate_numeric(value, ">=", 0.0)` for "Wert >= 0"
/// Example: `validate_numeric(value, "==", 1.0)` for "Wert = 1"
pub fn validate_numeric(value: &str, op: &str, threshold: f64) -> ConditionResult {
    let parsed = match value.parse::<f64>() {
        Ok(v) => v,
        Err(_) => return ConditionResult::Unknown,
    };
    let result = match op {
        "==" => (parsed - threshold).abs() < f64::EPSILON,
        "!=" => (parsed - threshold).abs() >= f64::EPSILON,
        ">" => parsed > threshold,
        ">=" => parsed >= threshold,
        "<" => parsed < threshold,
        "<=" => parsed <= threshold,
        _ => return ConditionResult::Unknown,
    };
    ConditionResult::from(result)
}

// --- DTM time/timezone validation ---

/// Validate that a DTM value's HHMM portion equals the expected value.
///
/// DTM format 303 is CCYYMMDDHHMM (12 chars) or CCYYMMDDHHMMZZZ (15 chars with timezone).
/// Extracts characters at positions 8..12 (HHMM) for comparison.
///
/// Example: `validate_hhmm_equals("202601012200+00", "2200")` → True
pub fn validate_hhmm_equals(dtm_value: &str, expected_hhmm: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        // Value too short — no HHMM component present, condition is not met
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[8..12] == expected_hhmm)
}

/// Validate that a DTM value's HHMM portion is within a range (inclusive).
///
/// Example: `validate_hhmm_range("202601011530+00", "0000", "2359")` → True
pub fn validate_hhmm_range(dtm_value: &str, min: &str, max: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        return ConditionResult::False;
    }
    let hhmm = &dtm_value[8..12];
    ConditionResult::from(hhmm >= min && hhmm <= max)
}

/// Validate that a DTM value's MMDDHHMM portion equals the expected value.
///
/// Extracts characters at positions 4..12 for comparison.
///
/// Example: `validate_mmddhhmm_equals("202612312300+00", "12312300")` → True
pub fn validate_mmddhhmm_equals(dtm_value: &str, expected: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[4..12] == expected)
}

/// Validate that a DTM value's timezone portion is "+00" (UTC).
///
/// DTM format 303 with timezone: CCYYMMDDHHMM+ZZ or CCYYMMDDHHMM-ZZ (15 chars).
/// Checks that the last 3 characters are "+00".
///
/// Example: `validate_timezone_utc("202601012200+00")` → True
/// Example: `validate_timezone_utc("202601012200+01")` → False
pub fn validate_timezone_utc(dtm_value: &str) -> ConditionResult {
    if dtm_value.len() < 15 {
        // Value too short — no timezone suffix present, condition is not met
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[12..] == "+00")
}

// --- Contact format validation ---

/// Validate email format: must contain both '@' and '.'.
///
/// Example: `validate_email("user@example.com")` → True
pub fn validate_email(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.contains('@') && value.contains('.'))
}

/// Validate phone format: must start with '+' followed by only digits.
///
/// Example: `validate_phone("+4930123456")` → True
/// Example: `validate_phone("030123456")` → False
pub fn validate_phone(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    if !value.starts_with('+') || value.len() < 2 {
        return ConditionResult::from(false);
    }
    ConditionResult::from(value[1..].chars().all(|c| c.is_ascii_digit()))
}

// --- ID format validation ---

/// Validate Marktlokations-ID (MaLo-ID): exactly 11 digits with BDEW check digit.
///
/// This is **not** standard Luhn — per the BDEW "Anwendungshilfe MaLo-ID v1.0" spec
/// and the Hochfrequenz BO4E-dotnet reference implementation
/// (`BO4E/BO/Marktlokation.cs::GetChecksum`), digits 1–10 are numbered left-to-right
/// (1-based), digits at even positions are multiplied by 2 and **added as the full
/// value** (no digit-sum, no mod-by-9 step), digits at odd positions are added as-is.
/// Check digit = `(10 - (sum mod 10)) mod 10`.
///
/// Example: `"51238696781"` — odd (1,3,5,7,9): 5+2+8+9+7=31; even doubled
/// (2,4,6,8,10): 2*(1+3+6+6+8)=48; sum=79; check = (10-79%10)%10 = 1 ✓.
pub fn validate_malo_id(value: &str) -> ConditionResult {
    if value.len() != 11 {
        return ConditionResult::from(false);
    }
    if !value.chars().all(|c| c.is_ascii_digit()) {
        return ConditionResult::from(false);
    }
    let digits: Vec<u32> = value.chars().filter_map(|c| c.to_digit(10)).collect();
    let check = digits[10];
    let mut sum = 0u32;
    for (i, &d) in digits[..10].iter().enumerate() {
        // 1-based position is i+1; even positions are doubled, odd positions as-is.
        if (i + 1) % 2 == 0 {
            sum += 2 * d;
        } else {
            sum += d;
        }
    }
    let expected = (10 - (sum % 10)) % 10;
    ConditionResult::from(check == expected)
}

/// Validate Transaktionsreferenz-ID (TR-ID): 1-35 alphanumeric characters.
pub fn validate_tr_id(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() <= 35 && value.chars().all(|c| c.is_ascii_alphanumeric()))
}

/// Validate Steuerbare-Ressource-ID (SR-ID): same format as MaLo-ID (11 digits, Luhn check).
pub fn validate_sr_id(value: &str) -> ConditionResult {
    validate_malo_id(value)
}

/// Validate Zahlpunktbezeichnung: exactly 33 alphanumeric characters.
pub fn validate_zahlpunkt(value: &str) -> ConditionResult {
    if value.len() != 33 {
        return ConditionResult::from(false);
    }
    ConditionResult::from(value.chars().all(|c| c.is_ascii_alphanumeric()))
}

/// Validate either MaLo-ID or Zahlpunktbezeichnung format.
pub fn validate_malo_or_zahlpunkt(value: &str) -> ConditionResult {
    if value.len() == 11 && validate_malo_id(value).is_true() {
        return ConditionResult::True;
    }
    if value.len() == 33 && validate_zahlpunkt(value).is_true() {
        return ConditionResult::True;
    }
    ConditionResult::False
}

// --- Artikelnummer pattern validation ---

/// Validate a dash-separated digit pattern like "n1-n2-n1-n3".
///
/// `segment_lengths` defines expected digit counts per dash-separated segment.
///
/// Example: `validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3])` → True
/// Example: `validate_artikel_pattern("1-23-4", &[1, 2, 1])` → True
pub fn validate_artikel_pattern(value: &str, segment_lengths: &[usize]) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let parts: Vec<&str> = value.split('-').collect();
    if parts.len() != segment_lengths.len() {
        return ConditionResult::from(false);
    }
    let valid = parts
        .iter()
        .zip(segment_lengths.iter())
        .all(|(part, &expected_len)| {
            part.len() == expected_len && part.chars().all(|c| c.is_ascii_digit())
        });
    ConditionResult::from(valid)
}

// --- General string validation ---

/// Validate exact character length.
pub fn validate_exact_length(value: &str, expected: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() == expected)
}

/// Validate maximum character length.
pub fn validate_max_length(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() <= max)
}

/// Validate that a string contains only digits (positive integer check).
pub fn validate_all_digits(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.chars().all(|c| c.is_ascii_digit()))
}

/// Current UTC date+time as a CCYYMMDDHHMM string (12 chars).
pub fn utc_now_ccyymmddhhmm() -> String {
    chrono::Utc::now().format("%Y%m%d%H%M").to_string()
}

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

    // --- Decimal places ---

    #[test]
    fn test_max_decimal_places() {
        assert_eq!(
            validate_max_decimal_places("123.45", 2),
            ConditionResult::True
        );
        assert_eq!(
            validate_max_decimal_places("123.456", 2),
            ConditionResult::False
        );
        assert_eq!(validate_max_decimal_places("123", 2), ConditionResult::True);
        assert_eq!(validate_max_decimal_places("0.1", 3), ConditionResult::True);
        assert_eq!(validate_max_decimal_places("", 2), ConditionResult::Unknown);
    }

    #[test]
    fn test_no_decimal_places() {
        assert_eq!(validate_max_decimal_places("100", 0), ConditionResult::True);
        assert_eq!(
            validate_max_decimal_places("100.5", 0),
            ConditionResult::False
        );
    }

    #[test]
    fn test_max_integer_digits() {
        assert_eq!(
            validate_max_integer_digits("1234", 4),
            ConditionResult::True
        );
        assert_eq!(
            validate_max_integer_digits("12345", 4),
            ConditionResult::False
        );
        assert_eq!(
            validate_max_integer_digits("-123.45", 4),
            ConditionResult::True
        );
        assert_eq!(validate_max_integer_digits("", 4), ConditionResult::Unknown);
    }

    // --- Numeric range ---

    #[test]
    fn test_validate_numeric() {
        assert_eq!(validate_numeric("5.0", ">=", 0.0), ConditionResult::True);
        assert_eq!(validate_numeric("-1.0", ">=", 0.0), ConditionResult::False);
        assert_eq!(validate_numeric("1", "==", 1.0), ConditionResult::True);
        assert_eq!(validate_numeric("2", "==", 1.0), ConditionResult::False);
        assert_eq!(validate_numeric("0", ">", 0.0), ConditionResult::False);
        assert_eq!(validate_numeric("1", ">", 0.0), ConditionResult::True);
        assert_eq!(validate_numeric("abc", ">=", 0.0), ConditionResult::Unknown);
    }

    // --- DTM validation ---

    #[test]
    fn test_hhmm_equals() {
        assert_eq!(
            validate_hhmm_equals("202601012200+00", "2200"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_equals("202601012300+00", "2200"),
            ConditionResult::False
        );
        assert_eq!(
            validate_hhmm_equals("short", "2200"),
            ConditionResult::False
        );
    }

    #[test]
    fn test_hhmm_range() {
        assert_eq!(
            validate_hhmm_range("202601011530+00", "0000", "2359"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_range("202601010000+00", "0000", "2359"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_range("202601012359+00", "0000", "2359"),
            ConditionResult::True
        );
    }

    #[test]
    fn test_mmddhhmm_equals() {
        assert_eq!(
            validate_mmddhhmm_equals("202612312300+00", "12312300"),
            ConditionResult::True
        );
        assert_eq!(
            validate_mmddhhmm_equals("202601012200+00", "12312300"),
            ConditionResult::False
        );
    }

    #[test]
    fn test_timezone_utc() {
        assert_eq!(
            validate_timezone_utc("202601012200+00"),
            ConditionResult::True
        );
        assert_eq!(
            validate_timezone_utc("202601012200+01"),
            ConditionResult::False
        );
        assert_eq!(
            validate_timezone_utc("202601012200"),
            ConditionResult::False
        );
    }

    // --- Contact validation ---

    #[test]
    fn test_email() {
        assert_eq!(validate_email("user@example.com"), ConditionResult::True);
        assert_eq!(validate_email("nope"), ConditionResult::False);
        assert_eq!(validate_email("has@but-no-dot"), ConditionResult::False);
        assert_eq!(validate_email(""), ConditionResult::Unknown);
    }

    #[test]
    fn test_phone() {
        assert_eq!(validate_phone("+4930123456"), ConditionResult::True);
        assert_eq!(validate_phone("030123456"), ConditionResult::False);
        assert_eq!(validate_phone("+"), ConditionResult::False);
        assert_eq!(validate_phone("+49 30 123"), ConditionResult::False); // spaces not allowed
        assert_eq!(validate_phone(""), ConditionResult::Unknown);
    }

    // --- ID validation ---

    #[test]
    fn test_malo_id() {
        // Valid MaLo-IDs — taken directly from the BO4E-dotnet reference test
        // suite (TestBO4E/TestMaLoMeLoId.cs), which uses the BDEW MaLo-ID spec
        // (no digit-sum on doubled products; see `validate_malo_id` docstring).
        assert_eq!(validate_malo_id("51238696781"), ConditionResult::True);
        assert_eq!(validate_malo_id("41373559241"), ConditionResult::True);
        assert_eq!(validate_malo_id("56789012345"), ConditionResult::True);
        assert_eq!(validate_malo_id("52935155442"), ConditionResult::True);

        // Negative cases from the same reference tests.
        assert_eq!(validate_malo_id("41373559240"), ConditionResult::False); // wrong check digit
        assert_eq!(validate_malo_id("512386967890"), ConditionResult::False); // 12 digits
        assert_eq!(validate_malo_id("1234567890"), ConditionResult::False); // too short
        assert_eq!(validate_malo_id("abcdefghijk"), ConditionResult::False); // not digits
    }

    #[test]
    fn test_zahlpunkt() {
        let valid = "DE0001234567890123456789012345678";
        assert_eq!(valid.len(), 33);
        assert_eq!(validate_zahlpunkt(valid), ConditionResult::True);
        assert_eq!(validate_zahlpunkt("tooshort"), ConditionResult::False);
    }

    // --- Artikelnummer pattern ---

    #[test]
    fn test_artikel_pattern() {
        assert_eq!(
            validate_artikel_pattern("1-23-4", &[1, 2, 1]),
            ConditionResult::True
        );
        assert_eq!(
            validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3]),
            ConditionResult::True
        );
        assert_eq!(
            validate_artikel_pattern("1-23-4-56", &[1, 2, 1, 3]),
            ConditionResult::False
        );
        assert_eq!(
            validate_artikel_pattern("1-AB-4", &[1, 2, 1]),
            ConditionResult::False
        );
        assert_eq!(
            validate_artikel_pattern("", &[1, 2, 1]),
            ConditionResult::Unknown
        );
    }

    // --- TR-ID / SR-ID validation ---

    #[test]
    fn test_tr_id() {
        assert_eq!(validate_tr_id("ABC123"), ConditionResult::True);
        assert_eq!(validate_tr_id("A"), ConditionResult::True);
        assert_eq!(validate_tr_id(&"A".repeat(35)), ConditionResult::True);
        assert_eq!(validate_tr_id(&"A".repeat(36)), ConditionResult::False);
        assert_eq!(validate_tr_id("has spaces"), ConditionResult::False);
        assert_eq!(validate_tr_id("has-dash"), ConditionResult::False);
        assert_eq!(validate_tr_id(""), ConditionResult::Unknown);
    }

    #[test]
    fn test_sr_id() {
        // SR-ID uses the same BDEW 11-digit check format as MaLo-ID; reuse
        // the reference-suite valid example from BO4E-dotnet tests.
        assert_eq!(validate_sr_id("51238696781"), ConditionResult::True);
        assert_eq!(validate_sr_id("41373559240"), ConditionResult::False);
        assert_eq!(validate_sr_id("1234567890"), ConditionResult::False);
        assert_eq!(validate_sr_id(""), ConditionResult::False);
    }

    // --- String validation ---

    #[test]
    fn test_exact_length() {
        assert_eq!(
            validate_exact_length("1234567890123456", 16),
            ConditionResult::True
        );
        assert_eq!(validate_exact_length("123", 16), ConditionResult::False);
        assert_eq!(validate_exact_length("", 16), ConditionResult::Unknown);
    }

    #[test]
    fn test_all_digits() {
        assert_eq!(validate_all_digits("12345"), ConditionResult::True);
        assert_eq!(validate_all_digits("123a5"), ConditionResult::False);
        assert_eq!(validate_all_digits(""), ConditionResult::Unknown);
    }
}