mx20022-validate 0.2.0

ISO 20022 message validation: XSD constraints, IBAN/BIC/LEI rules, FedNow, SEPA, and CBPR+ scheme checks
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! SEPA (Single Euro Payments Area) scheme validator.
//!
//! Enforces European Payments Council (EPC) usage guidelines for the SEPA
//! Credit Transfer (SCT) scheme:
//!
//! - Only EUR transactions.
//! - Settlement method must be `CLRG`; charges bearer must be `SLEV`.
//! - Single transaction per group (`NbOfTxs = "1"`).
//! - Debtor and creditor names are required (≤ 70 characters each).
//! - End-to-end ID ≤ 35 characters.
//! - `RmtInf/Ustrd` ≤ 140 characters in total.
//! - Amount in `[0.01, 999_999_999.99]` EUR with at most 2 decimal places.
//! - IBAN is required for both debtor and creditor accounts.
//! - SEPA restricted Latin character set on name and address fields.

use std::any::Any;

use super::xml_scan::{extract_all_elements, extract_attribute, extract_element};
use super::SchemeValidator;
use crate::error::{Severity, ValidationError, ValidationResult};

/// SEPA Credit Transfer scheme validator.
///
/// # Examples
///
/// ```
/// use mx20022_validate::schemes::sepa::SepaValidator;
/// use mx20022_validate::schemes::SchemeValidator;
///
/// let validator = SepaValidator::new();
/// assert_eq!(validator.name(), "SEPA");
/// assert!(validator.supported_messages().contains(&"pacs.008"));
/// ```
pub struct SepaValidator;

impl SepaValidator {
    /// Create a new `SepaValidator`.
    pub fn new() -> Self {
        Self
    }
}

impl Default for SepaValidator {
    fn default() -> Self {
        Self::new()
    }
}

/// Returns `true` if `c` is in the SEPA restricted Latin character set.
fn is_sepa_char(c: char) -> bool {
    matches!(c,
        'A'..='Z'
        | 'a'..='z'
        | '0'..='9'
        | '/' | '-' | '?' | ':' | '(' | ')' | '.' | ',' | '\'' | '+' | ' '
    ) || ('\u{00C0}'..='\u{00FF}').contains(&c)
}

/// Check whether a string contains only characters from the SEPA restricted
/// Latin character set.
///
/// Allowed: a-z A-Z 0-9 / - ? : ( ) . , ' + Space and Latin Extended-A
/// characters with diacritics (U+00C0 – U+00FF, i.e. À–ÿ).
pub fn is_sepa_charset(s: &str) -> bool {
    s.chars().all(is_sepa_char)
}

/// Tags whose text content must conform to the SEPA character set.
const CHARSET_TAGS: &[&str] = &["Nm", "Ustrd", "StrtNm", "TwnNm"];

