sepa 0.9.0

SEPA identifiers and ISO 20022 payment messages: builders, bank-report parsers, validation and integer monetary arithmetic.
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! ISO 11649 RF Creditor Reference and structured remittance information.
//!
//! An RF Creditor Reference is a self-checking invoice reference that survives
//! the round trip through the banking system: the creditor puts it on the
//! invoice, the debtor's bank carries it in `RmtInf/Strd/CdtrRefInf/Ref`, and it
//! comes back on the camt statement — letting the creditor match an incoming
//! payment to an invoice without human intervention.
//!
//! ## Structure (ISO 11649:2009 §5)
//!
//! ```text
//! RF 18 539007547034
//! ─┬ ─┬ ──────┬─────
//!  │  │       └─ creditor's own reference, 1–21 chars, A–Z and 0–9
//!  │  └───────── check digits, ISO 7064 MOD 97-10
//!  └──────────── literal "RF"
//! ```
//!
//! Maximum 25 characters. Printed in groups of four for legibility.
//!
//! ## In pain.001 / pain.008
//!
//! ```xml
//! <RmtInf>
//!   <Strd>
//!     <CdtrRefInf>
//!       <Tp><CdOrPrtry><Cd>SCOR</Cd></CdOrPrtry><Issr>ISO</Issr></Tp>
//!       <Ref>RF18539007547034</Ref>
//!     </CdtrRefInf>
//!   </Strd>
//! </RmtInf>
//! ```
//!
//! The EPC guidelines permit only `SCOR` in `Cd`, and require `Issr` to be
//! `ISO` when `Ref` carries an RF reference. Note the element is `CdOrPrtry`
//! (capital `O`) — a spelling several implementations get wrong, producing
//! schema-invalid output.
//!
//! ## Examples
//!
//! ```
//! use sepa::reference::RfReference;
//!
//! // Generate from your own invoice number — check digits are computed for you.
//! let rf = RfReference::generate("2348231")?;
//! assert_eq!(rf.as_str(), "RF712348231");
//!
//! // Validate one that arrived from outside.
//! let parsed: RfReference = "RF18 5390 0754 7034".parse()?;
//! assert_eq!(parsed.as_str(), "RF18539007547034");
//! assert_eq!(parsed.reference(), "539007547034");
//! assert_eq!(parsed.to_string(), "RF18 5390 0754 7034"); // grouped for printing
//! # Ok::<(), sepa::reference::RfReferenceError>(())
//! ```

use std::str::FromStr;

use crate::validate::{
    MAX_ID_LEN, MAX_STRUCTURED_REMITTANCE_LEN, ValidationError, check_remittance, check_text,
};

/// Maximum total length of an RF Creditor Reference, including `RF` and the
/// check digits (ISO 11649 §5).
pub const MAX_RF_LEN: usize = 25;

/// Maximum length of the creditor's own part of an RF reference.
pub const MAX_RF_REFERENCE_LEN: usize = MAX_RF_LEN - 4;

// ── error ─────────────────────────────────────────────────────────────────────

/// Error returned when an RF Creditor Reference is invalid.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RfReferenceError {
    /// The reference does not begin with `RF`.
    #[error("RF Creditor Reference must start with \"RF\", got {prefix:?}")]
    MissingRfPrefix {
        /// The first two characters that were found.
        prefix: String,
    },

    /// The reference is empty, or longer than 25 characters.
    #[error("RF Creditor Reference length {len} is outside the valid range 5–{MAX_RF_LEN}")]
    InvalidLength {
        /// The actual length after whitespace was stripped.
        len: usize,
    },

    /// The reference contains a character outside `A–Z` and `0–9`.
    #[error("RF Creditor Reference contains invalid character {ch:?}")]
    InvalidCharacter {
        /// The offending character.
        ch: char,
    },

    /// The check digits do not match the reference.
    #[error("RF Creditor Reference check digits are {actual}, expected {expected}")]
    InvalidChecksum {
        /// The check digits required by ISO 11649.
        expected: String,
        /// The check digits actually present.
        actual: String,
    },
}

// ── RfReference ───────────────────────────────────────────────────────────────

/// A validated ISO 11649 RF Creditor Reference.
///
/// Constructed only via [`RfReference::generate`] or [`RfReference::from_str`],
/// both of which enforce the MOD 97-10 check digits — so a value of this type
/// is always well-formed.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RfReference(String);

