Skip to main content

automapper_validation/eval/
format_validators.rs

1//! Format validation helpers for AHB 900-series conditions.
2//!
3//! These validate the FORMAT of data element values (decimal places, numeric ranges,
4//! time patterns, ID formats, etc.). They operate on string values extracted from
5//! EDIFACT segments and return `ConditionResult`.
6
7use super::evaluator::ConditionResult;
8
9// Re-export timezone helpers so generated code can use `use crate::eval::format_validators::*`
10pub use super::timezone::{dst_transitions_between, is_mesz_utc, is_mez_utc, parse_dtm303};
11pub use super::werktag::{
12    compute_easter, is_german_holiday, is_werktag, parse_ccyymmdd_prefix, werktage_between,
13};
14
15// --- Decimal/digit place validation ---
16
17/// Validate that a numeric string has at most `max` decimal places.
18///
19/// Returns `True` if the value has <= max decimal places (or no decimal point),
20/// `False` if it has more, `Unknown` if the value is empty.
21///
22/// Example: `validate_max_decimal_places("123.45", 2)` → True
23/// Example: `validate_max_decimal_places("123.456", 2)` → False
24/// Example: `validate_max_decimal_places("123", 2)` → True (no decimal → 0 places)
25pub fn validate_max_decimal_places(value: &str, max: usize) -> ConditionResult {
26    if value.is_empty() {
27        return ConditionResult::Unknown;
28    }
29    let decimal_places = match value.find('.') {
30        Some(pos) => value.len() - pos - 1,
31        None => 0,
32    };
33    ConditionResult::from(decimal_places <= max)
34}
35
36/// Validate that a numeric string has at most `max` integer digits (before decimal point).
37///
38/// Ignores leading minus sign.
39pub fn validate_max_integer_digits(value: &str, max: usize) -> ConditionResult {
40    if value.is_empty() {
41        return ConditionResult::Unknown;
42    }
43    let s = value.strip_prefix('-').unwrap_or(value);
44    let integer_part = match s.find('.') {
45        Some(pos) => &s[..pos],
46        None => s,
47    };
48    ConditionResult::from(integer_part.len() <= max)
49}
50
51// --- Numeric range validation ---
52
53/// Validate a numeric value against a comparison.
54///
55/// `op` is one of: "==", "!=", ">", ">=", "<", "<="
56/// An EDIFACT number is an optional sign, digits and at most one decimal mark
57/// (`.` or `,`, which the UNA may set). Anything else is no possible value and
58/// fails (`O5D2DXBG1A` is not "> 0"); only an empty value is `Unknown`.
59///
60/// Example: `validate_numeric(value, ">=", 0.0)` for "Wert >= 0"
61/// Example: `validate_numeric(value, "==", 1.0)` for "Wert = 1"
62pub fn validate_numeric(value: &str, op: &str, threshold: f64) -> ConditionResult {
63    if value.is_empty() {
64        return ConditionResult::Unknown;
65    }
66    let parsed = match edifact_number(value) {
67        Some(v) => v,
68        None => return ConditionResult::False,
69    };
70    let result = match op {
71        "==" => (parsed - threshold).abs() < f64::EPSILON,
72        "!=" => (parsed - threshold).abs() >= f64::EPSILON,
73        ">" => parsed > threshold,
74        ">=" => parsed >= threshold,
75        "<" => parsed < threshold,
76        "<=" => parsed <= threshold,
77        _ => return ConditionResult::Unknown,
78    };
79    ConditionResult::from(result)
80}
81
82/// Whether `value` is an EDIFACT number — what a data element of numeric
83/// format (`n..10`) may hold: an optional minus sign, at least one digit, and
84/// at most one decimal mark (`.` or `,`).
85pub fn is_edifact_number(value: &str) -> bool {
86    edifact_number(value).is_some()
87}
88
89/// `value` as an EDIFACT number: an optional sign, at least one digit, and at
90/// most one decimal mark (`.` or `,`). `None` for anything else (`1e3`, `NaN`).
91fn edifact_number(value: &str) -> Option<f64> {
92    let unsigned = value.strip_prefix('-').unwrap_or(value);
93    let mut marks = 0;
94    let mut digits = 0;
95    for c in unsigned.chars() {
96        match c {
97            '0'..='9' => digits += 1,
98            '.' | ',' => marks += 1,
99            _ => return None,
100        }
101    }
102    if digits == 0 || marks > 1 {
103        return None;
104    }
105    value.replace(',', ".").parse().ok()
106}
107
108// --- DTM time/timezone validation ---
109
110/// Validate that a DTM value's HHMM portion equals the expected value.
111///
112/// DTM format 303 is CCYYMMDDHHMM (12 chars) or CCYYMMDDHHMMZZZ (15 chars with timezone).
113/// Extracts characters at positions 8..12 (HHMM) for comparison.
114///
115/// Example: `validate_hhmm_equals("202601012200+00", "2200")` → True
116pub fn validate_hhmm_equals(dtm_value: &str, expected_hhmm: &str) -> ConditionResult {
117    if dtm_value.len() < 12 {
118        // Value too short — no HHMM component present, condition is not met
119        return ConditionResult::False;
120    }
121    ConditionResult::from(&dtm_value[8..12] == expected_hhmm)
122}
123
124/// Validate that a DTM value's HHMM portion is within a range (inclusive).
125///
126/// Example: `validate_hhmm_range("202601011530+00", "0000", "2359")` → True
127pub fn validate_hhmm_range(dtm_value: &str, min: &str, max: &str) -> ConditionResult {
128    if dtm_value.len() < 12 {
129        return ConditionResult::False;
130    }
131    let hhmm = &dtm_value[8..12];
132    ConditionResult::from(hhmm >= min && hhmm <= max)
133}
134
135/// Validate that a DTM value's MMDDHHMM portion equals the expected value.
136///
137/// Extracts characters at positions 4..12 for comparison.
138///
139/// Example: `validate_mmddhhmm_equals("202612312300+00", "12312300")` → True
140pub fn validate_mmddhhmm_equals(dtm_value: &str, expected: &str) -> ConditionResult {
141    if dtm_value.len() < 12 {
142        return ConditionResult::False;
143    }
144    ConditionResult::from(&dtm_value[4..12] == expected)
145}
146
147/// Validate that a DTM value's timezone portion ZZZ is "+00" (UTC).
148///
149/// The zone is the value's last three characters: format 303
150/// `CCYYMMDDHHMMZZZ` (15 chars) and 304 `CCYYMMDDHHMMSSZZZ` (17 chars) both
151/// end in it. Reading it at a fixed offset of 12 took 304's seconds for the
152/// zone and failed every 304 value.
153///
154/// Example: `validate_timezone_utc("202601012200+00")` → True
155/// Example: `validate_timezone_utc("20260101220000+00")` → True
156/// Example: `validate_timezone_utc("202601012200+01")` → False
157pub fn validate_timezone_utc(dtm_value: &str) -> ConditionResult {
158    if dtm_value.len() < 15 || !dtm_value.is_char_boundary(dtm_value.len() - 3) {
159        // Value too short — no timezone suffix present, condition is not met
160        return ConditionResult::False;
161    }
162    ConditionResult::from(&dtm_value[dtm_value.len() - 3..] == "+00")
163}
164
165// --- Contact format validation ---
166
167/// Validate email format: must contain both '@' and '.'.
168///
169/// Example: `validate_email("user@example.com")` → True
170pub fn validate_email(value: &str) -> ConditionResult {
171    if value.is_empty() {
172        return ConditionResult::Unknown;
173    }
174    ConditionResult::from(value.contains('@') && value.contains('.'))
175}
176
177/// Validate phone format: must start with '+' followed by only digits.
178///
179/// Example: `validate_phone("+4930123456")` → True
180/// Example: `validate_phone("030123456")` → False
181pub fn validate_phone(value: &str) -> ConditionResult {
182    if value.is_empty() {
183        return ConditionResult::Unknown;
184    }
185    if !value.starts_with('+') || value.len() < 2 {
186        return ConditionResult::from(false);
187    }
188    ConditionResult::from(value[1..].chars().all(|c| c.is_ascii_digit()))
189}
190
191// --- ID format validation ---
192
193/// Validate Marktlokations-ID (MaLo-ID): exactly 11 digits with BDEW check digit.
194///
195/// This is **not** standard Luhn — per the BDEW "Anwendungshilfe MaLo-ID v1.0" spec
196/// and the Hochfrequenz BO4E-dotnet reference implementation
197/// (`BO4E/BO/Marktlokation.cs::GetChecksum`), digits 1–10 are numbered left-to-right
198/// (1-based), digits at even positions are multiplied by 2 and **added as the full
199/// value** (no digit-sum, no mod-by-9 step), digits at odd positions are added as-is.
200/// Check digit = `(10 - (sum mod 10)) mod 10`.
201///
202/// Example: `"51238696781"` — odd (1,3,5,7,9): 5+2+8+9+7=31; even doubled
203/// (2,4,6,8,10): 2*(1+3+6+6+8)=48; sum=79; check = (10-79%10)%10 = 1 ✓.
204pub fn validate_malo_id(value: &str) -> ConditionResult {
205    if value.len() != 11 {
206        return ConditionResult::from(false);
207    }
208    if !value.chars().all(|c| c.is_ascii_digit()) {
209        return ConditionResult::from(false);
210    }
211    let digits: Vec<u32> = value.chars().filter_map(|c| c.to_digit(10)).collect();
212    let check = digits[10];
213    let mut sum = 0u32;
214    for (i, &d) in digits[..10].iter().enumerate() {
215        // 1-based position is i+1; even positions are doubled, odd positions as-is.
216        if (i + 1) % 2 == 0 {
217            sum += 2 * d;
218        } else {
219            sum += d;
220        }
221    }
222    let expected = (10 - (sum % 10)) % 10;
223    ConditionResult::from(check == expected)
224}
225
226/// Validate Transaktionsreferenz-ID (TR-ID): 1-35 alphanumeric characters.
227pub fn validate_tr_id(value: &str) -> ConditionResult {
228    if value.is_empty() {
229        return ConditionResult::Unknown;
230    }
231    ConditionResult::from(value.len() <= 35 && value.chars().all(|c| c.is_ascii_alphanumeric()))
232}
233
234/// A BDEW location ID of the lettered kind: `prefix` followed by ten ASCII
235/// uppercase letters or digits (11 characters).
236fn validate_prefixed_location_id(value: &str, prefix: char) -> ConditionResult {
237    let mut chars = value.chars();
238    ConditionResult::from(
239        value.len() == 11
240            && chars.next() == Some(prefix)
241            && chars.all(|c| c.is_ascii_digit() || c.is_ascii_uppercase()),
242    )
243}
244
245/// Validate Steuerbare-Ressource-ID (SR-ID): "C" + ten alphanumerics
246/// (`C816417ST77`).
247pub fn validate_sr_id(value: &str) -> ConditionResult {
248    validate_prefixed_location_id(value, 'C')
249}
250
251/// Validate Netzlokations-ID: "E" + ten alphanumerics (`E1688117482`).
252pub fn validate_nelo_id(value: &str) -> ConditionResult {
253    validate_prefixed_location_id(value, 'E')
254}
255
256// --- OBIS code pattern matching ---
257
258/// Parse an OBIS code of the form `A-B:C.D.E[*F]` and return `(C, D)`.
259///
260/// OBIS structure (IEC 62056-61, BDEW/DVGW usage):
261/// - `A` — medium (1 = electricity, 7 = gas, 6 = heat, …)
262/// - `B` — channel
263/// - `C` — measurement type (1 = +A active energy import, 2 = -A active energy
264///   export, 3 = +R reactive import, 4 = -R reactive export, …)
265/// - `D` — measurement mode (8 = total time integral, 9 = billing-period
266///   integral, 29 = previous-billing-period partial value for interval
267///   measurements, 5 = actual/instantaneous value, …)
268/// - `E` — rate/tariff
269/// - `F` — optional billing period marker
270///
271/// Returns `None` when the value doesn't fit the shape. Whitespace-tolerant.
272pub fn parse_obis(value: &str) -> Option<(u32, u32)> {
273    let value = value.trim();
274    // Split at the colon between `A-B` and `C.D.E`.
275    let (_ab, cde) = value.split_once(':')?;
276    // Drop optional `*F` suffix.
277    let cde = cde.split('*').next()?;
278    let mut parts = cde.split('.');
279    let c = parts.next()?.parse::<u32>().ok()?;
280    let d = parts.next()?.parse::<u32>().ok()?;
281    Some((c, d))
282}
283
284/// Is the OBIS code "Wirkarbeit kumuliert" — active energy as a cumulated
285/// time integral (total or per billing period)?
286///
287/// Matches BDEW convention: `C ∈ {1, 2}` (active energy import/export) and
288/// `D ∈ {8, 9}` (total time integral / billing-period integral).
289pub fn is_obis_wirkarbeit_kumuliert(value: &str) -> bool {
290    matches!(parse_obis(value), Some((1 | 2, 8 | 9)))
291}
292
293/// Is the OBIS code "Wirkarbeit 1/4 Stunde" — active energy 15-minute
294/// interval (Lastgang) measurement?
295///
296/// Matches BDEW convention for quarter-hour Lastgang: `C ∈ {1, 2}` and
297/// `D = 29` (partial value for previous billing period, the standard marker
298/// for interval-measured energy in German energy market MSCONS/UTILMD).
299pub fn is_obis_wirkarbeit_quarter_hour(value: &str) -> bool {
300    matches!(parse_obis(value), Some((1 | 2, 29)))
301}
302
303/// Is the OBIS code an energy register, `1-b:c.8.e` with `c` 1 to 8?
304///
305/// UTILMD Strom `[273]` lists exactly these: "1-b?:1.8.e / 1-b?:2.8.e / … /
306/// 1-b?:8.8.e / 1-b?:1.8.63" (1.8.63 is a 1.8.e). A load profile
307/// (`1-1:1.29.0`) or a register of another medium (`7-…`) is not one.
308pub fn is_energy_register_obis(value: &str) -> bool {
309    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((1..=8, 8)))
310}
311
312/// Validate an X.509 certificate body per BSI TR-03109-4.
313///
314/// In EDIFACT messages (e.g. ORDERS/REQOTE for Smartmeter gateway config) the
315/// certificate body is transmitted as base64-encoded DER — the PEM armoring
316/// (`-----BEGIN CERTIFICATE-----` / `-----END CERTIFICATE-----` lines) may or
317/// may not be present depending on the profile.
318///
319/// This validator performs a structural check only:
320/// - non-empty
321/// - composed exclusively of base64 characters (`A-Za-z0-9+/=`) plus
322///   whitespace (`\n\r\t` and space — PEM lines wrap at 64 chars)
323/// - decoded length plausible for a DER-encoded X.509 certificate (we allow a
324///   loose lower bound — a minimal self-signed cert is ~400 bytes, so the
325///   base64 form is ≥ ~540 chars; we use 100 as a sanity floor)
326///
327/// Cryptographic validation (signature, CA chain, TR-03109 certificate
328/// extensions) is out of scope for static AHB validation — those require a
329/// trust store and runtime context.
330pub fn validate_x509_cert_body(value: &str) -> ConditionResult {
331    let trimmed = value.trim();
332    if trimmed.is_empty() {
333        return ConditionResult::Unknown;
334    }
335    // Strip optional PEM armoring so the charset check operates on the
336    // encoded body alone.
337    let body = trimmed
338        .trim_start_matches("-----BEGIN CERTIFICATE-----")
339        .trim_end_matches("-----END CERTIFICATE-----")
340        .trim();
341    let chars_ok = body.chars().all(|c| {
342        c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '\n' | '\r' | '\t' | ' ')
343    });
344    // Minimum plausible length for a base64-encoded X.509 body. Shorter
345    // values are almost certainly not a real certificate.
346    let len_ok = body.chars().filter(|c| !c.is_whitespace()).count() >= 100;
347    ConditionResult::from(chars_ok && len_ok)
348}
349
350/// Validate Zahlpunktbezeichnung: exactly 33 alphanumeric characters.
351pub fn validate_zahlpunkt(value: &str) -> ConditionResult {
352    if value.len() != 33 {
353        return ConditionResult::from(false);
354    }
355    ConditionResult::from(value.chars().all(|c| c.is_ascii_alphanumeric()))
356}
357
358/// Validate either MaLo-ID or Zahlpunktbezeichnung format.
359pub fn validate_malo_or_zahlpunkt(value: &str) -> ConditionResult {
360    if value.len() == 11 && validate_malo_id(value).is_true() {
361        return ConditionResult::True;
362    }
363    if value.len() == 33 && validate_zahlpunkt(value).is_true() {
364        return ConditionResult::True;
365    }
366    ConditionResult::False
367}
368
369// --- Artikelnummer pattern validation ---
370
371/// Validate a dash-separated digit pattern like "n1-n2-n1-n3".
372///
373/// `segment_lengths` defines expected digit counts per dash-separated segment.
374///
375/// Example: `validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3])` → True
376/// Example: `validate_artikel_pattern("1-23-4", &[1, 2, 1])` → True
377pub fn validate_artikel_pattern(value: &str, segment_lengths: &[usize]) -> ConditionResult {
378    if value.is_empty() {
379        return ConditionResult::Unknown;
380    }
381    let parts: Vec<&str> = value.split('-').collect();
382    if parts.len() != segment_lengths.len() {
383        return ConditionResult::from(false);
384    }
385    let valid = parts
386        .iter()
387        .zip(segment_lengths.iter())
388        .all(|(part, &expected_len)| {
389            part.len() == expected_len && part.chars().all(|c| c.is_ascii_digit())
390        });
391    ConditionResult::from(valid)
392}
393
394// --- General string validation ---
395
396/// Validate exact character length.
397pub fn validate_exact_length(value: &str, expected: usize) -> ConditionResult {
398    if value.is_empty() {
399        return ConditionResult::Unknown;
400    }
401    ConditionResult::from(value.len() == expected)
402}
403
404/// Validate maximum character length.
405pub fn validate_max_length(value: &str, max: usize) -> ConditionResult {
406    if value.is_empty() {
407        return ConditionResult::Unknown;
408    }
409    ConditionResult::from(value.len() <= max)
410}
411
412/// Validate that a string contains only digits (positive integer check).
413pub fn validate_all_digits(value: &str) -> ConditionResult {
414    if value.is_empty() {
415        return ConditionResult::Unknown;
416    }
417    ConditionResult::from(value.chars().all(|c| c.is_ascii_digit()))
418}
419
420/// Current UTC date+time as a CCYYMMDDHHMM string (12 chars).
421pub fn utc_now_ccyymmddhhmm() -> String {
422    chrono::Utc::now().format("%Y%m%d%H%M").to_string()
423}
424
425/// A DTM format 303 value (`CCYYMMDDHHMMZZZ`, `202610312300+00`) as German
426/// local time: CET, or CEST from the last Sunday of March to the last Sunday of
427/// October (01:00 UTC each). `None` if it is no such value.
428///
429/// "0 Uhr gem. deutscher Zeit" (UTILMD [87]) is `…2300+00` in winter and
430/// `…2200+00` in summer; the digits alone never show midnight.
431pub fn german_local_time(value: &str) -> Option<chrono::NaiveDateTime> {
432    use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, Weekday};
433    let value = value.replace('?', "");
434    let stamp = NaiveDateTime::parse_from_str(value.get(..12)?, "%Y%m%d%H%M").ok()?;
435    let offset: i64 = match value.get(12..) {
436        None | Some("") => 0,
437        Some(zone) => zone.parse().ok()?,
438    };
439    let utc = stamp - Duration::hours(offset);
440    let switch = |month: u32| {
441        let mut day = NaiveDate::from_ymd_opt(utc.year(), month, 31)?;
442        while day.weekday() != Weekday::Sun {
443            day = day.pred_opt()?;
444        }
445        day.and_hms_opt(1, 0, 0)
446    };
447    let summer = utc >= switch(3)? && utc < switch(10)?;
448    Some(utc + Duration::hours(if summer { 2 } else { 1 }))
449}
450
451#[cfg(test)]
452mod tests {
453    #[test]
454    fn energy_registers_are_c_8_e_with_c_one_to_eight() {
455        use super::is_energy_register_obis;
456        for obis in ["1-1:1.8.0", "1-0:2.8.1", "1-1:8.8.0", "1-1:1.8.63", "1-65:3.8.2"] {
457            assert!(is_energy_register_obis(obis), "{obis}");
458        }
459        for obis in ["1-1:1.29.0", "1-1:2.29.0", "1-1:9.8.0", "7-0:3.0.0", "1-1:1.9.0", "x"] {
460            assert!(!is_energy_register_obis(obis), "{obis}");
461        }
462    }
463
464    use super::*;
465
466    // --- Decimal places ---
467
468    #[test]
469    fn test_max_decimal_places() {
470        assert_eq!(
471            validate_max_decimal_places("123.45", 2),
472            ConditionResult::True
473        );
474        assert_eq!(
475            validate_max_decimal_places("123.456", 2),
476            ConditionResult::False
477        );
478        assert_eq!(validate_max_decimal_places("123", 2), ConditionResult::True);
479        assert_eq!(validate_max_decimal_places("0.1", 3), ConditionResult::True);
480        assert_eq!(validate_max_decimal_places("", 2), ConditionResult::Unknown);
481    }
482
483    #[test]
484    fn test_no_decimal_places() {
485        assert_eq!(validate_max_decimal_places("100", 0), ConditionResult::True);
486        assert_eq!(
487            validate_max_decimal_places("100.5", 0),
488            ConditionResult::False
489        );
490    }
491
492    #[test]
493    fn test_max_integer_digits() {
494        assert_eq!(
495            validate_max_integer_digits("1234", 4),
496            ConditionResult::True
497        );
498        assert_eq!(
499            validate_max_integer_digits("12345", 4),
500            ConditionResult::False
501        );
502        assert_eq!(
503            validate_max_integer_digits("-123.45", 4),
504            ConditionResult::True
505        );
506        assert_eq!(validate_max_integer_digits("", 4), ConditionResult::Unknown);
507    }
508
509    // --- Numeric range ---
510
511    #[test]
512    fn test_validate_numeric() {
513        assert_eq!(validate_numeric("5.0", ">=", 0.0), ConditionResult::True);
514        assert_eq!(validate_numeric("-1.0", ">=", 0.0), ConditionResult::False);
515        assert_eq!(validate_numeric("1", "==", 1.0), ConditionResult::True);
516        assert_eq!(validate_numeric("2", "==", 1.0), ConditionResult::False);
517        assert_eq!(validate_numeric("0", ">", 0.0), ConditionResult::False);
518        assert_eq!(validate_numeric("1", ">", 0.0), ConditionResult::True);
519        // Not a number is no "möglicher Wert" (mako-twin: RFF+Z60
520        // `O5D2DXBG1A` passed `[914]` "> 0").
521        assert_eq!(validate_numeric("abc", ">=", 0.0), ConditionResult::False);
522        assert_eq!(
523            validate_numeric("O5D2DXBG1A", ">", 0.0),
524            ConditionResult::False
525        );
526        assert_eq!(validate_numeric("NaN", ">", 0.0), ConditionResult::False);
527        assert_eq!(validate_numeric("inf", ">", 0.0), ConditionResult::False);
528        assert_eq!(validate_numeric("1e3", ">", 0.0), ConditionResult::False);
529        // A comma is a decimal mark the UNA may set.
530        assert_eq!(validate_numeric("0,5", ">", 0.0), ConditionResult::True);
531        assert_eq!(validate_numeric("-2", "<=", 0.0), ConditionResult::True);
532        assert_eq!(validate_numeric("", ">", 0.0), ConditionResult::Unknown);
533    }
534
535    // --- DTM validation ---
536
537    #[test]
538    fn test_hhmm_equals() {
539        assert_eq!(
540            validate_hhmm_equals("202601012200+00", "2200"),
541            ConditionResult::True
542        );
543        assert_eq!(
544            validate_hhmm_equals("202601012300+00", "2200"),
545            ConditionResult::False
546        );
547        assert_eq!(
548            validate_hhmm_equals("short", "2200"),
549            ConditionResult::False
550        );
551    }
552
553    #[test]
554    fn test_hhmm_range() {
555        assert_eq!(
556            validate_hhmm_range("202601011530+00", "0000", "2359"),
557            ConditionResult::True
558        );
559        assert_eq!(
560            validate_hhmm_range("202601010000+00", "0000", "2359"),
561            ConditionResult::True
562        );
563        assert_eq!(
564            validate_hhmm_range("202601012359+00", "0000", "2359"),
565            ConditionResult::True
566        );
567    }
568
569    #[test]
570    fn test_mmddhhmm_equals() {
571        assert_eq!(
572            validate_mmddhhmm_equals("202612312300+00", "12312300"),
573            ConditionResult::True
574        );
575        assert_eq!(
576            validate_mmddhhmm_equals("202601012200+00", "12312300"),
577            ConditionResult::False
578        );
579    }
580
581    #[test]
582    fn test_timezone_utc() {
583        assert_eq!(
584            validate_timezone_utc("202601012200+00"),
585            ConditionResult::True
586        );
587        assert_eq!(
588            validate_timezone_utc("202601012200+01"),
589            ConditionResult::False
590        );
591        assert_eq!(
592            validate_timezone_utc("202601012200"),
593            ConditionResult::False
594        );
595        // Format 304 carries seconds before the zone.
596        assert_eq!(
597            validate_timezone_utc("20260101220000+00"),
598            ConditionResult::True
599        );
600        assert_eq!(
601            validate_timezone_utc("20260101220000+01"),
602            ConditionResult::False
603        );
604    }
605
606    // --- Contact validation ---
607
608    #[test]
609    fn test_email() {
610        assert_eq!(validate_email("user@example.com"), ConditionResult::True);
611        assert_eq!(validate_email("nope"), ConditionResult::False);
612        assert_eq!(validate_email("has@but-no-dot"), ConditionResult::False);
613        assert_eq!(validate_email(""), ConditionResult::Unknown);
614    }
615
616    #[test]
617    fn test_phone() {
618        assert_eq!(validate_phone("+4930123456"), ConditionResult::True);
619        assert_eq!(validate_phone("030123456"), ConditionResult::False);
620        assert_eq!(validate_phone("+"), ConditionResult::False);
621        assert_eq!(validate_phone("+49 30 123"), ConditionResult::False); // spaces not allowed
622        assert_eq!(validate_phone(""), ConditionResult::Unknown);
623    }
624
625    // --- ID validation ---
626
627    #[test]
628    fn test_malo_id() {
629        // Valid MaLo-IDs — taken directly from the BO4E-dotnet reference test
630        // suite (TestBO4E/TestMaLoMeLoId.cs), which uses the BDEW MaLo-ID spec
631        // (no digit-sum on doubled products; see `validate_malo_id` docstring).
632        assert_eq!(validate_malo_id("51238696781"), ConditionResult::True);
633        assert_eq!(validate_malo_id("41373559241"), ConditionResult::True);
634        assert_eq!(validate_malo_id("56789012345"), ConditionResult::True);
635        assert_eq!(validate_malo_id("52935155442"), ConditionResult::True);
636
637        // Negative cases from the same reference tests.
638        assert_eq!(validate_malo_id("41373559240"), ConditionResult::False); // wrong check digit
639        assert_eq!(validate_malo_id("512386967890"), ConditionResult::False); // 12 digits
640        assert_eq!(validate_malo_id("1234567890"), ConditionResult::False); // too short
641        assert_eq!(validate_malo_id("abcdefghijk"), ConditionResult::False); // not digits
642    }
643
644    #[test]
645    fn test_zahlpunkt() {
646        let valid = "DE0001234567890123456789012345678";
647        assert_eq!(valid.len(), 33);
648        assert_eq!(validate_zahlpunkt(valid), ConditionResult::True);
649        assert_eq!(validate_zahlpunkt("tooshort"), ConditionResult::False);
650    }
651
652    // --- Artikelnummer pattern ---
653
654    #[test]
655    fn test_artikel_pattern() {
656        assert_eq!(
657            validate_artikel_pattern("1-23-4", &[1, 2, 1]),
658            ConditionResult::True
659        );
660        assert_eq!(
661            validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3]),
662            ConditionResult::True
663        );
664        assert_eq!(
665            validate_artikel_pattern("1-23-4-56", &[1, 2, 1, 3]),
666            ConditionResult::False
667        );
668        assert_eq!(
669            validate_artikel_pattern("1-AB-4", &[1, 2, 1]),
670            ConditionResult::False
671        );
672        assert_eq!(
673            validate_artikel_pattern("", &[1, 2, 1]),
674            ConditionResult::Unknown
675        );
676    }
677
678    // --- TR-ID / SR-ID validation ---
679
680    #[test]
681    fn test_tr_id() {
682        assert_eq!(validate_tr_id("ABC123"), ConditionResult::True);
683        assert_eq!(validate_tr_id("A"), ConditionResult::True);
684        assert_eq!(validate_tr_id(&"A".repeat(35)), ConditionResult::True);
685        assert_eq!(validate_tr_id(&"A".repeat(36)), ConditionResult::False);
686        assert_eq!(validate_tr_id("has spaces"), ConditionResult::False);
687        assert_eq!(validate_tr_id("has-dash"), ConditionResult::False);
688        assert_eq!(validate_tr_id(""), ConditionResult::Unknown);
689    }
690
691    #[test]
692    fn test_parse_obis() {
693        assert_eq!(parse_obis("1-1:1.8.0"), Some((1, 8)));
694        assert_eq!(parse_obis("1-1:2.29.0"), Some((2, 29)));
695        assert_eq!(parse_obis("1-0:1.8.0*255"), Some((1, 8))); // star suffix
696        assert_eq!(parse_obis(" 1-1:1.8.0 "), Some((1, 8))); // whitespace
697        assert_eq!(parse_obis("no-colon"), None);
698        assert_eq!(parse_obis("1-1:abc.8.0"), None);
699        assert_eq!(parse_obis(""), None);
700    }
701
702    #[test]
703    fn test_obis_wirkarbeit_kumuliert() {
704        // Active energy import/export, total or billing-period integral.
705        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.8.0"));
706        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.8.0"));
707        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.9.0"));
708        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.9.0"));
709        assert!(is_obis_wirkarbeit_kumuliert("1-0:1.8.0*255"));
710        // Reactive energy — not Wirkarbeit.
711        assert!(!is_obis_wirkarbeit_kumuliert("1-1:3.8.0"));
712        assert!(!is_obis_wirkarbeit_kumuliert("1-1:4.8.0"));
713        // 15-min partial value — not kumuliert.
714        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.29.0"));
715        // Actual value — not kumuliert.
716        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.5.0"));
717    }
718
719    #[test]
720    fn test_obis_wirkarbeit_quarter_hour() {
721        // Active energy 15-min Lastgang.
722        assert!(is_obis_wirkarbeit_quarter_hour("1-1:1.29.0"));
723        assert!(is_obis_wirkarbeit_quarter_hour("1-1:2.29.0"));
724        assert!(is_obis_wirkarbeit_quarter_hour("1-0:1.29.0*255"));
725        // Cumulated — not 1/4h.
726        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.8.0"));
727        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.9.0"));
728        // Reactive.
729        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:3.29.0"));
730    }
731
732    #[test]
733    fn test_x509_cert_body() {
734        // Valid: 600-char base64 body (well above 100-char floor).
735        let body = "A".repeat(600);
736        assert_eq!(validate_x509_cert_body(&body), ConditionResult::True);
737
738        // Valid with base64 padding and newlines (PEM-style wrapping).
739        let pem_body = "A".repeat(64) + "\n" + &"B".repeat(64) + "\n" + &"C".repeat(64);
740        assert_eq!(validate_x509_cert_body(&pem_body), ConditionResult::True);
741
742        // Valid with explicit PEM armoring — stripped before charset check.
743        let armored = format!(
744            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
745            "A".repeat(200)
746        );
747        assert_eq!(validate_x509_cert_body(&armored), ConditionResult::True);
748
749        // Valid: base64 chars include +, /, =
750        let with_punct = "AB+/==".to_string() + &"A".repeat(200);
751        assert_eq!(validate_x509_cert_body(&with_punct), ConditionResult::True);
752
753        // Too short — not a plausible cert.
754        assert_eq!(validate_x509_cert_body("QUJD"), ConditionResult::False);
755
756        // Non-base64 characters.
757        let invalid_chars = "A".repeat(200) + "!@#";
758        assert_eq!(
759            validate_x509_cert_body(&invalid_chars),
760            ConditionResult::False
761        );
762
763        // Empty is Unknown (consistent with other format validators).
764        assert_eq!(validate_x509_cert_body(""), ConditionResult::Unknown);
765        assert_eq!(validate_x509_cert_body("   \n  "), ConditionResult::Unknown);
766    }
767
768    /// SR-IDs are "C" + ten alphanumerics, not MaLo-shaped: every SR-ID in
769    /// `example_market_communication_bo4e_transactions/` looks like this
770    /// (`LOC+Z19+C816417ST77`), and a MaLo-ID check rejected all of them.
771    #[test]
772    fn test_sr_id() {
773        for real in ["C816417ST77", "CZZ6M5DGSS5", "COPFWS2EX96"] {
774            assert_eq!(validate_sr_id(real), ConditionResult::True, "{real}");
775        }
776        assert_eq!(
777            validate_sr_id("51238696781"),
778            ConditionResult::False,
779            "a MaLo-ID"
780        );
781        assert_eq!(validate_sr_id("C12345"), ConditionResult::False);
782        assert_eq!(validate_sr_id(""), ConditionResult::False);
783    }
784
785    /// Netzlokations-IDs are "E" + ten alphanumerics (`LOC+Z18+E1688117482`,
786    /// `EU5UQAWW8D0` in the example transactions). The generated evaluators
787    /// checked them as MaLo-IDs, so every real one failed `[960]`.
788    #[test]
789    fn test_nelo_id() {
790        for real in ["E1688117482", "EU5UQAWW8D0", "EEW7TM7V906"] {
791            assert_eq!(validate_nelo_id(real), ConditionResult::True, "{real}");
792        }
793        assert_eq!(
794            validate_nelo_id("51238696781"),
795            ConditionResult::False,
796            "a MaLo-ID"
797        );
798        assert_eq!(validate_nelo_id("E123"), ConditionResult::False);
799        assert_eq!(validate_nelo_id("e1688117482"), ConditionResult::False);
800    }
801
802    // --- String validation ---
803
804    #[test]
805    fn test_exact_length() {
806        assert_eq!(
807            validate_exact_length("1234567890123456", 16),
808            ConditionResult::True
809        );
810        assert_eq!(validate_exact_length("123", 16), ConditionResult::False);
811        assert_eq!(validate_exact_length("", 16), ConditionResult::Unknown);
812    }
813
814    #[test]
815    fn test_all_digits() {
816        assert_eq!(validate_all_digits("12345"), ConditionResult::True);
817        assert_eq!(validate_all_digits("123a5"), ConditionResult::False);
818        assert_eq!(validate_all_digits(""), ConditionResult::Unknown);
819    }
820}