impl SchemeValidator for SepaValidator {
    fn name(&self) -> &'static str {
        "SEPA"
    }

    fn supported_messages(&self) -> &[&str] {
        &["pacs.008", "pacs.002", "pain.001"]
    }

    fn validate(&self, xml: &str, message_type: &str) -> ValidationResult {
        let short_type = super::short_message_type(message_type);

        if !self.supported_messages().contains(&short_type.as_str()) {
            return ValidationResult::default();
        }

        let mut errors: Vec<ValidationError> = Vec::new();

        // The field-level checks are pacs.008-specific.
        if short_type != "pacs.008" {
            return ValidationResult::new(errors);
        }

        // --- Currency must be EUR -------------------------------------------
        if let Some(ccy) = extract_attribute(xml, "IntrBkSttlmAmt", "Ccy") {
            if ccy != "EUR" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt/@Ccy",
                    Severity::Error,
                    "SEPA_CURRENCY",
                    format!("SEPA only accepts EUR transactions; found currency \"{ccy}\""),
                ));
            }
        }

        // --- ChrgBr must be SLEV -------------------------------------------
        if let Some(chrg_br) = extract_element(xml, "ChrgBr") {
            if chrg_br != "SLEV" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                    Severity::Error,
                    "SEPA_CHRGBR",
                    format!("SEPA SCT requires ChrgBr = \"SLEV\", got \"{chrg_br}\""),
                ));
            }
        } else {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                Severity::Error,
                "SEPA_CHRGBR_REQUIRED",
                "SEPA SCT requires ChrgBr = \"SLEV\"",
            ));
        }

        // --- Settlement method must be CLRG ---------------------------------
        if let Some(sttlm_mtd) = extract_element(xml, "SttlmMtd") {
            if sttlm_mtd != "CLRG" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/GrpHdr/SttlmInf/SttlmMtd",
                    Severity::Error,
                    "SEPA_STTLM_MTD",
                    format!("SEPA requires SttlmMtd = \"CLRG\", got \"{sttlm_mtd}\""),
                ));
            }
        }

        // --- NbOfTxs must be "1" -------------------------------------------
        if let Some(nb) = extract_element(xml, "NbOfTxs") {
            if nb != "1" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/GrpHdr/NbOfTxs",
                    Severity::Error,
                    "SEPA_SINGLE_TX",
                    format!(
                        "SEPA requires one transaction per group (NbOfTxs = \"1\"), got \"{nb}\""
                    ),
                ));
            }
        }

        // --- Debtor name required, max 70 chars -----------------------------
        check_name(xml, "Dbtr", 70, &mut errors, "SEPA_DBTR_NM");
        // --- Creditor name required, max 70 chars ---------------------------
        check_name(xml, "Cdtr", 70, &mut errors, "SEPA_CDTR_NM");

        // --- End-to-end ID max 35 chars -------------------------------------
        if let Some(e2e) = extract_element(xml, "EndToEndId") {
            if e2e.chars().count() > 35 {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/EndToEndId",
                    Severity::Error,
                    "SEPA_E2E_LENGTH",
                    format!(
                        "EndToEndId must be at most 35 characters; got {} characters",
                        e2e.chars().count()
                    ),
                ));
            }
        }

        // --- Ustrd total length max 140 chars --------------------------------
        let ustrd_total: usize = extract_all_elements(xml, "Ustrd")
            .iter()
            .map(|s| s.chars().count())
            .sum();
        if ustrd_total > 140 {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/Ustrd",
                Severity::Error,
                "SEPA_USTRD_LENGTH",
                format!(
                    "RmtInf/Ustrd total length must not exceed 140 characters; got {ustrd_total}"
                ),
            ));
        }

        // --- Amount range ---------------------------------------------------
        if let Some(amt_str) = extract_element(xml, "IntrBkSttlmAmt") {
            Self::validate_sepa_amount(
                amt_str,
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt",
                &mut errors,
            );
        }

        // --- IBAN required for debtor and creditor --------------------------
        // Presence check only — format is validated elsewhere.
        let ibans = extract_all_elements(xml, "IBAN");
        if ibans.is_empty() {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf",
                Severity::Error,
                "SEPA_IBAN_REQUIRED",
                "SEPA requires IBAN for both debtor and creditor accounts; none found",
            ));
        } else if ibans.len() < 2 {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf",
                Severity::Warning,
                "SEPA_IBAN_BOTH",
                "SEPA requires IBAN for both debtor and creditor; only one found",
            ));
        }

        // --- SEPA character set check ---------------------------------------
        for tag in CHARSET_TAGS {
            for value in extract_all_elements(xml, tag) {
                if !is_sepa_charset(value) {
                    // Report just the offending characters.
                    let bad: String = value.chars().filter(|&c| !is_sepa_char(c)).collect();
                    errors.push(ValidationError::new(
                        format!("//{tag}"),
                        Severity::Error,
                        "SEPA_CHARSET",
                        format!(
                            "Field <{tag}> contains characters outside the SEPA restricted \
                             Latin character set: {bad:?}"
                        ),
                    ));
                }
            }
        }

        ValidationResult::new(errors)
    }

    fn validate_typed(&self, msg: &dyn Any, message_type: &str) -> Option<ValidationResult> {
        use mx20022_model::generated::pacs::pacs_008_001_13;

        let short_type = super::short_message_type(message_type);
        if !self.supported_messages().contains(&short_type.as_str()) {
            return None;
        }

        if short_type != "pacs.008" {
            return None;
        }

        let doc = msg.downcast_ref::<pacs_008_001_13::Document>()?;

        Some(self.validate_pacs008_typed(doc))
    }
}

