sepa 0.8.0

SEPA payment utilities for all five EPC payment schemes: SCT, SCT Inst, SDD Core, SDD B2B and One-Leg Out Instant (OCT Inst). Builds pain.001, pain.008, pain.007 and camt.055; parses pain.002 (incl. Verification of Payee), camt.029 and camt.052/053/054. IBAN, BIC, Creditor Identifier and ISO 11649 RF reference validation, structured addresses, EPC field rules and charset transliteration. Output is XSD-validated in CI against the ISO schemas and the German GBIC 5 subsets. No I/O, no async, no f64 in 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
//! ISO 20022 camt.053 — Bank-to-Customer Statement parser.
//!
//! Parses end-of-day electronic bank statements (the SEPA equivalent of MT940).
//!
//! ## The camt.05x family
//!
//! | Message | Content | Module |
//! |---|---|---|
//! | camt.052 | Intraday account report, provisional | [`camt052`](crate::camt052) |
//! | camt.053 | End-of-day statement, booked and final | this module |
//! | camt.054 | Debit/credit notification of specific events | [`camt054`](crate::camt054) |
//!
//! All three share the entry model in [`crate::camt`], so reconciliation code
//! can treat them uniformly. Every ISO version from `.001.02` to `.001.13` is
//! accepted, including the `.001.07` reshaping of `Ntry/Sts` and of the party
//! elements.
//!
//! ## Example
//!
//! ```rust
//! use sepa::camt053::parse_camt053;
//!
//! let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
//! <Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
//!   <BkToCstmrStmt>
//!     <GrpHdr><MsgId>STMT-001</MsgId><CreDtTm>2026-07-14T23:59:00</CreDtTm></GrpHdr>
//!     <Stmt>
//!       <Id>2026-07-14</Id>
//!       <Acct><Id><IBAN>DE89370400440532013000</IBAN></Id></Acct>
//!       <Bal>
//!         <Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp>
//!         <Amt Ccy="EUR">1155.42</Amt>
//!         <CdtDbtInd>CRDT</CdtDbtInd>
//!         <Dt><Dt>2026-07-14</Dt></Dt>
//!       </Bal>
//!     </Stmt>
//!   </BkToCstmrStmt>
//! </Document>"#;
//!
//! let doc = parse_camt053(xml)?;
//! let stmt = &doc.statements[0];
//! assert_eq!(stmt.account.iban.as_deref(), Some("DE89370400440532013000"));
//! assert_eq!(stmt.closing_balance().unwrap().amount.ct, Some(115_542));
//! # Ok::<(), sepa::Camt053ParseError>(())
//! ```

use crate::camt::{self, AccountRef, BalanceType, CashEntry, StatementBalance};
use crate::xml::{Document, Node, XmlError};

// ── known namespaces ──────────────────────────────────────────────────────────

/// Known camt.053 XML namespace URIs.
pub mod ns {
    /// Deutsche Kreditwirtschaft V2.
    pub const CAMT053_001_02: &str = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02";
    /// Deutsche Kreditwirtschaft V6 — most common in Germany (current).
    pub const CAMT053_001_06: &str = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.06";
    /// Newer ISO 20022 version.
    pub const CAMT053_001_08: &str = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.08";
}

// ── Camt053Statement ──────────────────────────────────────────────────────────

/// A single account statement within a camt.053 document.
///
/// Typically one statement per account per day.
#[derive(Debug, Clone)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Camt053Statement {
    /// Statement ID (`Id`).
    pub stmt_id: String,
    /// Electronic sequence number.
    pub sequence_number: Option<u64>,
    /// The account this covers — IBAN or proprietary identifier, currency and
    /// servicing institution. See [`AccountRef`].
    pub account: AccountRef,
    /// Statement period start, ISO 8601.
    pub from_date_raw: Option<String>,
    /// Statement period end, ISO 8601.
    pub to_date_raw: Option<String>,
    /// All balances in this statement.
    pub balances: Vec<StatementBalance>,
    /// All entries (booked and pending transactions).
    pub entries: Vec<CashEntry>,
}

impl Camt053Statement {
    /// The period start, typed.
    ///
    /// `FrToDt` is a date/time choice, so it arrives as `"2026-07-14"` from one
    /// bank and `"2026-07-14T00:00:00"` from the next. The text that arrived is
    /// kept in [`from_date_raw`](Self::from_date_raw) either way — the same
    /// verbatim-and-typed rule [`CashEntry::booking_date`] follows, applied
    /// here so the whole read path answers dates the same way.
    ///
    /// [`CashEntry::booking_date`]: crate::CashEntry::booking_date
    #[must_use]
    pub fn from_date(&self) -> Option<crate::IsoDate> {
        crate::IsoDate::parse_date_part(self.from_date_raw.as_deref()?).ok()
    }

