1use super::evaluator::ConditionResult;
8
9pub 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
15pub 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
36pub 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
51pub 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
82pub fn is_edifact_number(value: &str) -> bool {
86 edifact_number(value).is_some()
87}
88
89fn 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
108pub fn validate_hhmm_equals(dtm_value: &str, expected_hhmm: &str) -> ConditionResult {
117 if dtm_value.len() < 12 {
118 return ConditionResult::False;
120 }
121 ConditionResult::from(&dtm_value[8..12] == expected_hhmm)
122}
123
124pub 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
135pub 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
147pub fn validate_timezone_utc(dtm_value: &str) -> ConditionResult {
158 if dtm_value.len() < 15 || !dtm_value.is_char_boundary(dtm_value.len() - 3) {
159 return ConditionResult::False;
161 }
162 ConditionResult::from(&dtm_value[dtm_value.len() - 3..] == "+00")
163}
164
165pub 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
177pub 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
191pub 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 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
226pub 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
234fn 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
245pub fn validate_sr_id(value: &str) -> ConditionResult {
248 validate_prefixed_location_id(value, 'C')
249}
250
251pub fn validate_nelo_id(value: &str) -> ConditionResult {
253 validate_prefixed_location_id(value, 'E')
254}
255
256pub fn parse_obis(value: &str) -> Option<(u32, u32)> {
273 let value = value.trim();
274 let (_ab, cde) = value.split_once(':')?;
276 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
284pub fn is_obis_wirkarbeit_kumuliert(value: &str) -> bool {
290 matches!(parse_obis(value), Some((1 | 2, 8 | 9)))
291}
292
293pub fn is_obis_wirkarbeit_quarter_hour(value: &str) -> bool {
300 matches!(parse_obis(value), Some((1 | 2, 29)))
301}
302
303pub fn validate_x509_cert_body(value: &str) -> ConditionResult {
322 let trimmed = value.trim();
323 if trimmed.is_empty() {
324 return ConditionResult::Unknown;
325 }
326 let body = trimmed
329 .trim_start_matches("-----BEGIN CERTIFICATE-----")
330 .trim_end_matches("-----END CERTIFICATE-----")
331 .trim();
332 let chars_ok = body.chars().all(|c| {
333 c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '\n' | '\r' | '\t' | ' ')
334 });
335 let len_ok = body.chars().filter(|c| !c.is_whitespace()).count() >= 100;
338 ConditionResult::from(chars_ok && len_ok)
339}
340
341pub fn validate_zahlpunkt(value: &str) -> ConditionResult {
343 if value.len() != 33 {
344 return ConditionResult::from(false);
345 }
346 ConditionResult::from(value.chars().all(|c| c.is_ascii_alphanumeric()))
347}
348
349pub fn validate_malo_or_zahlpunkt(value: &str) -> ConditionResult {
351 if value.len() == 11 && validate_malo_id(value).is_true() {
352 return ConditionResult::True;
353 }
354 if value.len() == 33 && validate_zahlpunkt(value).is_true() {
355 return ConditionResult::True;
356 }
357 ConditionResult::False
358}
359
360pub fn validate_artikel_pattern(value: &str, segment_lengths: &[usize]) -> ConditionResult {
369 if value.is_empty() {
370 return ConditionResult::Unknown;
371 }
372 let parts: Vec<&str> = value.split('-').collect();
373 if parts.len() != segment_lengths.len() {
374 return ConditionResult::from(false);
375 }
376 let valid = parts
377 .iter()
378 .zip(segment_lengths.iter())
379 .all(|(part, &expected_len)| {
380 part.len() == expected_len && part.chars().all(|c| c.is_ascii_digit())
381 });
382 ConditionResult::from(valid)
383}
384
385pub fn validate_exact_length(value: &str, expected: usize) -> ConditionResult {
389 if value.is_empty() {
390 return ConditionResult::Unknown;
391 }
392 ConditionResult::from(value.len() == expected)
393}
394
395pub fn validate_max_length(value: &str, max: usize) -> ConditionResult {
397 if value.is_empty() {
398 return ConditionResult::Unknown;
399 }
400 ConditionResult::from(value.len() <= max)
401}
402
403pub fn validate_all_digits(value: &str) -> ConditionResult {
405 if value.is_empty() {
406 return ConditionResult::Unknown;
407 }
408 ConditionResult::from(value.chars().all(|c| c.is_ascii_digit()))
409}
410
411pub fn utc_now_ccyymmddhhmm() -> String {
413 chrono::Utc::now().format("%Y%m%d%H%M").to_string()
414}
415
416pub fn german_local_time(value: &str) -> Option<chrono::NaiveDateTime> {
423 use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, Weekday};
424 let value = value.replace('?', "");
425 let stamp = NaiveDateTime::parse_from_str(value.get(..12)?, "%Y%m%d%H%M").ok()?;
426 let offset: i64 = match value.get(12..) {
427 None | Some("") => 0,
428 Some(zone) => zone.parse().ok()?,
429 };
430 let utc = stamp - Duration::hours(offset);
431 let switch = |month: u32| {
432 let mut day = NaiveDate::from_ymd_opt(utc.year(), month, 31)?;
433 while day.weekday() != Weekday::Sun {
434 day = day.pred_opt()?;
435 }
436 day.and_hms_opt(1, 0, 0)
437 };
438 let summer = utc >= switch(3)? && utc < switch(10)?;
439 Some(utc + Duration::hours(if summer { 2 } else { 1 }))
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 #[test]
449 fn test_max_decimal_places() {
450 assert_eq!(
451 validate_max_decimal_places("123.45", 2),
452 ConditionResult::True
453 );
454 assert_eq!(
455 validate_max_decimal_places("123.456", 2),
456 ConditionResult::False
457 );
458 assert_eq!(validate_max_decimal_places("123", 2), ConditionResult::True);
459 assert_eq!(validate_max_decimal_places("0.1", 3), ConditionResult::True);
460 assert_eq!(validate_max_decimal_places("", 2), ConditionResult::Unknown);
461 }
462
463 #[test]
464 fn test_no_decimal_places() {
465 assert_eq!(validate_max_decimal_places("100", 0), ConditionResult::True);
466 assert_eq!(
467 validate_max_decimal_places("100.5", 0),
468 ConditionResult::False
469 );
470 }
471
472 #[test]
473 fn test_max_integer_digits() {
474 assert_eq!(
475 validate_max_integer_digits("1234", 4),
476 ConditionResult::True
477 );
478 assert_eq!(
479 validate_max_integer_digits("12345", 4),
480 ConditionResult::False
481 );
482 assert_eq!(
483 validate_max_integer_digits("-123.45", 4),
484 ConditionResult::True
485 );
486 assert_eq!(validate_max_integer_digits("", 4), ConditionResult::Unknown);
487 }
488
489 #[test]
492 fn test_validate_numeric() {
493 assert_eq!(validate_numeric("5.0", ">=", 0.0), ConditionResult::True);
494 assert_eq!(validate_numeric("-1.0", ">=", 0.0), ConditionResult::False);
495 assert_eq!(validate_numeric("1", "==", 1.0), ConditionResult::True);
496 assert_eq!(validate_numeric("2", "==", 1.0), ConditionResult::False);
497 assert_eq!(validate_numeric("0", ">", 0.0), ConditionResult::False);
498 assert_eq!(validate_numeric("1", ">", 0.0), ConditionResult::True);
499 assert_eq!(validate_numeric("abc", ">=", 0.0), ConditionResult::False);
502 assert_eq!(
503 validate_numeric("O5D2DXBG1A", ">", 0.0),
504 ConditionResult::False
505 );
506 assert_eq!(validate_numeric("NaN", ">", 0.0), ConditionResult::False);
507 assert_eq!(validate_numeric("inf", ">", 0.0), ConditionResult::False);
508 assert_eq!(validate_numeric("1e3", ">", 0.0), ConditionResult::False);
509 assert_eq!(validate_numeric("0,5", ">", 0.0), ConditionResult::True);
511 assert_eq!(validate_numeric("-2", "<=", 0.0), ConditionResult::True);
512 assert_eq!(validate_numeric("", ">", 0.0), ConditionResult::Unknown);
513 }
514
515 #[test]
518 fn test_hhmm_equals() {
519 assert_eq!(
520 validate_hhmm_equals("202601012200+00", "2200"),
521 ConditionResult::True
522 );
523 assert_eq!(
524 validate_hhmm_equals("202601012300+00", "2200"),
525 ConditionResult::False
526 );
527 assert_eq!(
528 validate_hhmm_equals("short", "2200"),
529 ConditionResult::False
530 );
531 }
532
533 #[test]
534 fn test_hhmm_range() {
535 assert_eq!(
536 validate_hhmm_range("202601011530+00", "0000", "2359"),
537 ConditionResult::True
538 );
539 assert_eq!(
540 validate_hhmm_range("202601010000+00", "0000", "2359"),
541 ConditionResult::True
542 );
543 assert_eq!(
544 validate_hhmm_range("202601012359+00", "0000", "2359"),
545 ConditionResult::True
546 );
547 }
548
549 #[test]
550 fn test_mmddhhmm_equals() {
551 assert_eq!(
552 validate_mmddhhmm_equals("202612312300+00", "12312300"),
553 ConditionResult::True
554 );
555 assert_eq!(
556 validate_mmddhhmm_equals("202601012200+00", "12312300"),
557 ConditionResult::False
558 );
559 }
560
561 #[test]
562 fn test_timezone_utc() {
563 assert_eq!(
564 validate_timezone_utc("202601012200+00"),
565 ConditionResult::True
566 );
567 assert_eq!(
568 validate_timezone_utc("202601012200+01"),
569 ConditionResult::False
570 );
571 assert_eq!(
572 validate_timezone_utc("202601012200"),
573 ConditionResult::False
574 );
575 assert_eq!(
577 validate_timezone_utc("20260101220000+00"),
578 ConditionResult::True
579 );
580 assert_eq!(
581 validate_timezone_utc("20260101220000+01"),
582 ConditionResult::False
583 );
584 }
585
586 #[test]
589 fn test_email() {
590 assert_eq!(validate_email("user@example.com"), ConditionResult::True);
591 assert_eq!(validate_email("nope"), ConditionResult::False);
592 assert_eq!(validate_email("has@but-no-dot"), ConditionResult::False);
593 assert_eq!(validate_email(""), ConditionResult::Unknown);
594 }
595
596 #[test]
597 fn test_phone() {
598 assert_eq!(validate_phone("+4930123456"), ConditionResult::True);
599 assert_eq!(validate_phone("030123456"), ConditionResult::False);
600 assert_eq!(validate_phone("+"), ConditionResult::False);
601 assert_eq!(validate_phone("+49 30 123"), ConditionResult::False); assert_eq!(validate_phone(""), ConditionResult::Unknown);
603 }
604
605 #[test]
608 fn test_malo_id() {
609 assert_eq!(validate_malo_id("51238696781"), ConditionResult::True);
613 assert_eq!(validate_malo_id("41373559241"), ConditionResult::True);
614 assert_eq!(validate_malo_id("56789012345"), ConditionResult::True);
615 assert_eq!(validate_malo_id("52935155442"), ConditionResult::True);
616
617 assert_eq!(validate_malo_id("41373559240"), ConditionResult::False); assert_eq!(validate_malo_id("512386967890"), ConditionResult::False); assert_eq!(validate_malo_id("1234567890"), ConditionResult::False); assert_eq!(validate_malo_id("abcdefghijk"), ConditionResult::False); }
623
624 #[test]
625 fn test_zahlpunkt() {
626 let valid = "DE0001234567890123456789012345678";
627 assert_eq!(valid.len(), 33);
628 assert_eq!(validate_zahlpunkt(valid), ConditionResult::True);
629 assert_eq!(validate_zahlpunkt("tooshort"), ConditionResult::False);
630 }
631
632 #[test]
635 fn test_artikel_pattern() {
636 assert_eq!(
637 validate_artikel_pattern("1-23-4", &[1, 2, 1]),
638 ConditionResult::True
639 );
640 assert_eq!(
641 validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3]),
642 ConditionResult::True
643 );
644 assert_eq!(
645 validate_artikel_pattern("1-23-4-56", &[1, 2, 1, 3]),
646 ConditionResult::False
647 );
648 assert_eq!(
649 validate_artikel_pattern("1-AB-4", &[1, 2, 1]),
650 ConditionResult::False
651 );
652 assert_eq!(
653 validate_artikel_pattern("", &[1, 2, 1]),
654 ConditionResult::Unknown
655 );
656 }
657
658 #[test]
661 fn test_tr_id() {
662 assert_eq!(validate_tr_id("ABC123"), ConditionResult::True);
663 assert_eq!(validate_tr_id("A"), ConditionResult::True);
664 assert_eq!(validate_tr_id(&"A".repeat(35)), ConditionResult::True);
665 assert_eq!(validate_tr_id(&"A".repeat(36)), ConditionResult::False);
666 assert_eq!(validate_tr_id("has spaces"), ConditionResult::False);
667 assert_eq!(validate_tr_id("has-dash"), ConditionResult::False);
668 assert_eq!(validate_tr_id(""), ConditionResult::Unknown);
669 }
670
671 #[test]
672 fn test_parse_obis() {
673 assert_eq!(parse_obis("1-1:1.8.0"), Some((1, 8)));
674 assert_eq!(parse_obis("1-1:2.29.0"), Some((2, 29)));
675 assert_eq!(parse_obis("1-0:1.8.0*255"), Some((1, 8))); assert_eq!(parse_obis(" 1-1:1.8.0 "), Some((1, 8))); assert_eq!(parse_obis("no-colon"), None);
678 assert_eq!(parse_obis("1-1:abc.8.0"), None);
679 assert_eq!(parse_obis(""), None);
680 }
681
682 #[test]
683 fn test_obis_wirkarbeit_kumuliert() {
684 assert!(is_obis_wirkarbeit_kumuliert("1-1:1.8.0"));
686 assert!(is_obis_wirkarbeit_kumuliert("1-1:2.8.0"));
687 assert!(is_obis_wirkarbeit_kumuliert("1-1:1.9.0"));
688 assert!(is_obis_wirkarbeit_kumuliert("1-1:2.9.0"));
689 assert!(is_obis_wirkarbeit_kumuliert("1-0:1.8.0*255"));
690 assert!(!is_obis_wirkarbeit_kumuliert("1-1:3.8.0"));
692 assert!(!is_obis_wirkarbeit_kumuliert("1-1:4.8.0"));
693 assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.29.0"));
695 assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.5.0"));
697 }
698
699 #[test]
700 fn test_obis_wirkarbeit_quarter_hour() {
701 assert!(is_obis_wirkarbeit_quarter_hour("1-1:1.29.0"));
703 assert!(is_obis_wirkarbeit_quarter_hour("1-1:2.29.0"));
704 assert!(is_obis_wirkarbeit_quarter_hour("1-0:1.29.0*255"));
705 assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.8.0"));
707 assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.9.0"));
708 assert!(!is_obis_wirkarbeit_quarter_hour("1-1:3.29.0"));
710 }
711
712 #[test]
713 fn test_x509_cert_body() {
714 let body = "A".repeat(600);
716 assert_eq!(validate_x509_cert_body(&body), ConditionResult::True);
717
718 let pem_body = "A".repeat(64) + "\n" + &"B".repeat(64) + "\n" + &"C".repeat(64);
720 assert_eq!(validate_x509_cert_body(&pem_body), ConditionResult::True);
721
722 let armored = format!(
724 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
725 "A".repeat(200)
726 );
727 assert_eq!(validate_x509_cert_body(&armored), ConditionResult::True);
728
729 let with_punct = "AB+/==".to_string() + &"A".repeat(200);
731 assert_eq!(validate_x509_cert_body(&with_punct), ConditionResult::True);
732
733 assert_eq!(validate_x509_cert_body("QUJD"), ConditionResult::False);
735
736 let invalid_chars = "A".repeat(200) + "!@#";
738 assert_eq!(
739 validate_x509_cert_body(&invalid_chars),
740 ConditionResult::False
741 );
742
743 assert_eq!(validate_x509_cert_body(""), ConditionResult::Unknown);
745 assert_eq!(validate_x509_cert_body(" \n "), ConditionResult::Unknown);
746 }
747
748 #[test]
752 fn test_sr_id() {
753 for real in ["C816417ST77", "CZZ6M5DGSS5", "COPFWS2EX96"] {
754 assert_eq!(validate_sr_id(real), ConditionResult::True, "{real}");
755 }
756 assert_eq!(
757 validate_sr_id("51238696781"),
758 ConditionResult::False,
759 "a MaLo-ID"
760 );
761 assert_eq!(validate_sr_id("C12345"), ConditionResult::False);
762 assert_eq!(validate_sr_id(""), ConditionResult::False);
763 }
764
765 #[test]
769 fn test_nelo_id() {
770 for real in ["E1688117482", "EU5UQAWW8D0", "EEW7TM7V906"] {
771 assert_eq!(validate_nelo_id(real), ConditionResult::True, "{real}");
772 }
773 assert_eq!(
774 validate_nelo_id("51238696781"),
775 ConditionResult::False,
776 "a MaLo-ID"
777 );
778 assert_eq!(validate_nelo_id("E123"), ConditionResult::False);
779 assert_eq!(validate_nelo_id("e1688117482"), ConditionResult::False);
780 }
781
782 #[test]
785 fn test_exact_length() {
786 assert_eq!(
787 validate_exact_length("1234567890123456", 16),
788 ConditionResult::True
789 );
790 assert_eq!(validate_exact_length("123", 16), ConditionResult::False);
791 assert_eq!(validate_exact_length("", 16), ConditionResult::Unknown);
792 }
793
794 #[test]
795 fn test_all_digits() {
796 assert_eq!(validate_all_digits("12345"), ConditionResult::True);
797 assert_eq!(validate_all_digits("123a5"), ConditionResult::False);
798 assert_eq!(validate_all_digits(""), ConditionResult::Unknown);
799 }
800}