impl SepaValidator {
    /// Validate a SEPA amount string: decimal places, min, max.
    fn validate_sepa_amount(amt_str: &str, path: &str, errors: &mut Vec<ValidationError>) {
        let decimals = amt_str.find('.').map_or(0, |dot| amt_str.len() - dot - 1);
        if decimals > 2 {
            errors.push(ValidationError::new(
                path,
                Severity::Error,
                "SEPA_AMOUNT_DECIMALS",
                format!("SEPA amounts must have at most 2 decimal places; got \"{amt_str}\""),
            ));
        }
        match super::common::parse_amount_cents_lenient(amt_str) {
            Some(cents) => {
                if cents < 1 {
                    errors.push(ValidationError::new(
                        path,
                        Severity::Error,
                        "SEPA_AMOUNT_MIN",
                        format!("SEPA minimum amount is 0.01 EUR; got \"{amt_str}\""),
                    ));
                }
                if cents > 99_999_999_999 {
                    errors.push(ValidationError::new(
                        path,
                        Severity::Error,
                        "SEPA_AMOUNT_MAX",
                        format!("SEPA maximum amount is 999,999,999.99 EUR; got \"{amt_str}\""),
                    ));
                }
            }
            None => {
                errors.push(ValidationError::new(
                    path,
                    Severity::Error,
                    "SEPA_AMOUNT_FORMAT",
                    format!("Cannot parse amount as a number: \"{amt_str}\""),
                ));
            }
        }
    }

    /// Check that a name string conforms to the SEPA restricted Latin character set.
    fn check_sepa_name(name: &str, errors: &mut Vec<ValidationError>) {
        if !is_sepa_charset(name) {
            let bad: String = name.chars().filter(|&c| !is_sepa_char(c)).collect();
            errors.push(ValidationError::new(
                "//Nm",
                Severity::Error,
                "SEPA_CHARSET",
                format!(
                    "Field <Nm> contains characters outside the SEPA restricted \
                     Latin character set: {bad:?}"
                ),
            ));
        }
    }