    /// The period end, typed. See [`from_date`](Self::from_date).
    #[must_use]
    pub fn to_date(&self) -> Option<crate::IsoDate> {
        crate::IsoDate::parse_date_part(self.to_date_raw.as_deref()?).ok()
    }

    /// Opening booked balance (`OPBD`), if present.
    #[must_use]
    pub fn opening_balance(&self) -> Option<&StatementBalance> {
        self.balances
            .iter()
            .find(|b| b.balance_type == BalanceType::OpeningBooked)
    }

    /// Closing booked balance (`CLBD`), if present.
    #[must_use]
    pub fn closing_balance(&self) -> Option<&StatementBalance> {
        self.balances
            .iter()
            .find(|b| b.balance_type == BalanceType::ClosingBooked)
    }

    /// Net movement in **ct** for this statement — the sum of the signed entry
    /// amounts — or `None` when any entry's amount or direction is unreadable.
    ///
    /// All-or-nothing on purpose. Skipping the entries that cannot be resolved
    /// produces a total that looks right and is not, which is the failure mode
    /// a net movement exists to rule out; `None` says "ask about this file"
    /// where a partial sum says nothing at all. Overflow saturates rather than
    /// panicking, because the input is a third party's file.
    #[must_use]
    pub fn net_movement_ct(&self) -> Option<i64> {
        self.entries
            .iter()
            .try_fold(0i64, |acc, e| Some(acc.saturating_add(e.signed_ct()?)))
    }
}

// ── Camt053Document ───────────────────────────────────────────────────────────

/// A parsed camt.053 Bank-to-Customer Statement document.
///
/// Produced by [`parse_camt053`].
#[derive(Debug, Clone)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Camt053Document {
    /// Document message ID.
    pub msg_id: String,
    /// Document creation timestamp.
    pub created_at_raw: String,
    /// Detected XML namespace URI.
    pub namespace: Option<String>,
    /// One or more statements (one per account, typically one per document).
    pub statements: Vec<Camt053Statement>,
}

impl Camt053Document {
    /// When the bank generated this document, typed.
    ///
    /// `None` when it reported none, or one this crate cannot read;
    /// [`created_at_raw`](Self::created_at_raw) still holds whatever arrived.
    #[must_use]
    pub fn created_at(&self) -> Option<crate::IsoDateTime> {
        crate::IsoDateTime::parse(&self.created_at_raw).ok()
    }
}

// ── Error ─────────────────────────────────────────────────────────────────────

/// Error returned when camt.053 XML cannot be parsed.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Camt053ParseError {
    /// The input is not well-formed XML.
    #[error(transparent)]
    Xml(#[from] XmlError),

    /// Root element `BkToCstmrStmt` not found — not a camt.053 document.
    ///
    /// Everything below the root is optional to this parser: a statement with
    /// no entries, no balances or no account identifier is unusual but not
    /// malformed, and refusing to read the rest of a real bank file over it
    /// would help nobody.
    #[error("not a camt.053 document: root element <BkToCstmrStmt> not found")]
    NotCamt053,
}

// ── Parser ────────────────────────────────────────────────────────────────────

/// Parse a camt.053 Bank-to-Customer Statement XML string.
///
/// Accepts every ISO version and both the default-namespace and prefixed
/// document shapes.
///
/// # Errors
///
/// Returns [`Camt053ParseError::NotCamt053`] when the root element is missing,
/// or [`Camt053ParseError::Xml`] when the input is not well-formed.
pub fn parse_camt053(xml: &str) -> Result<Camt053Document, Camt053ParseError> {
    let doc = Document::parse(xml)?;
    let root = doc
        .root
        .child("BkToCstmrStmt")
        .ok_or(Camt053ParseError::NotCamt053)?;

    let grp_hdr = root.child("GrpHdr");
    let text = |tag: &str| {
        grp_hdr
            .and_then(|h| h.text_of(tag))
            .unwrap_or_default()
            .to_owned()
    };

    Ok(Camt053Document {
        msg_id: text("MsgId"),
        created_at_raw: text("CreDtTm"),
        namespace: doc.namespace,
        statements: root.children_named("Stmt").map(parse_statement).collect(),
    })
}