impl RfReference {
    /// The reference in electronic format, e.g. `"RF18539007547034"`.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The two check digits (characters 3–4).
    #[inline]
    #[must_use]
    pub fn check_digits(&self) -> &str {
        self.0.get(2..4).unwrap_or_default()
    }

    /// The creditor's own reference — everything after the check digits.
    #[inline]
    #[must_use]
    pub fn reference(&self) -> &str {
        self.0.get(4..).unwrap_or_default()
    }

    /// Compute an RF reference for `reference`, deriving the check digits.
    ///
    /// Non-alphanumeric characters are stripped first, as ISO 11649 §6.3.1
    /// requires, and lower-case letters are upper-cased. So `"inv-2026/0042"`
    /// and `"INV20260042"` produce the same reference.
    ///
    /// # Errors
    ///
    /// Returns [`RfReferenceError::InvalidLength`] when `reference` is empty or
    /// longer than 21 characters after stripping.
    ///
    /// # Examples
    ///
    /// ```
    /// use sepa::reference::RfReference;
    ///
    /// // The worked example from ISO 11649 Annex B.
    /// assert_eq!(RfReference::generate("2348231")?.as_str(), "RF712348231");
    ///
    /// // Separators are stripped before the check digits are computed.
    /// let a = RfReference::generate("inv-2026/0042")?;
    /// let b = RfReference::generate("INV20260042")?;
    /// assert_eq!(a, b);
    /// # Ok::<(), sepa::reference::RfReferenceError>(())
    /// ```
    pub fn generate(reference: &str) -> Result<Self, RfReferenceError> {
        let core: String = reference
            .chars()
            .filter(char::is_ascii_alphanumeric)
            .map(|c| c.to_ascii_uppercase())
            .collect();

        if core.is_empty() || core.len() > MAX_RF_REFERENCE_LEN {
            return Err(RfReferenceError::InvalidLength {
                len: core.len() + 4,
            });
        }

        let check = check_digits_for(&core);
        Ok(Self(format!("RF{check}{core}")))
    }

    /// Compute the check digits an RF reference would carry, without building one.
    ///
    /// # Examples
    ///
    /// ```
    /// use sepa::reference::RfReference;
    /// assert_eq!(RfReference::check_digits_for("2348231"), "71");
    /// assert_eq!(RfReference::check_digits_for("539007547034"), "18");
    /// ```
    #[must_use]
    pub fn check_digits_for(reference: &str) -> String {
        let core: String = reference
            .chars()
            .filter(char::is_ascii_alphanumeric)
            .map(|c| c.to_ascii_uppercase())
            .collect();
        check_digits_for(&core)
    }
}

/// ISO 11649 §6.3: append `"RF00"`, expand letters (A=10 … Z=35), then `98 − n mod 97`.
fn check_digits_for(core: &str) -> String {
    let remainder = mod97(core.chars().chain("RF00".chars()));
    format!("{:02}", 98 - remainder)
}

/// Streaming ISO 7064 MOD 97-10 over alphanumeric characters.
///
/// Digits contribute one decimal place, letters two (their 10–35 value), so the
/// running remainder never approaches `u64` overflow.
fn mod97(chars: impl Iterator<Item = char>) -> u64 {
    chars.fold(0u64, |acc, c| match c.to_digit(36) {
        Some(d) if d < 10 => (acc * 10 + u64::from(d)) % 97,
        Some(d) => (acc * 100 + u64::from(d)) % 97,
        None => acc,
    })
}

impl FromStr for RfReference {
    type Err = RfReferenceError;

    /// Parse and validate an RF reference in electronic or printed format.
    ///
    /// Whitespace is stripped and letters are upper-cased before validation.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let normalised: String = s
            .chars()
            .filter(|c| !c.is_whitespace())
            .map(|c| c.to_ascii_uppercase())
            .collect();

        // Shortest useful reference is "RF" + 2 check digits + 1 char.
        // Counted in characters: a non-ASCII character is rejected just below,
        // but the length reported for one must not be its UTF-8 byte count.
        let len = normalised.chars().count();
        if !(5..=MAX_RF_LEN).contains(&len) {
            return Err(RfReferenceError::InvalidLength { len });
        }
        if let Some(ch) = normalised.chars().find(|c| !c.is_ascii_alphanumeric()) {
            return Err(RfReferenceError::InvalidCharacter { ch });
        }
        let prefix = normalised.get(..2).unwrap_or_default();
        if prefix != "RF" {
            return Err(RfReferenceError::MissingRfPrefix {
                prefix: prefix.to_owned(),
            });
        }