    /// Typed validation for pacs.008 messages under SEPA SCT rules.
    #[allow(clippy::unused_self)]
    fn validate_pacs008_typed(
        &self,
        doc: &mx20022_model::generated::pacs::pacs_008_001_13::Document,
    ) -> ValidationResult {
        use mx20022_model::generated::pacs::pacs_008_001_13::{
            AccountIdentification4Choice, ChargeBearerType1Code, SettlementMethod1Code,
        };

        let mut errors: Vec<ValidationError> = Vec::new();
        let msg = &doc.fi_to_fi_cstmr_cdt_trf;

        // --- Settlement method must be CLRG ---------------------------------
        if msg.grp_hdr.sttlm_inf.sttlm_mtd != SettlementMethod1Code::Clrg {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/GrpHdr/SttlmInf/SttlmMtd",
                Severity::Error,
                "SEPA_STTLM_MTD",
                format!(
                    "SEPA requires SttlmMtd = \"CLRG\", got {:?}",
                    msg.grp_hdr.sttlm_inf.sttlm_mtd
                ),
            ));
        }

        // --- NbOfTxs must be "1" -------------------------------------------
        if msg.grp_hdr.nb_of_txs.0 != "1" {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/GrpHdr/NbOfTxs",
                Severity::Error,
                "SEPA_SINGLE_TX",
                format!(
                    "SEPA requires one transaction per group (NbOfTxs = \"1\"), got \"{}\"",
                    msg.grp_hdr.nb_of_txs.0
                ),
            ));
        }

        for tx in &msg.cdt_trf_tx_inf {
            // --- Currency must be EUR ---------------------------------------
            let ccy = &tx.intr_bk_sttlm_amt.ccy.0;
            if ccy != "EUR" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt/@Ccy",
                    Severity::Error,
                    "SEPA_CURRENCY",
                    format!("SEPA only accepts EUR transactions; found currency \"{ccy}\""),
                ));
            }

            // --- ChrgBr must be SLEV ----------------------------------------
            if tx.chrg_br != ChargeBearerType1Code::Slev {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                    Severity::Error,
                    "SEPA_CHRGBR",
                    format!("SEPA SCT requires ChrgBr = \"SLEV\", got {:?}", tx.chrg_br),
                ));
            }

            // --- Debtor name required, max 70 chars -------------------------
            match &tx.dbtr.nm {
                None => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Dbtr/Nm",
                        Severity::Error,
                        "SEPA_DBTR_NM",
                        "Dbtr/Nm is required for SEPA",
                    ));
                }
                Some(nm) if nm.0.chars().count() > 70 => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Dbtr/Nm",
                        Severity::Error,
                        "SEPA_DBTR_NM",
                        format!(
                            "Dbtr/Nm must be at most 70 characters; got {} characters",
                            nm.0.chars().count()
                        ),
                    ));
                }
                Some(_) => {}
            }

            // --- Creditor name required, max 70 chars -----------------------
            match &tx.cdtr.nm {
                None => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Cdtr/Nm",
                        Severity::Error,
                        "SEPA_CDTR_NM",
                        "Cdtr/Nm is required for SEPA",
                    ));
                }
                Some(nm) if nm.0.chars().count() > 70 => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Cdtr/Nm",
                        Severity::Error,
                        "SEPA_CDTR_NM",
                        format!(
                            "Cdtr/Nm must be at most 70 characters; got {} characters",
                            nm.0.chars().count()
                        ),
                    ));
                }
                Some(_) => {}
            }

            // --- End-to-end ID max 35 chars ---------------------------------
            // Max35Text enforces 35 via XSD. Typed path trusts XSD validation
            // for length but checks that it's present (it's a required field).

            // --- Ustrd total length max 140 chars ---------------------------
            if let Some(rmt_inf) = &tx.rmt_inf {
                let ustrd_total: usize = rmt_inf.ustrd.iter().map(|u| u.0.chars().count()).sum();
                if ustrd_total > 140 {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/Ustrd",
                        Severity::Error,
                        "SEPA_USTRD_LENGTH",
                        format!(
                            "RmtInf/Ustrd total length must not exceed 140 characters; got {ustrd_total}"
                        ),
                    ));
                }

                // SEPA character set check on Ustrd.
                for ustrd in &rmt_inf.ustrd {
                    if !is_sepa_charset(&ustrd.0) {
                        let bad: String = ustrd.0.chars().filter(|&c| !is_sepa_char(c)).collect();
                        errors.push(ValidationError::new(
                            "//Ustrd",
                            Severity::Error,
                            "SEPA_CHARSET",
                            format!(
                                "Field <Ustrd> contains characters outside the SEPA restricted \
                                 Latin character set: {bad:?}"
                            ),
                        ));
                    }
                }
            }

            // --- Amount range -----------------------------------------------
            let amt_str: &str = &tx.intr_bk_sttlm_amt.value.0;
            Self::validate_sepa_amount(
                amt_str,
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt",
                &mut errors,
            );

            // --- SEPA character set check on names --------------------------
            if let Some(nm) = &tx.dbtr.nm {
                Self::check_sepa_name(&nm.0, &mut errors);
            }
            if let Some(nm) = &tx.cdtr.nm {
                Self::check_sepa_name(&nm.0, &mut errors);
            }

            // --- IBAN required for debtor and creditor accounts ---
            let has_dbtr_iban = tx.dbtr_acct.as_ref().is_some_and(|acct| {
                acct.id.as_ref().is_some_and(|choice| {
                    matches!(choice.inner, AccountIdentification4Choice::IBAN(_))
                })
            });
            let has_cdtr_iban = tx.cdtr_acct.as_ref().is_some_and(|acct| {
                acct.id.as_ref().is_some_and(|choice| {
                    matches!(choice.inner, AccountIdentification4Choice::IBAN(_))
                })
            });
            if !has_dbtr_iban && !has_cdtr_iban {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf",
                    Severity::Error,
                    "SEPA_IBAN_REQUIRED",
                    "SEPA requires IBAN for both debtor and creditor accounts; none found",
                ));
            } else if !has_dbtr_iban || !has_cdtr_iban {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf",
                    Severity::Warning,
                    "SEPA_IBAN_BOTH",
                    "SEPA requires IBAN for both debtor and creditor; only one found",
                ));
            }
        }

        ValidationResult::new(errors)
    }
}