fn parse_statement(s: &Node) -> Camt053Statement {
    // `Id` must be a direct child: `Stmt/Acct/Id` is a different element, and a
    // descendant search would pick it up whenever the statement carries no `Id`.
    let (from_date, to_date) = camt::period(s);
    Camt053Statement {
        stmt_id: s.text_of("Id").unwrap_or_default().to_owned(),
        sequence_number: s.text_of("ElctrncSeqNb").and_then(|v| v.parse().ok()),
        account: camt::account_of(s),
        from_date_raw: from_date,
        to_date_raw: to_date,
        balances: camt::balances_of(s),
        entries: camt::entries_of(s),
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::IsoDate;
    use crate::camt054::CreditDebitIndicator;
    use crate::{BalanceType, EntryStatus};

    const CAMT053_EXAMPLE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.06">
  <BkToCstmrStmt>
    <GrpHdr>
      <MsgId>STMT-2026-07-14-001</MsgId>
      <CreDtTm>2026-07-14T23:59:00</CreDtTm>
    </GrpHdr>
    <Stmt>
      <Id>2026-07-14</Id>
      <ElctrncSeqNb>42</ElctrncSeqNb>
      <CreDtTm>2026-07-14T23:59:00</CreDtTm>
      <Acct><Id><IBAN>DE89370400440532013000</IBAN></Id></Acct>
      <Bal>
        <Tp><CdOrPrtry><Cd>OPBD</Cd></CdOrPrtry></Tp>
        <Amt Ccy="EUR">1000.00</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
        <Dt><Dt>2026-07-13</Dt></Dt>
      </Bal>
      <Bal>
        <Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp>
        <Amt Ccy="EUR">1155.42</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
        <Dt><Dt>2026-07-14</Dt></Dt>
      </Bal>
      <Ntry>
        <Amt Ccy="EUR">155.42</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
        <Sts>BOOK</Sts>
        <BookgDt><Dt>2026-07-14</Dt></BookgDt>
        <ValDt><Dt>2026-07-14</Dt></ValDt>
        <AcctSvcrRef>SVCRREF-001</AcctSvcrRef>
        
        <BkTxCd><Domn><Cd>PMNT</Cd><Fmly><Cd>RDDT</Cd><SubFmlyCd>PMDD</SubFmlyCd></Fmly></Domn></BkTxCd>
        <NtryDtls>
          <TxDtls>
            <Refs>
              <EndToEndId>E2E-INV-2026</EndToEndId>
            </Refs>
            <Amt Ccy="EUR">155.42</Amt>
            <CdtDbtInd>CRDT</CdtDbtInd>
            <RltdPties>
              <Dbtr><Nm>Max Mustermann GmbH</Nm></Dbtr>
              <DbtrAcct><Id><IBAN>NL91ABNA0417164300</IBAN></Id></DbtrAcct>
            </RltdPties>
            <RmtInf><Ustrd>Invoice 2026-07-001</Ustrd></RmtInf>
          </TxDtls>
        </NtryDtls>
      </Ntry>
    </Stmt>
  </BkToCstmrStmt>
</Document>"#;

    #[test]
    fn parse_basic_statement() {
        let doc = parse_camt053(CAMT053_EXAMPLE).unwrap();
        assert_eq!(doc.msg_id, "STMT-2026-07-14-001");
        assert_eq!(
            doc.namespace.as_deref(),
            Some("urn:iso:std:iso:20022:tech:xsd:camt.053.001.06")
        );

        assert_eq!(doc.statements.len(), 1);
        let stmt = &doc.statements[0];
        assert_eq!(stmt.stmt_id, "2026-07-14");
        assert_eq!(stmt.sequence_number, Some(42));
        assert_eq!(stmt.account.iban.as_deref(), Some("DE89370400440532013000"));
    }

    #[test]
    fn balances_parsed() {
        let doc = parse_camt053(CAMT053_EXAMPLE).unwrap();
        let stmt = &doc.statements[0];

        let opening = stmt.opening_balance().unwrap();
        assert_eq!(opening.amount.ct, Some(100_000));
        assert_eq!(opening.date_raw, "2026-07-13");
        assert_eq!(opening.date(), Some(IsoDate::new(2026, 7, 13).unwrap()));

        let closing = stmt.closing_balance().unwrap();
        assert_eq!(closing.amount.ct, Some(115_542));
        assert_eq!(closing.date(), Some(IsoDate::new(2026, 7, 14).unwrap()));
    }

    #[test]
    fn entry_parsed() {
        let doc = parse_camt053(CAMT053_EXAMPLE).unwrap();
        let stmt = &doc.statements[0];
        assert_eq!(stmt.entries.len(), 1);

        let e = &stmt.entries[0];
        assert_eq!(e.amount.ct, Some(15_542));
        assert_eq!(e.amount.direction, Some(CreditDebitIndicator::Credit));
        assert_eq!(e.status, EntryStatus::Booked);
        assert_eq!(e.booking_date(), Some(IsoDate::new(2026, 7, 14).unwrap()));
        assert_eq!(e.account_servicer_ref.as_deref(), Some("SVCRREF-001"));
        assert_eq!(e.end_to_end_id(), Some("E2E-INV-2026"));
        assert_eq!(e.reference(), Some("Invoice 2026-07-001"));
        assert_eq!(e.counterparty_name(), Some("Max Mustermann GmbH"));
        assert_eq!(e.counterparty_iban(), Some("NL91ABNA0417164300"));
        assert!(!e.is_return());
        assert_eq!(e.signed_ct(), Some(15_542)); // credit = positive
    }

    #[test]
    fn net_movement() {
        let doc = parse_camt053(CAMT053_EXAMPLE).unwrap();
        assert_eq!(doc.statements[0].net_movement_ct(), Some(15_542));
    }

    #[test]
    fn a_non_iban_account_is_reported_rather_than_lost() {
        // `Acct/Id` is a choice: IBAN *or* a proprietary identifier. Collapsing
        // it to one string made a non-IBAN account read as "" — indistinguishable
        // from an account with no identifier at all.
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
  <BkToCstmrStmt>
    <GrpHdr><MsgId>M</MsgId><CreDtTm>2026-07-21T23:59:00</CreDtTm></GrpHdr>
    <Stmt>
      <Id>S1</Id>
      <Acct>
        <Id><Othr><Id>1234567890</Id></Othr></Id>
        <Ccy>CHF</Ccy>
        <Svcr><FinInstnId><BICFI>POFICHBEXXX</BICFI></FinInstnId></Svcr>
      </Acct>
      <Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">0.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-07-21</Dt></Dt></Bal>
    </Stmt>
  </BkToCstmrStmt>
</Document>"#;
        let acct = &parse_camt053(xml).unwrap().statements[0].account;
        assert_eq!(acct.iban, None);
        assert_eq!(acct.other_id.as_deref(), Some("1234567890"));
        assert_eq!(acct.currency.as_deref(), Some("CHF"));
        assert_eq!(acct.servicer_bic.as_deref(), Some("POFICHBEXXX"));
        assert_eq!(acct.any_id(), Some("1234567890"));

        // An IBAN account still reports the IBAN, and `any_id` prefers it.
        let acct = &parse_camt053(CAMT053_EXAMPLE).unwrap().statements[0].account;
        assert_eq!(acct.any_id(), Some("DE89370400440532013000"));

        // No Acct block at all is empty, not a panic or an invented value.
        let bare = "<Document><BkToCstmrStmt><Stmt><Id>S</Id></Stmt></BkToCstmrStmt></Document>";
        let acct = &parse_camt053(bare).unwrap().statements[0].account;
        assert_eq!(acct.any_id(), None);
    }

    #[test]
    fn not_camt053() {
        let err = parse_camt053("<Document><Other/></Document>").unwrap_err();
        assert_eq!(err, Camt053ParseError::NotCamt053);
    }

    #[test]
    fn balance_type_codes() {
        assert_eq!(BalanceType::OpeningBooked.as_code(), "OPBD");
        assert_eq!(BalanceType::ClosingBooked.as_code(), "CLBD");
        assert_eq!(BalanceType::from_code("CLBD"), BalanceType::ClosingBooked);
    }

    #[test]
    fn debit_entry_counterparty_is_creditor() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.06">
  <BkToCstmrStmt>
    <GrpHdr><MsgId>STMT-DEBIT</MsgId><CreDtTm>2026-07-14T23:59:00</CreDtTm></GrpHdr>
    <Stmt>
      <Id>2026-07-14-D</Id>
      <CreDtTm>2026-07-14T23:59:00</CreDtTm>
      <Acct><Id><IBAN>DE89370400440532013000</IBAN></Id></Acct>
      <Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">0.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-07-14</Dt></Dt></Bal>
      <Ntry>
        <Amt Ccy="EUR">500.00</Amt>
        <CdtDbtInd>DBIT</CdtDbtInd>
        <Sts>BOOK</Sts>
        <BookgDt><Dt>2026-07-14</Dt></BookgDt>
        
        <BkTxCd><Domn><Cd>PMNT</Cd><Fmly><Cd>RDDT</Cd><SubFmlyCd>PMDD</SubFmlyCd></Fmly></Domn></BkTxCd>
        <NtryDtls>
          <TxDtls>
            <Refs><EndToEndId>PAY-OUT-001</EndToEndId></Refs>
            <Amt Ccy="EUR">500.00</Amt>
            <CdtDbtInd>DBIT</CdtDbtInd>
            <RltdPties>
              <Cdtr><Nm>Supplier AG</Nm></Cdtr>
              <CdtrAcct><Id><IBAN>NL91ABNA0417164300</IBAN></Id></CdtrAcct>
            </RltdPties>
            <RmtInf><Ustrd>Supplier invoice July</Ustrd></RmtInf>
          </TxDtls>
        </NtryDtls>
      </Ntry>
    </Stmt>
  </BkToCstmrStmt>
</Document>"#;
        let doc = parse_camt053(xml).unwrap();
        let e = &doc.statements[0].entries[0];
        assert_eq!(e.amount.ct, Some(50_000));
        assert_eq!(e.amount.direction, Some(CreditDebitIndicator::Debit));
        assert_eq!(e.signed_ct(), Some(-50_000)); // debit = negative
        assert_eq!(e.counterparty_name(), Some("Supplier AG"));
        assert_eq!(e.counterparty_iban(), Some("NL91ABNA0417164300"));
        assert_eq!(e.reference(), Some("Supplier invoice July"));
    }

    #[test]
    fn return_entry_detected() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.06">
  <BkToCstmrStmt>
    <GrpHdr><MsgId>STMT-RTN</MsgId><CreDtTm>2026-07-14T23:59:00</CreDtTm></GrpHdr>
    <Stmt>
      <Id>2026-07-14-R</Id>
      <CreDtTm>2026-07-14T23:59:00</CreDtTm>
      <Acct><Id><IBAN>DE89370400440532013000</IBAN></Id></Acct>
      <Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">0.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-07-14</Dt></Dt></Bal>
      <Ntry>
        <Amt Ccy="EUR">75.00</Amt>
        <CdtDbtInd>DBIT</CdtDbtInd>
        <Sts>BOOK</Sts>
        
        <BkTxCd><Domn><Cd>PMNT</Cd><Fmly><Cd>RDDT</Cd><SubFmlyCd>PMDD</SubFmlyCd></Fmly></Domn></BkTxCd>
        <NtryDtls>
          <TxDtls>
            <Refs><EndToEndId>MND-001</EndToEndId></Refs>
            <Amt Ccy="EUR">75.00</Amt>
            <CdtDbtInd>DBIT</CdtDbtInd>
            <RtrInf>
              <Rsn><Cd>MD01</Cd></Rsn>
              <AddtlInf>No mandate found</AddtlInf>
            </RtrInf>
          </TxDtls>
        </NtryDtls>
      </Ntry>
    </Stmt>
  </BkToCstmrStmt>
</Document>"#;
        let doc = parse_camt053(xml).unwrap();
        let e = &doc.statements[0].entries[0];
        assert!(e.is_return());
        assert_eq!(e.return_reason_code(), Some("MD01"));
    }

    #[test]
    fn no_from_date_fallback_to_creation_time() {
        // FrToDt absent → from_date must be None, NOT the document CreDtTm
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.06">
  <BkToCstmrStmt>
    <GrpHdr><MsgId>STMT-NO-PERIOD</MsgId><CreDtTm>2026-07-14T23:59:00</CreDtTm></GrpHdr>
    <Stmt>
      <Id>2026-07-14</Id>
      <CreDtTm>2026-07-14T23:59:00</CreDtTm>
      <Acct><Id><IBAN>DE89370400440532013000</IBAN></Id></Acct>
      <Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">0.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-07-14</Dt></Dt></Bal>
    </Stmt>
  </BkToCstmrStmt>
</Document>"#;
        let doc = parse_camt053(xml).unwrap();
        assert_eq!(
            doc.statements[0].from_date_raw, None,
            "from_date_raw must be None when FrToDt is absent"
        );
        assert_eq!(doc.statements[0].to_date_raw, None);
        assert_eq!(doc.statements[0].from_date(), None);
    }
}