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; for electricity the BDEW "Codeliste der
266///   OBIS-Kennzahlen und Medien" (2.5c) uses 6 = Maximum, 8 = Zeitintegral 1
267///   (Zählerstände), 9 = Zeitintegral 2 (Vorschübe, "Energiemenge für einen
268///   beliebigen Zeitraum") and 29 = Zeitintegral 5 (Lastgang, "Energiemengen
269///   für Zeitintervalle von äquidistanter Dauer")
270/// - `E` — rate/tariff
271/// - `F` — optional billing period marker
272///
273/// Returns `None` when the value doesn't fit the shape. Whitespace-tolerant.
274pub fn parse_obis(value: &str) -> Option<(u32, u32)> {
275    let value = value.trim();
276    // Split at the colon between `A-B` and `C.D.E`.
277    let (_ab, cde) = value.split_once(':')?;
278    // Drop optional `*F` suffix.
279    let cde = cde.split('*').next()?;
280    let mut parts = cde.split('.');
281    let c = parts.next()?.parse::<u32>().ok()?;
282    let d = parts.next()?.parse::<u32>().ok()?;
283    Some((c, d))
284}
285
286/// The tariff `E` of an OBIS code `A-B:C.D.E[*F]`; `None` when the value
287/// doesn't fit the shape. UTILMD Strom `[391]` names it: "OBIS mit zugeordneter
288/// Zählzeit (Tarif: e = 1 .. 62)".
289pub fn obis_tariff(value: &str) -> Option<u32> {
290    let (_ab, cde) = value.trim().split_once(':')?;
291    let cde = cde.split('*').next()?;
292    let mut parts = cde.split('.');
293    parts.next()?.parse::<u32>().ok()?;
294    parts.next()?.parse::<u32>().ok()?;
295    parts.next()?.parse::<u32>().ok()
296}
297
298/// Is the OBIS code "Wirkarbeit kumuliert" — active energy as a cumulated
299/// time integral (total or per billing period)?
300///
301/// Matches BDEW convention: `C ∈ {1, 2}` (active energy import/export) and
302/// `D ∈ {8, 9}` (total time integral / billing-period integral).
303pub fn is_obis_wirkarbeit_kumuliert(value: &str) -> bool {
304    matches!(parse_obis(value), Some((1 | 2, 8 | 9)))
305}
306
307/// Is the OBIS code "Wirkarbeit 1/4 Stunde" — active energy 15-minute
308/// interval (Lastgang) measurement?
309///
310/// Matches the BDEW code list's quarter-hour Lastgang: `C ∈ {1, 2}` (Wirkarbeit
311/// Bezug / Lieferung) and `D = 29` (Zeitintegral 5, Lastgang; its example
312/// "Vorschub (1/4 Std. Lastgang) elektrische Wirkarbeit" is `1-b:1.29.0`).
313pub fn is_obis_wirkarbeit_quarter_hour(value: &str) -> bool {
314    matches!(parse_obis(value), Some((1 | 2, 29)))
315}
316
317/// Is the electricity OBIS code an "Energiemenge" — a Vorschub (`D = 9`) or a
318/// Lastgang (`D = 29`)? The BDEW code list tells "Messwerte (Energiemengen,
319/// Zählerstände)" apart: a Zählerstand (`D = 8`) is not one.
320pub fn is_obis_energiemenge(value: &str) -> bool {
321    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((_, 9 | 29)))
322}
323
324/// Is the electricity OBIS code a "Zählerstand" (`D = 8`, Zeitintegral 1)?
325pub fn is_obis_zaehlerstand(value: &str) -> bool {
326    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((_, 8)))
327}
328
329/// Is the OBIS code a Wirkleistung maximum (`C ∈ {1, 2}`, `D = 6`), the code
330/// list's "Wirkleistung Bezug (+) / Lieferung (-) Maximum" (`1-b:1.6.0`,
331/// `1-b:2.6.0`) — the highest quarter hour's energy of a period?
332pub fn is_obis_wirkleistung_maximum(value: &str) -> bool {
333    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((1 | 2, 6)))
334}
335
336/// Is the electricity OBIS code a Blindarbeit (`C` 3 to 8, reactive energy
337/// and its quadrants) as a Zählerstand, Vorschub or Lastgang (`D ∈ {8, 9, 29}`)?
338pub fn is_obis_blindarbeit(value: &str) -> bool {
339    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((3..=8, 8 | 9 | 29)))
340}
341
342/// Whether the OBIS code names a Zählzeit: tariff `e = 1 … 62` ("OBIS mit
343/// zugeordneter Zählzeit"); `0` is "tariflos".
344pub fn obis_has_zaehlzeit(value: &str) -> bool {
345    obis_tariff(value).is_some_and(|e| (1..=62).contains(&e))
346}
347
348/// Is the OBIS code an energy register, `1-b:c.8.e` with `c` 1 to 8?
349///
350/// UTILMD Strom `[273]` lists exactly these: "1-b?:1.8.e / 1-b?:2.8.e / … /
351/// 1-b?:8.8.e / 1-b?:1.8.63" (1.8.63 is a 1.8.e). A load profile
352/// (`1-1:1.29.0`) or a register of another medium (`7-…`) is not one.
353pub fn is_energy_register_obis(value: &str) -> bool {
354    value.trim().starts_with("1-") && matches!(parse_obis(value), Some((1..=8, 8)))
355}
356
357/// Validate an X.509 certificate body per BSI TR-03109-4.
358///
359/// In EDIFACT messages (e.g. ORDERS/REQOTE for Smartmeter gateway config) the
360/// certificate body is transmitted as base64-encoded DER — the PEM armoring
361/// (`-----BEGIN CERTIFICATE-----` / `-----END CERTIFICATE-----` lines) may or
362/// may not be present depending on the profile.
363///
364/// This validator performs a structural check only:
365/// - non-empty
366/// - composed exclusively of base64 characters (`A-Za-z0-9+/=`) plus
367///   whitespace (`\n\r\t` and space — PEM lines wrap at 64 chars)
368/// - decoded length plausible for a DER-encoded X.509 certificate (we allow a
369///   loose lower bound — a minimal self-signed cert is ~400 bytes, so the
370///   base64 form is ≥ ~540 chars; we use 100 as a sanity floor)
371///
372/// Cryptographic validation (signature, CA chain, TR-03109 certificate
373/// extensions) is out of scope for static AHB validation — those require a
374/// trust store and runtime context.
375pub fn validate_x509_cert_body(value: &str) -> ConditionResult {
376    let trimmed = value.trim();
377    if trimmed.is_empty() {
378        return ConditionResult::Unknown;
379    }
380    // Strip optional PEM armoring so the charset check operates on the
381    // encoded body alone.
382    let body = trimmed
383        .trim_start_matches("-----BEGIN CERTIFICATE-----")
384        .trim_end_matches("-----END CERTIFICATE-----")
385        .trim();
386    let chars_ok = body.chars().all(|c| {
387        c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '\n' | '\r' | '\t' | ' ')
388    });
389    // Minimum plausible length for a base64-encoded X.509 body. Shorter
390    // values are almost certainly not a real certificate.
391    let len_ok = body.chars().filter(|c| !c.is_whitespace()).count() >= 100;
392    ConditionResult::from(chars_ok && len_ok)
393}
394
395/// Validate Zahlpunktbezeichnung: exactly 33 alphanumeric characters.
396pub fn validate_zahlpunkt(value: &str) -> ConditionResult {
397    if value.len() != 33 {
398        return ConditionResult::from(false);
399    }
400    ConditionResult::from(value.chars().all(|c| c.is_ascii_alphanumeric()))
401}
402
403/// Validate either MaLo-ID or Zahlpunktbezeichnung format.
404pub fn validate_malo_or_zahlpunkt(value: &str) -> ConditionResult {
405    if value.len() == 11 && validate_malo_id(value).is_true() {
406        return ConditionResult::True;
407    }
408    if value.len() == 33 && validate_zahlpunkt(value).is_true() {
409        return ConditionResult::True;
410    }
411    ConditionResult::False
412}
413
414// --- Artikelnummer pattern validation ---
415
416/// Validate a dash-separated digit pattern like "n1-n2-n1-n3".
417///
418/// `segment_lengths` defines expected digit counts per dash-separated segment.
419///
420/// Example: `validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3])` → True
421/// Example: `validate_artikel_pattern("1-23-4", &[1, 2, 1])` → True
422pub fn validate_artikel_pattern(value: &str, segment_lengths: &[usize]) -> ConditionResult {
423    if value.is_empty() {
424        return ConditionResult::Unknown;
425    }
426    let parts: Vec<&str> = value.split('-').collect();
427    if parts.len() != segment_lengths.len() {
428        return ConditionResult::from(false);
429    }
430    let valid = parts
431        .iter()
432        .zip(segment_lengths.iter())
433        .all(|(part, &expected_len)| {
434            part.len() == expected_len && part.chars().all(|c| c.is_ascii_digit())
435        });
436    ConditionResult::from(valid)
437}
438
439// --- General string validation ---
440
441/// Validate exact character length.
442pub fn validate_exact_length(value: &str, expected: usize) -> ConditionResult {
443    if value.is_empty() {
444        return ConditionResult::Unknown;
445    }
446    ConditionResult::from(value.len() == expected)
447}
448
449/// Validate maximum character length.
450pub fn validate_max_length(value: &str, max: usize) -> ConditionResult {
451    if value.is_empty() {
452        return ConditionResult::Unknown;
453    }
454    ConditionResult::from(value.len() <= max)
455}
456
457/// Validate that a string contains only digits (positive integer check).
458pub fn validate_all_digits(value: &str) -> ConditionResult {
459    if value.is_empty() {
460        return ConditionResult::Unknown;
461    }
462    ConditionResult::from(value.chars().all(|c| c.is_ascii_digit()))
463}
464
465/// Current UTC date+time as a CCYYMMDDHHMM string (12 chars).
466pub fn utc_now_ccyymmddhhmm() -> String {
467    chrono::Utc::now().format("%Y%m%d%H%M").to_string()
468}
469
470/// A DTM format 303 value (`CCYYMMDDHHMMZZZ`, `202610312300+00`) as German
471/// local time: CET, or CEST from the last Sunday of March to the last Sunday of
472/// October (01:00 UTC each). `None` if it is no such value.
473///
474/// "0 Uhr gem. deutscher Zeit" (UTILMD [87]) is `…2300+00` in winter and
475/// `…2200+00` in summer; the digits alone never show midnight.
476pub fn german_local_time(value: &str) -> Option<chrono::NaiveDateTime> {
477    use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, Weekday};
478    let value = value.replace('?', "");
479    let stamp = NaiveDateTime::parse_from_str(value.get(..12)?, "%Y%m%d%H%M").ok()?;
480    let offset: i64 = match value.get(12..) {
481        None | Some("") => 0,
482        Some(zone) => zone.parse().ok()?,
483    };
484    let utc = stamp - Duration::hours(offset);
485    let switch = |month: u32| {
486        let mut day = NaiveDate::from_ymd_opt(utc.year(), month, 31)?;
487        while day.weekday() != Weekday::Sun {
488            day = day.pred_opt()?;
489        }
490        day.and_hms_opt(1, 0, 0)
491    };
492    let summer = utc >= switch(3)? && utc < switch(10)?;
493    Some(utc + Duration::hours(if summer { 2 } else { 1 }))
494}
495
496#[cfg(test)]
497mod tests {
498    /// The classes the BDEW "Codeliste der OBIS-Kennzahlen und Medien" 2.5c
499    /// defines, on codes it lists.
500    #[test]
501    fn obis_classes_follow_the_code_list() {
502        use super::*;
503        // Zählerstand, Vorschub, Lastgang of Wirkarbeit Bezug.
504        assert!(is_obis_zaehlerstand("1-1:1.8.0") && !is_obis_energiemenge("1-1:1.8.0"));
505        assert!(is_obis_energiemenge("1-1:1.9.0") && !is_obis_zaehlerstand("1-1:1.9.0"));
506        assert!(
507            is_obis_energiemenge("1-1:1.29.0") && is_obis_wirkarbeit_quarter_hour("1-1:1.29.0")
508        );
509        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.9.0"));
510        // Wirkleistung Maximum, Blindarbeit.
511        assert!(is_obis_wirkleistung_maximum("1-1:2.6.0"));
512        assert!(!is_obis_wirkleistung_maximum("1-1:3.6.0"));
513        assert!(is_obis_blindarbeit("1-1:3.9.0") && is_obis_blindarbeit("1-1:4.29.0"));
514        assert!(!is_obis_blindarbeit("1-1:1.8.0"));
515        // Tarif e = 1 … 62 names a Zählzeit, 0 is tariflos.
516        assert!(obis_has_zaehlzeit("1-1:1.9.1") && obis_has_zaehlzeit("1-1:1.8.62"));
517        assert!(!obis_has_zaehlzeit("1-1:1.9.0") && !obis_has_zaehlzeit("1-1:1.8.63"));
518        // Gas is not electricity.
519        assert!(!is_obis_energiemenge("7-0:3.9.0"));
520    }
521
522    #[test]
523    fn the_tariff_is_the_e_of_c_d_e() {
524        use super::obis_tariff;
525        assert_eq!(obis_tariff("1-1:1.8.1"), Some(1));
526        assert_eq!(obis_tariff("1-0:2.8.62*255"), Some(62));
527        assert_eq!(obis_tariff("1-0:1.8.0"), Some(0));
528        assert_eq!(obis_tariff("1-0:1.8"), None);
529        assert_eq!(obis_tariff("x"), None);
530    }
531
532    #[test]
533    fn energy_registers_are_c_8_e_with_c_one_to_eight() {
534        use super::is_energy_register_obis;
535        for obis in [
536            "1-1:1.8.0",
537            "1-0:2.8.1",
538            "1-1:8.8.0",
539            "1-1:1.8.63",
540            "1-65:3.8.2",
541        ] {
542            assert!(is_energy_register_obis(obis), "{obis}");
543        }
544        for obis in [
545            "1-1:1.29.0",
546            "1-1:2.29.0",
547            "1-1:9.8.0",
548            "7-0:3.0.0",
549            "1-1:1.9.0",
550            "x",
551        ] {
552            assert!(!is_energy_register_obis(obis), "{obis}");
553        }
554    }
555
556    use super::*;
557
558    // --- Decimal places ---
559
560    #[test]
561    fn test_max_decimal_places() {
562        assert_eq!(
563            validate_max_decimal_places("123.45", 2),
564            ConditionResult::True
565        );
566        assert_eq!(
567            validate_max_decimal_places("123.456", 2),
568            ConditionResult::False
569        );
570        assert_eq!(validate_max_decimal_places("123", 2), ConditionResult::True);
571        assert_eq!(validate_max_decimal_places("0.1", 3), ConditionResult::True);
572        assert_eq!(validate_max_decimal_places("", 2), ConditionResult::Unknown);
573    }
574
575    #[test]
576    fn test_no_decimal_places() {
577        assert_eq!(validate_max_decimal_places("100", 0), ConditionResult::True);
578        assert_eq!(
579            validate_max_decimal_places("100.5", 0),
580            ConditionResult::False
581        );
582    }
583
584    #[test]
585    fn test_max_integer_digits() {
586        assert_eq!(
587            validate_max_integer_digits("1234", 4),
588            ConditionResult::True
589        );
590        assert_eq!(
591            validate_max_integer_digits("12345", 4),
592            ConditionResult::False
593        );
594        assert_eq!(
595            validate_max_integer_digits("-123.45", 4),
596            ConditionResult::True
597        );
598        assert_eq!(validate_max_integer_digits("", 4), ConditionResult::Unknown);
599    }
600
601    // --- Numeric range ---
602
603    #[test]
604    fn test_validate_numeric() {
605        assert_eq!(validate_numeric("5.0", ">=", 0.0), ConditionResult::True);
606        assert_eq!(validate_numeric("-1.0", ">=", 0.0), ConditionResult::False);
607        assert_eq!(validate_numeric("1", "==", 1.0), ConditionResult::True);
608        assert_eq!(validate_numeric("2", "==", 1.0), ConditionResult::False);
609        assert_eq!(validate_numeric("0", ">", 0.0), ConditionResult::False);
610        assert_eq!(validate_numeric("1", ">", 0.0), ConditionResult::True);
611        // Not a number is no "möglicher Wert" (mako-twin: RFF+Z60
612        // `O5D2DXBG1A` passed `[914]` "> 0").
613        assert_eq!(validate_numeric("abc", ">=", 0.0), ConditionResult::False);
614        assert_eq!(
615            validate_numeric("O5D2DXBG1A", ">", 0.0),
616            ConditionResult::False
617        );
618        assert_eq!(validate_numeric("NaN", ">", 0.0), ConditionResult::False);
619        assert_eq!(validate_numeric("inf", ">", 0.0), ConditionResult::False);
620        assert_eq!(validate_numeric("1e3", ">", 0.0), ConditionResult::False);
621        // A comma is a decimal mark the UNA may set.
622        assert_eq!(validate_numeric("0,5", ">", 0.0), ConditionResult::True);
623        assert_eq!(validate_numeric("-2", "<=", 0.0), ConditionResult::True);
624        assert_eq!(validate_numeric("", ">", 0.0), ConditionResult::Unknown);
625    }
626
627    // --- DTM validation ---
628
629    #[test]
630    fn test_hhmm_equals() {
631        assert_eq!(
632            validate_hhmm_equals("202601012200+00", "2200"),
633            ConditionResult::True
634        );
635        assert_eq!(
636            validate_hhmm_equals("202601012300+00", "2200"),
637            ConditionResult::False
638        );
639        assert_eq!(
640            validate_hhmm_equals("short", "2200"),
641            ConditionResult::False
642        );
643    }
644
645    #[test]
646    fn test_hhmm_range() {
647        assert_eq!(
648            validate_hhmm_range("202601011530+00", "0000", "2359"),
649            ConditionResult::True
650        );
651        assert_eq!(
652            validate_hhmm_range("202601010000+00", "0000", "2359"),
653            ConditionResult::True
654        );
655        assert_eq!(
656            validate_hhmm_range("202601012359+00", "0000", "2359"),
657            ConditionResult::True
658        );
659    }
660
661    #[test]
662    fn test_mmddhhmm_equals() {
663        assert_eq!(
664            validate_mmddhhmm_equals("202612312300+00", "12312300"),
665            ConditionResult::True
666        );
667        assert_eq!(
668            validate_mmddhhmm_equals("202601012200+00", "12312300"),
669            ConditionResult::False
670        );
671    }
672
673    #[test]
674    fn test_timezone_utc() {
675        assert_eq!(
676            validate_timezone_utc("202601012200+00"),
677            ConditionResult::True
678        );
679        assert_eq!(
680            validate_timezone_utc("202601012200+01"),
681            ConditionResult::False
682        );
683        assert_eq!(
684            validate_timezone_utc("202601012200"),
685            ConditionResult::False
686        );
687        // Format 304 carries seconds before the zone.
688        assert_eq!(
689            validate_timezone_utc("20260101220000+00"),
690            ConditionResult::True
691        );
692        assert_eq!(
693            validate_timezone_utc("20260101220000+01"),
694            ConditionResult::False
695        );
696    }
697
698    // --- Contact validation ---
699
700    #[test]
701    fn test_email() {
702        assert_eq!(validate_email("user@example.com"), ConditionResult::True);
703        assert_eq!(validate_email("nope"), ConditionResult::False);
704        assert_eq!(validate_email("has@but-no-dot"), ConditionResult::False);
705        assert_eq!(validate_email(""), ConditionResult::Unknown);
706    }
707
708    #[test]
709    fn test_phone() {
710        assert_eq!(validate_phone("+4930123456"), ConditionResult::True);
711        assert_eq!(validate_phone("030123456"), ConditionResult::False);
712        assert_eq!(validate_phone("+"), ConditionResult::False);
713        assert_eq!(validate_phone("+49 30 123"), ConditionResult::False); // spaces not allowed
714        assert_eq!(validate_phone(""), ConditionResult::Unknown);
715    }
716
717    // --- ID validation ---
718
719    #[test]
720    fn test_malo_id() {
721        // Valid MaLo-IDs — taken directly from the BO4E-dotnet reference test
722        // suite (TestBO4E/TestMaLoMeLoId.cs), which uses the BDEW MaLo-ID spec
723        // (no digit-sum on doubled products; see `validate_malo_id` docstring).
724        assert_eq!(validate_malo_id("51238696781"), ConditionResult::True);
725        assert_eq!(validate_malo_id("41373559241"), ConditionResult::True);
726        assert_eq!(validate_malo_id("56789012345"), ConditionResult::True);
727        assert_eq!(validate_malo_id("52935155442"), ConditionResult::True);
728
729        // Negative cases from the same reference tests.
730        assert_eq!(validate_malo_id("41373559240"), ConditionResult::False); // wrong check digit
731        assert_eq!(validate_malo_id("512386967890"), ConditionResult::False); // 12 digits
732        assert_eq!(validate_malo_id("1234567890"), ConditionResult::False); // too short
733        assert_eq!(validate_malo_id("abcdefghijk"), ConditionResult::False); // not digits
734    }
735
736    #[test]
737    fn test_zahlpunkt() {
738        let valid = "DE0001234567890123456789012345678";
739        assert_eq!(valid.len(), 33);
740        assert_eq!(validate_zahlpunkt(valid), ConditionResult::True);
741        assert_eq!(validate_zahlpunkt("tooshort"), ConditionResult::False);
742    }
743
744    // --- Artikelnummer pattern ---
745
746    #[test]
747    fn test_artikel_pattern() {
748        assert_eq!(
749            validate_artikel_pattern("1-23-4", &[1, 2, 1]),
750            ConditionResult::True
751        );
752        assert_eq!(
753            validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3]),
754            ConditionResult::True
755        );
756        assert_eq!(
757            validate_artikel_pattern("1-23-4-56", &[1, 2, 1, 3]),
758            ConditionResult::False
759        );
760        assert_eq!(
761            validate_artikel_pattern("1-AB-4", &[1, 2, 1]),
762            ConditionResult::False
763        );
764        assert_eq!(
765            validate_artikel_pattern("", &[1, 2, 1]),
766            ConditionResult::Unknown
767        );
768    }
769
770    // --- TR-ID / SR-ID validation ---
771
772    #[test]
773    fn test_tr_id() {
774        assert_eq!(validate_tr_id("ABC123"), ConditionResult::True);
775        assert_eq!(validate_tr_id("A"), ConditionResult::True);
776        assert_eq!(validate_tr_id(&"A".repeat(35)), ConditionResult::True);
777        assert_eq!(validate_tr_id(&"A".repeat(36)), ConditionResult::False);
778        assert_eq!(validate_tr_id("has spaces"), ConditionResult::False);
779        assert_eq!(validate_tr_id("has-dash"), ConditionResult::False);
780        assert_eq!(validate_tr_id(""), ConditionResult::Unknown);
781    }
782
783    #[test]
784    fn test_parse_obis() {
785        assert_eq!(parse_obis("1-1:1.8.0"), Some((1, 8)));
786        assert_eq!(parse_obis("1-1:2.29.0"), Some((2, 29)));
787        assert_eq!(parse_obis("1-0:1.8.0*255"), Some((1, 8))); // star suffix
788        assert_eq!(parse_obis(" 1-1:1.8.0 "), Some((1, 8))); // whitespace
789        assert_eq!(parse_obis("no-colon"), None);
790        assert_eq!(parse_obis("1-1:abc.8.0"), None);
791        assert_eq!(parse_obis(""), None);
792    }
793
794    #[test]
795    fn test_obis_wirkarbeit_kumuliert() {
796        // Active energy import/export, total or billing-period integral.
797        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.8.0"));
798        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.8.0"));
799        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.9.0"));
800        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.9.0"));
801        assert!(is_obis_wirkarbeit_kumuliert("1-0:1.8.0*255"));
802        // Reactive energy — not Wirkarbeit.
803        assert!(!is_obis_wirkarbeit_kumuliert("1-1:3.8.0"));
804        assert!(!is_obis_wirkarbeit_kumuliert("1-1:4.8.0"));
805        // 15-min partial value — not kumuliert.
806        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.29.0"));
807        // Actual value — not kumuliert.
808        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.5.0"));
809    }
810
811    #[test]
812    fn test_obis_wirkarbeit_quarter_hour() {
813        // Active energy 15-min Lastgang.
814        assert!(is_obis_wirkarbeit_quarter_hour("1-1:1.29.0"));
815        assert!(is_obis_wirkarbeit_quarter_hour("1-1:2.29.0"));
816        assert!(is_obis_wirkarbeit_quarter_hour("1-0:1.29.0*255"));
817        // Cumulated — not 1/4h.
818        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.8.0"));
819        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.9.0"));
820        // Reactive.
821        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:3.29.0"));
822    }
823
824    #[test]
825    fn test_x509_cert_body() {
826        // Valid: 600-char base64 body (well above 100-char floor).
827        let body = "A".repeat(600);
828        assert_eq!(validate_x509_cert_body(&body), ConditionResult::True);
829
830        // Valid with base64 padding and newlines (PEM-style wrapping).
831        let pem_body = "A".repeat(64) + "\n" + &"B".repeat(64) + "\n" + &"C".repeat(64);
832        assert_eq!(validate_x509_cert_body(&pem_body), ConditionResult::True);
833
834        // Valid with explicit PEM armoring — stripped before charset check.
835        let armored = format!(
836            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
837            "A".repeat(200)
838        );
839        assert_eq!(validate_x509_cert_body(&armored), ConditionResult::True);
840
841        // Valid: base64 chars include +, /, =
842        let with_punct = "AB+/==".to_string() + &"A".repeat(200);
843        assert_eq!(validate_x509_cert_body(&with_punct), ConditionResult::True);
844
845        // Too short — not a plausible cert.
846        assert_eq!(validate_x509_cert_body("QUJD"), ConditionResult::False);
847
848        // Non-base64 characters.
849        let invalid_chars = "A".repeat(200) + "!@#";
850        assert_eq!(
851            validate_x509_cert_body(&invalid_chars),
852            ConditionResult::False
853        );
854
855        // Empty is Unknown (consistent with other format validators).
856        assert_eq!(validate_x509_cert_body(""), ConditionResult::Unknown);
857        assert_eq!(validate_x509_cert_body("   \n  "), ConditionResult::Unknown);
858    }
859
860    /// SR-IDs are "C" + ten alphanumerics, not MaLo-shaped: every SR-ID in
861    /// `example_market_communication_bo4e_transactions/` looks like this
862    /// (`LOC+Z19+C816417ST77`), and a MaLo-ID check rejected all of them.
863    #[test]
864    fn test_sr_id() {
865        for real in ["C816417ST77", "CZZ6M5DGSS5", "COPFWS2EX96"] {
866            assert_eq!(validate_sr_id(real), ConditionResult::True, "{real}");
867        }
868        assert_eq!(
869            validate_sr_id("51238696781"),
870            ConditionResult::False,
871            "a MaLo-ID"
872        );
873        assert_eq!(validate_sr_id("C12345"), ConditionResult::False);
874        assert_eq!(validate_sr_id(""), ConditionResult::False);
875    }
876
877    /// Netzlokations-IDs are "E" + ten alphanumerics (`LOC+Z18+E1688117482`,
878    /// `EU5UQAWW8D0` in the example transactions). The generated evaluators
879    /// checked them as MaLo-IDs, so every real one failed `[960]`.
880    #[test]
881    fn test_nelo_id() {
882        for real in ["E1688117482", "EU5UQAWW8D0", "EEW7TM7V906"] {
883            assert_eq!(validate_nelo_id(real), ConditionResult::True, "{real}");
884        }
885        assert_eq!(
886            validate_nelo_id("51238696781"),
887            ConditionResult::False,
888            "a MaLo-ID"
889        );
890        assert_eq!(validate_nelo_id("E123"), ConditionResult::False);
891        assert_eq!(validate_nelo_id("e1688117482"), ConditionResult::False);
892    }
893
894    // --- String validation ---
895
896    #[test]
897    fn test_exact_length() {
898        assert_eq!(
899            validate_exact_length("1234567890123456", 16),
900            ConditionResult::True
901        );
902        assert_eq!(validate_exact_length("123", 16), ConditionResult::False);
903        assert_eq!(validate_exact_length("", 16), ConditionResult::Unknown);
904    }
905
906    #[test]
907    fn test_all_digits() {
908        assert_eq!(validate_all_digits("12345"), ConditionResult::True);
909        assert_eq!(validate_all_digits("123a5"), ConditionResult::False);
910        assert_eq!(validate_all_digits(""), ConditionResult::Unknown);
911    }
912}