/// Validate that the `<Nm>` child of `<parent_tag>` is present and within
/// `max_len` characters.
fn check_name(
    xml: &str,
    parent_tag: &str,
    max_len: usize,
    errors: &mut Vec<ValidationError>,
    rule_id: &str,
) {
    let path = format!("/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/{parent_tag}");
    super::common::check_name_in_parent(
        xml,
        parent_tag,
        Some(max_len),
        &path,
        rule_id,
        "SEPA",
        errors,
        true,
    );
}

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

    #[test]
    fn name_is_sepa() {
        assert_eq!(SepaValidator::new().name(), "SEPA");
    }

    #[test]
    fn supports_pacs008() {
        let v = SepaValidator::new();
        assert!(v.supported_messages().contains(&"pacs.008"));
    }

    #[test]
    fn unsupported_message_returns_empty() {
        let v = SepaValidator::new();
        let result = v.validate("<xml/>", "pacs.009.001.10");
        assert!(result.errors.is_empty());
    }

    #[test]
    fn sepa_charset_ascii_allowed() {
        assert!(is_sepa_charset("Alice Smith / 123"));
    }

    #[test]
    fn sepa_charset_diacritics_allowed() {
        assert!(is_sepa_charset("Müller")); // ü is U+00FC, in range
    }

    #[test]
    fn sepa_charset_control_chars_rejected() {
        assert!(!is_sepa_charset("Alice\x01Smith"));
    }

    #[test]
    fn sepa_charset_cyrillic_rejected() {
        assert!(!is_sepa_charset("Алиса")); // Cyrillic
    }

    /// Build a minimal pacs.008 XML with the given amount for SEPA validation.
    fn sepa_xml_with_amount(amount: &str) -> String {
        format!(
            r#"<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.13">
  <FIToFICstmrCdtTrf>
    <GrpHdr><NbOfTxs>1</NbOfTxs><SttlmInf><SttlmMtd>CLRG</SttlmMtd></SttlmInf></GrpHdr>
    <CdtTrfTxInf>
      <IntrBkSttlmAmt Ccy="EUR">{amount}</IntrBkSttlmAmt>
      <ChrgBr>SLEV</ChrgBr>
      <Dbtr><Nm>Alice</Nm></Dbtr>
      <Cdtr><Nm>Bob</Nm></Cdtr>
      <DbtrAgt><FinInstnId><BICFI>BANKDEFF</BICFI></FinInstnId></DbtrAgt>
      <CdtrAgt><FinInstnId><BICFI>BANKDEFF</BICFI></FinInstnId></CdtrAgt>
      <DbtrAcct><Id><IBAN>DE89370400440532013000</IBAN></Id></DbtrAcct>
      <CdtrAcct><Id><IBAN>DE89370400440532013000</IBAN></Id></CdtrAcct>
    </CdtTrfTxInf>
  </FIToFICstmrCdtTrf>
</Document>"#
        )
    }

    fn has_error(result: &ValidationResult, code: &str) -> bool {
        result.errors.iter().any(|e| e.rule_id == code)
    }

    #[test]
    fn sepa_amount_at_max_boundary() {
        let v = SepaValidator::new();
        let xml = sepa_xml_with_amount("999999999.99");
        let result = v.validate(&xml, "pacs.008.001.13");
        assert!(
            !has_error(&result, "SEPA_AMOUNT_MAX"),
            "999999999.99 should be within SEPA max; errors: {:?}",
            result.errors
        );
    }

    #[test]
    fn sepa_amount_just_under_max() {
        let v = SepaValidator::new();
        let xml = sepa_xml_with_amount("999999999.98");
        let result = v.validate(&xml, "pacs.008.001.13");
        assert!(!has_error(&result, "SEPA_AMOUNT_MAX"));
    }

    #[test]
    fn sepa_amount_exceeds_max() {
        let v = SepaValidator::new();
        let xml = sepa_xml_with_amount("1000000000.00");
        let result = v.validate(&xml, "pacs.008.001.13");
        assert!(
            has_error(&result, "SEPA_AMOUNT_MAX"),
            "1000000000.00 should exceed SEPA max"
        );
    }

    #[test]
    fn sepa_amount_at_min_boundary() {
        let v = SepaValidator::new();
        let xml = sepa_xml_with_amount("0.01");
        let result = v.validate(&xml, "pacs.008.001.13");
        assert!(
            !has_error(&result, "SEPA_AMOUNT_MIN"),
            "0.01 should be within SEPA min"
        );
    }

    #[test]
    fn sepa_amount_below_min() {
        let v = SepaValidator::new();
        let xml = sepa_xml_with_amount("0.00");
        let result = v.validate(&xml, "pacs.008.001.13");
        assert!(
            has_error(&result, "SEPA_AMOUNT_MIN"),
            "0.00 should be below SEPA min"
        );
    }
}