        // ISO 11649 §6.2: rotate the first four characters to the end; valid iff
        // the remainder is 1.
        let (head, tail) = normalised.split_at(4);
        if mod97(tail.chars().chain(head.chars())) == 1 {
            Ok(Self(normalised))
        } else {
            let expected = check_digits_for(tail);
            Err(RfReferenceError::InvalidChecksum {
                expected,
                actual: normalised.get(2..4).unwrap_or_default().to_owned(),
            })
        }
    }
}

impl TryFrom<&str> for RfReference {
    type Error = RfReferenceError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.parse()
    }
}

impl std::fmt::Display for RfReference {
    /// Printed format: groups of four, e.g. `"RF18 5390 0754 7034"`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Validation guarantees pure ASCII — see `crate::iban::group_of_four`.
        for (i, chunk) in crate::iban::group_of_four(&self.0).enumerate() {
            if i > 0 {
                f.write_str(" ")?;
            }
            f.write_str(chunk)?;
        }
        Ok(())
    }
}

impl AsRef<str> for RfReference {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl From<RfReference> for String {
    fn from(r: RfReference) -> Self {
        r.0
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for RfReference {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for RfReference {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

// ── RemittanceInfo ────────────────────────────────────────────────────────────

/// What to put in `RmtInf` — free text or a structured creditor reference.
///
/// The EPC permits **one or the other, not both**, and allows only a single
/// `Strd` occurrence.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RemittanceInfo {
    /// Unstructured free text (`RmtInf/Ustrd`), up to 140 characters.
    ///
    /// The German *Verwendungszweck*. Readable by humans, useless to machines.
    Unstructured(String),

    /// A structured ISO 11649 creditor reference (`RmtInf/Strd/CdtrRefInf`).
    ///
    /// Prefer this when you control the invoice: it round-trips through the
    /// banking system and lets you reconcile automatically.
    Structured(RfReference),

    /// A structured reference issued under a national scheme rather than
    /// ISO 11649 — e.g. a Belgian structured communication.
    ///
    /// Emitted with `Cd = SCOR` but **without** `Issr = ISO`, since the EPC
    /// reserves that marker for genuine RF references. Not check-digit
    /// validated: the scheme is national and its rules vary.
    Proprietary {
        /// The reference value, up to 35 characters.
        reference: String,
        /// The issuing scheme, placed in `Tp/Issr`.
        issuer: Option<String>,
    },
}

impl RemittanceInfo {
    /// Free-text remittance information.
    pub fn unstructured(text: impl Into<String>) -> Self {
        Self::Unstructured(text.into())
    }

    /// A structured ISO 11649 reference.
    #[must_use]
    pub fn structured(reference: RfReference) -> Self {
        Self::Structured(reference)
    }

    /// Validate against the EPC length and character-set rules.
    ///
    /// Free text is measured **after** the charset policy has been applied,
    /// because transliteration can lengthen it — 140 characters of German
    /// *Verwendungszweck* can cross the limit on its way to `Mueller`. Checking
    /// the input instead would leave `build()` with a value it can neither emit
    /// nor shorten without silently losing a reconciliation key.
    ///
    /// # Errors
    ///
    /// Returns [`ValidationError`] when the text is empty, too long, or — under
    /// [`CharsetPolicy::Strict`](crate::CharsetPolicy::Strict) — outside the
    /// SEPA character set.
    pub fn validate(
        &self,
        field: &'static str,
        charset: crate::validate::CharsetPolicy,
    ) -> Result<(), ValidationError> {
        match self {
            Self::Unstructured(text) => {
                return check_remittance(field, &charset.apply(field, text)?);
            }
            // An RfReference is at most 25 characters and SEPA-legal by
            // construction, so only the block length below can still fail.
            Self::Structured(_) => {}
            Self::Proprietary { reference, issuer } => {
                // `Ref` is a reference, so EPC230-15's slash rule applies.
                crate::validate::check_id("RmtInf/Strd/CdtrRefInf/Ref", reference)?;
                // `Issr` is a plain `Max35Text` scheme name, not a reference:
                // no slash rule, but it *is* text on the wire, so it has to
                // survive the charset policy and the length limit like every
                // other emitted string.
                if let Some(issuer) = issuer {
                    check_text(
                        "RmtInf/Strd/CdtrRefInf/Tp/Issr",
                        &charset.apply("RmtInf/Strd/CdtrRefInf/Tp/Issr", issuer)?,
                        MAX_ID_LEN,
                    )?;
                }
            }
        }

        // The EPC caps `Strd` at 140 characters *including the XML tags*, which
        // no XSD expresses and no per-field check catches. Measure what is
        // actually going to be written, by writing it — the same function the
        // writer uses, so the two cannot drift.
        let mut rendered = String::new();
        // Writing into a String is infallible.
        let _ = Self::write_structured(&mut rendered, self, charset);
        let actual = rendered.chars().count();
        if actual > MAX_STRUCTURED_REMITTANCE_LEN {
            return Err(ValidationError::TooLong {
                field: "RmtInf/Strd",
                max: MAX_STRUCTURED_REMITTANCE_LEN,
                actual,
            });
        }
        Ok(())
    }

    /// Render the `Strd` block, minified.
    ///
    /// Shared by [`validate`](Self::validate) and [`write_xml`](Self::write_xml)
    /// so the length that is checked is the length that is emitted. Writes
    /// nothing for the unstructured variant.
    fn write_structured<W: std::fmt::Write>(
        w: &mut W,
        remittance: &Self,
        charset: crate::validate::CharsetPolicy,
    ) -> std::fmt::Result {
        use crate::xml_util::write_escaped;

        match remittance {
            Self::Unstructured(_) => Ok(()),
            Self::Structured(rf) => {
                // `CdOrPrtry`, not `CdorPrtry` — the latter is schema-invalid and
                // is a mistake other implementations have shipped.
                w.write_str(
                    "<Strd><CdtrRefInf><Tp><CdOrPrtry><Cd>SCOR</Cd></CdOrPrtry>\
                     <Issr>ISO</Issr></Tp><Ref>",
                )?;
                w.write_str(rf.as_str())?;
                w.write_str("</Ref></CdtrRefInf></Strd>")
            }
            Self::Proprietary { reference, issuer } => {
                w.write_str("<Strd><CdtrRefInf><Tp><CdOrPrtry><Cd>SCOR</Cd></CdOrPrtry>")?;
                if let Some(issuer) = issuer {
                    w.write_str("<Issr>")?;
                    write_escaped(w, &charset.render(issuer))?;
                    w.write_str("</Issr>")?;
                }
                w.write_str("</Tp><Ref>")?;
                write_escaped(w, reference)?;
                w.write_str("</Ref></CdtrRefInf></Strd>")
            }
        }
    }

    /// Write this remittance information as `RmtInf` XML.
    pub(crate) fn write_xml<W: std::fmt::Write>(
        &self,
        w: &mut W,
        indent: &str,
        charset: crate::validate::CharsetPolicy,
    ) -> std::fmt::Result {
        use crate::xml_util::write_escaped;

        write!(w, "{indent}<RmtInf>")?;
        match self {
            Self::Unstructured(text) => {
                // `validate` has already bounded this at MAX_REMITTANCE_LEN
                // characters *after* transliteration, so there is nothing to
                // truncate. Silently cutting here instead would ship a payment
                // whose reference no longer matches the invoice.
                w.write_str("<Ustrd>")?;
                write_escaped(w, &charset.render(text))?;
                w.write_str("</Ustrd>")?;
            }
            // Minified, and rendered by the same function `validate` measured:
            // the EPC's 140-character cap on `Strd` counts the tags, so
            // pretty-printing alone would overrun it.
            structured => Self::write_structured(w, structured, charset)?,
        }
        w.write_str("</RmtInf>\n")
    }
}

impl From<&str> for RemittanceInfo {
    fn from(text: &str) -> Self {
        Self::Unstructured(text.to_owned())
    }
}

impl From<String> for RemittanceInfo {
    fn from(text: String) -> Self {
        Self::Unstructured(text)
    }
}

impl From<RfReference> for RemittanceInfo {
    fn from(rf: RfReference) -> Self {
        Self::Structured(rf)
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn a_proprietary_issuer_is_length_checked_and_transliterated() {
        // Regression: `Tp/Issr` was neither validated nor put through the
        // charset policy, so any text at all reached the wire — non-SEPA
        // characters included, and with no `Max35Text` bound.
        use crate::validate::CharsetPolicy;

        let long = RemittanceInfo::Proprietary {
            reference: "REF-1".to_owned(),
            issuer: Some("X".repeat(36)),
        };
        assert!(matches!(
            long.validate("RmtInf", CharsetPolicy::default()),
            Err(ValidationError::TooLong {
                field: "RmtInf/Strd/CdtrRefInf/Tp/Issr",
                max: 35,
                ..
            })
        ));

        let umlaut = RemittanceInfo::Proprietary {
            reference: "REF-1".to_owned(),
            issuer: Some("Bräuner".to_owned()),
        };
        assert!(umlaut.validate("RmtInf", CharsetPolicy::default()).is_ok());
        let mut out = String::new();
        umlaut
            .write_xml(&mut out, "", CharsetPolicy::default())
            .unwrap();
        assert!(out.contains("<Issr>Braeuner</Issr>"), "{out}");

        // Strict refuses rather than rewriting, here as everywhere else.
        assert!(matches!(
            umlaut.validate("RmtInf", CharsetPolicy::Strict),
            Err(ValidationError::InvalidCharacter { ch: 'ä', .. })
        ));
    }

    #[test]
    fn the_structured_block_is_capped_at_140_characters_including_tags() {
        // The EPC caps `Strd` at 140 characters *with* the markup, which no
        // per-field check can see: a 35-character `Ref` and a 35-character
        // `Issr` are both legal and together overrun the block.
        use crate::validate::CharsetPolicy;

        let big = RemittanceInfo::Proprietary {
            reference: "R".repeat(35),
            issuer: Some("I".repeat(35)),
        };
        let err = big
            .validate("RmtInf", CharsetPolicy::default())
            .unwrap_err();
        assert!(
            matches!(
                err,
                ValidationError::TooLong {
                    field: "RmtInf/Strd",
                    max: 140,
                    ..
                }
            ),
            "{err:?}"
        );

        // What is measured is what is written: an RF reference plus its
        // mandatory `Issr` of `ISO` is the longest shape that still fits.
        let rf = RemittanceInfo::Structured(RfReference::generate(&"9".repeat(21)).unwrap());
        assert!(rf.validate("RmtInf", CharsetPolicy::default()).is_ok());
        let mut out = String::new();
        rf.write_xml(&mut out, "", CharsetPolicy::default())
            .unwrap();
        let strd = out.split("<Strd>").nth(1).unwrap();
        let strd = format!("<Strd>{}", strd.split("</RmtInf>").next().unwrap());
        assert!(
            strd.chars().count() <= 140,
            "{} chars",
            strd.chars().count()
        );
    }

    #[test]
    fn iso_11649_annex_b_worked_example() {
        // ISO 11649 Annex B.1: 2348231 -> RF712348231
        let rf = RfReference::generate("2348231").unwrap();
        assert_eq!(rf.as_str(), "RF712348231");
        assert_eq!(rf.check_digits(), "71");
        assert_eq!(rf.reference(), "2348231");
    }

    #[test]
    fn printed_format_round_trips() {
        let rf: RfReference = "RF18539007547034".parse().unwrap();
        assert_eq!(rf.to_string(), "RF18 5390 0754 7034");
        assert_eq!("RF18 5390 0754 7034".parse::<RfReference>().unwrap(), rf);
    }

    #[test]
    fn the_iso_annex_a_string_is_not_a_valid_reference() {
        // ISO 11649 Annex A illustrates *print grouping* with "RF68539007547034".
        // Annex A is informative and that string's check digits are wrong
        // (mod 97 = 51, not 1) — yet it circulates widely as a test vector.
        // The correct reference for 539007547034 is RF18.
        assert!("RF68539007547034".parse::<RfReference>().is_err());
        assert_eq!(
            RfReference::generate("539007547034").unwrap().as_str(),
            "RF18539007547034"
        );
    }

    #[test]
    fn published_reference_vectors() {
        // Finance Finland and ISO 11649 published examples, each independently
        // verified to satisfy mod 97 == 1.
        for v in [
            "RF712348231",               // ISO 11649 Annex B
            "RF541234",                  // Finance Finland
            "RF98REF1234",               // Finance Finland
            "RF18539007547034",          // EPC069-12 QR example
            "RF040",                     // minimum length, leading-zero check digit
            "RF95ABCDEFGHIJKLMNOPQRSTU", // maximum length
        ] {
            assert!(v.parse::<RfReference>().is_ok(), "{v} must validate");
        }
        for v in [
            "RF712348232",  // check digit off by one
            "RF12",         // too short
            "RF7A2348231",  // non-numeric check digits
            "XY712348231",  // wrong prefix
            "RF7123-48231", // punctuation
        ] {
            assert!(v.parse::<RfReference>().is_err(), "{v} must be rejected");
        }
    }

    #[test]
    fn leading_zero_check_digits_are_padded() {
        // "0" needs check digits "04" — a bare `98 - n` would emit "4".
        let rf = RfReference::generate("0").unwrap();
        assert_eq!(rf.as_str(), "RF040");
        assert_eq!(rf.check_digits(), "04");
    }

    #[test]
    fn generated_references_always_validate() {
        for input in [
            "1",
            "2348231",
            "539007547034",
            "INV20260042",
            "ABCDEFGHIJKLMNOPQRSTU", // 21 chars, the maximum
            "0000000001",
            "Z",
        ] {
            let rf = RfReference::generate(input).unwrap();
            assert_eq!(
                rf.as_str().parse::<RfReference>().unwrap(),
                rf,
                "generated {} must re-validate",
                rf.as_str()
            );
            assert!(rf.as_str().len() <= MAX_RF_LEN);
        }
    }

    #[test]
    fn separators_are_stripped_before_computing_check_digits() {
        let a = RfReference::generate("inv-2026/0042").unwrap();
        let b = RfReference::generate("INV20260042").unwrap();
        assert_eq!(a, b);
        assert_eq!(a.reference(), "INV20260042");
    }

    #[test]
    fn check_digits_helper_matches_generation() {
        for input in ["2348231", "539007547034", "INV1"] {
            let rf = RfReference::generate(input).unwrap();
            assert_eq!(RfReference::check_digits_for(input), rf.check_digits());
        }
    }

    #[test]
    fn wrong_check_digits_are_rejected() {
        // RF71 is correct for 2348231, so RF72 must fail.
        let err = "RF722348231".parse::<RfReference>().unwrap_err();
        assert_eq!(
            err,
            RfReferenceError::InvalidChecksum {
                expected: "71".to_owned(),
                actual: "72".to_owned(),
            }
        );
    }

    #[test]
    fn malformed_input_is_rejected() {
        assert!(matches!(
            "XX712348231".parse::<RfReference>(),
            Err(RfReferenceError::MissingRfPrefix { .. })
        ));
        assert!(matches!(
            "RF71-2348".parse::<RfReference>(),
            Err(RfReferenceError::InvalidCharacter { ch: '-' })
        ));
        assert!(matches!(
            "".parse::<RfReference>(),
            Err(RfReferenceError::InvalidLength { .. })
        ));
        assert!(matches!(
            "RF18".parse::<RfReference>(),
            Err(RfReferenceError::InvalidLength { len: 4 })
        ));
        // 26 characters — one over the maximum.
        assert!(matches!(
            "RF181234567890123456789012".parse::<RfReference>(),
            Err(RfReferenceError::InvalidLength { len: 26 })
        ));
    }

    #[test]
    fn over_long_reference_is_rejected_at_generation() {
        // 22 characters of payload exceeds the 21-character limit.
        assert!(matches!(
            RfReference::generate(&"A".repeat(22)),
            Err(RfReferenceError::InvalidLength { .. })
        ));
        assert!(RfReference::generate(&"A".repeat(21)).is_ok());
        assert!(matches!(
            RfReference::generate("---"),
            Err(RfReferenceError::InvalidLength { .. })
        ));
    }

    #[test]
    fn lowercase_input_is_accepted_on_parse() {
        // ISO 11649 §6.2.3 permits lower case when validating.
        let rf: RfReference = "rf18539007547034".parse().unwrap();
        assert_eq!(rf.as_str(), "RF18539007547034");
    }

    #[test]
    fn structured_remittance_xml_uses_the_correct_element_names() {
        let rf = RfReference::generate("539007547034").unwrap();
        let mut out = String::new();
        RemittanceInfo::Structured(rf)
            .write_xml(&mut out, "  ", crate::validate::CharsetPolicy::default())
            .unwrap();

        assert!(
            out.contains("<CdOrPrtry>"),
            "must be CdOrPrtry, not CdorPrtry"
        );
        assert!(out.contains("<Cd>SCOR</Cd>"));
        assert!(out.contains("<Issr>ISO</Issr>"));
        assert!(out.contains("<Ref>RF18539007547034</Ref>"));
        assert!(!out.contains("<Ustrd>"), "structured excludes unstructured");
    }

    #[test]
    fn unstructured_remittance_xml_is_escaped_and_transliterated() {
        let mut out = String::new();
        RemittanceInfo::unstructured("Zahlung für Müller & Co")
            .write_xml(&mut out, "  ", crate::validate::CharsetPolicy::default())
            .unwrap();
        assert!(out.contains("<Ustrd>Zahlung fuer Mueller + Co</Ustrd>"));
        assert!(!out.contains("<Strd>"));
    }

    #[test]
    fn proprietary_reference_omits_the_iso_issuer_marker() {
        let mut out = String::new();
        RemittanceInfo::Proprietary {
            reference: "+++090/9337/55493+++".replace(['+', '/'], ""),
            issuer: Some("BE".to_owned()),
        }
        .write_xml(&mut out, "  ", crate::validate::CharsetPolicy::default())
        .unwrap();
        assert!(out.contains("<Cd>SCOR</Cd>"));
        assert!(out.contains("<Issr>BE</Issr>"));
        assert!(
            !out.contains("<Issr>ISO</Issr>"),
            "ISO marks a genuine ISO 11649 reference only"
        );
    }

    #[test]
    fn remittance_validation_enforces_epc_limits() {
        let policy = crate::validate::CharsetPolicy::default();
        assert!(
            RemittanceInfo::unstructured("A".repeat(140))
                .validate("RmtInf/Ustrd", policy)
                .is_ok()
        );
        assert!(matches!(
            RemittanceInfo::unstructured("A".repeat(141)).validate("RmtInf/Ustrd", policy),
            Err(ValidationError::TooLong { .. })
        ));
        assert!(matches!(
            RemittanceInfo::unstructured("").validate("RmtInf/Ustrd", policy),
            Err(ValidationError::Empty { .. })
        ));
    }

    #[test]
    fn the_limit_binds_on_the_transliterated_text_not_the_input() {
        // Regression: 140 characters of German went in, `Mueller`-style
        // expansion pushed it past 140, and the writer silently cut the tail —
        // which is where an invoice number tends to sit.
        let policy = crate::validate::CharsetPolicy::default();
        let input = format!("{}ü", "A".repeat(139)); // 140 chars in, 141 out
        assert_eq!(input.chars().count(), 140);
        assert!(matches!(
            RemittanceInfo::unstructured(&input).validate("RmtInf/Ustrd", policy),
            Err(ValidationError::TooLong {
                max: 140,
                actual: 141,
                ..
            })
        ));
        // The strict policy neither rewrites nor truncates — it names the char.
        assert!(matches!(
            RemittanceInfo::unstructured("Zahlung für Müller")
                .validate("RmtInf/Ustrd", crate::validate::CharsetPolicy::Strict),
            Err(ValidationError::InvalidCharacter { ch: 'ü', .. })
        ));
    }

    #[test]
    fn accepted_remittance_text_is_written_whole() {
        let mut out = String::new();
        let text = "Ü".repeat(70); // 70 chars in, 140 out — exactly the limit
        RemittanceInfo::unstructured(&text)
            .write_xml(&mut out, "", crate::validate::CharsetPolicy::default())
            .unwrap();
        assert!(out.contains(&format!("<Ustrd>{}</Ustrd>", "Ue".repeat(70))));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip_validates() {
        let rf = RfReference::generate("2348231").unwrap();
        let json = serde_json::to_string(&rf).unwrap();
        assert_eq!(json, r#""RF712348231""#);
        assert_eq!(serde_json::from_str::<RfReference>(&json).unwrap(), rf);
        // A bad checksum must not deserialise.
        assert!(serde_json::from_str::<RfReference>(r#""RF722348231""#).is_err());
    }
}