Skip to main content

fints_client/
camt.rs

1//! CAMT.052 (ISO 20022 "Bank to Customer Account Report") parser.
2//!
3//! HICAZ answers HKCAZ with one or more complete camt.052 XML documents.
4//! Each `<Ntry>` (entry) of a `<Rpt>` (report) becomes one [`Transaction`]:
5//!
6//! ```text
7//! Document/BkToCstmrAcctRpt/Rpt
8//!   Acct/Ccy                               account currency (fallback for Amt)
9//!   Ntry
10//!     Amt @Ccy, CdtDbtInd (CRDT|DBIT)      amount and sign
11//!     RvslInd                              reversal (Storno)
12//!     Sts (or Sts/Cd)                      BOOK | PDNG | INFO
13//!     BookgDt/Dt (or DtTm)                 booking date  -> Transaction::date
14//!     ValDt/Dt   (or DtTm)                 value date    -> Transaction::valuta_date
15//!     AcctSvcrRef                          bank reference
16//!     BkTxCd/Prtry/Cd                      DK code "SWIFT+GVC+primanota[+ext]"
17//!     AddtlNtryInf                         booking text  -> posting_text
18//!     NtryDtls/TxDtls                      first TxDtls only:
19//!       Refs/EndToEndId, Refs/MndtId, Refs/AcctSvcrRef
20//!       RltdPties/{Dbtr,Cdtr,UltmtDbtr,UltmtCdtr}[/Pty]/Nm
21//!       RltdPties/{DbtrAcct,CdtrAcct}/Id/IBAN
22//!       RltdAgts/{DbtrAgt,CdtrAgt}/FinInstnId/{BIC,BICFI}
23//!       Purp/Cd                            ISO 20022 purpose code
24//!       RmtInf/Ustrd                       remittance text, parts joined with a line break
25//!       RltdPties/Cdtr[/Pty]/Id/PrvtId/Othr/Id          -> creditor_id (SEPA creditor ID)
26//!       RltdPties/Dbtr[/Pty]/Id/{PrvtId,OrgId}/Othr/Id  -> debtor_id
27//! ```
28//!
29//! Dates follow the same rule as MT940 (`crate::formats::mt940`): `date` is the
30//! booking date and `valuta_date` the value date; an entry without a booking
31//! date (typically a pending one) falls back to its value date.
32//!
33//! Element names are matched without namespace prefix, so camt.052.001.02
34//! and the later versions (001.08, …) parse with the same code. Written from
35//! the ISO 20022 message definition and the German banking industry's (DK)
36//! camt usage notes as seen in bank responses; unknown elements are ignored.
37
38use std::str::FromStr;
39
40use jiff::civil::Date;
41use quick_xml::Reader;
42use quick_xml::events::{BytesStart, Event};
43use rust_decimal::Decimal;
44
45use crate::banks::BookingIdSource;
46use crate::error::{FinTSError, Result};
47use crate::types::{Bic, Currency, Iban, Transaction, TransactionStatus};
48
49/// Parse one camt.052 XML document into transactions, in document order.
50///
51/// Malformed XML, or an entry whose amount or dates cannot be read, is an
52/// error ([`FinTSError::Camt`]); the document is not partially returned.
53/// The status comes from each entry's `<Sts>` (`PDNG` = pending); callers
54/// that know a document holds pending entries (HICAZ's second data element)
55/// may override it.
56///
57/// `booking_id` is the bank profile's rule for
58/// [`Transaction::booking_id`]: with
59/// [`BookingIdSource::CamtEntryAcctSvcrRef`] an entry with `<Sts>BOOK` gets
60/// its entry-level `AcctSvcrRef` (never the one of a `TxDtls`: an entry is
61/// one transaction, and its first `TxDtls` describes only part of a batch).
62/// A reference that occurs on more than one entry of the document is
63/// dropped from all of them.
64pub fn parse_camt052(xml: &[u8], booking_id: BookingIdSource) -> Result<Vec<Transaction>> {
65    let mut reader = Reader::from_reader(xml);
66
67    let mut buf = Vec::new();
68    let mut path: Vec<String> = Vec::new();
69    // Text of the current element: text, CDATA and entity references arrive
70    // as separate events and are joined here until the next tag.
71    let mut text = String::new();
72    let mut report_currency: Option<String> = None;
73    // When the bank made the report (`CreDtTm` of the report, else of the
74    // message): the date of a pending entry that carries none.
75    let mut report_created: Option<String> = None;
76    let mut entry: Option<Entry> = None;
77    let mut out = Vec::new();
78
79    loop {
80        let event = reader.read_event_into(&mut buf).map_err(|e| {
81            camt_err(format!(
82                "XML error at byte {}: {e}",
83                reader.error_position()
84            ))
85        })?;
86        if matches!(
87            event,
88            Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof
89        ) {
90            let t = text.trim();
91            if !t.is_empty() {
92                if entry.is_none() && ends_with(&path, &["Rpt", "Acct", "Ccy"]) {
93                    report_currency = Some(t.to_string());
94                }
95                if entry.is_none()
96                    && (ends_with(&path, &["Rpt", "CreDtTm"])
97                        || (report_created.is_none() && ends_with(&path, &["GrpHdr", "CreDtTm"])))
98                {
99                    report_created = Some(t.to_string());
100                }
101                if let Some(e) = entry.as_mut() {
102                    e.on_text(&path, t);
103                }
104            }
105            text.clear();
106        }
107        match event {
108            Event::Start(ref e) => {
109                path.push(local_name(e.name().as_ref()));
110                check_root(&path)?;
111                on_start(&path, e, &mut entry);
112            }
113            Event::Empty(ref e) => {
114                // <Amt Ccy="EUR"/> etc. carry no text; only attributes matter.
115                path.push(local_name(e.name().as_ref()));
116                check_root(&path)?;
117                on_start(&path, e, &mut entry);
118                path.pop();
119            }
120            Event::End(_) => {
121                let closed = path.pop();
122                if closed.as_deref() == Some("Ntry")
123                    && let Some(e) = entry.take()
124                {
125                    let n = out.len() + 1;
126                    let fallback = report_currency.as_deref();
127                    out.push(
128                        e.build(fallback, report_created.as_deref(), booking_id)
129                            .map_err(|why| camt_err(format!("entry {n}: {why}")))?,
130                    );
131                }
132            }
133            Event::Text(ref t) => {
134                let decoded = t.decode().map_err(|e| camt_err(format!("bad text: {e}")))?;
135                text.push_str(&decoded);
136            }
137            Event::CData(ref t) => text.push_str(&String::from_utf8_lossy(&t[..])),
138            Event::GeneralRef(ref r) => {
139                let name = r
140                    .decode()
141                    .map_err(|e| camt_err(format!("bad reference: {e}")))?;
142                if let Some(c) = r
143                    .resolve_char_ref()
144                    .map_err(|e| camt_err(format!("bad reference &{name};: {e}")))?
145                {
146                    text.push(c);
147                } else if let Some(s) = quick_xml::escape::resolve_predefined_entity(&name) {
148                    text.push_str(s);
149                } else {
150                    return Err(camt_err(format!("unknown entity &{name};")));
151                }
152            }
153            Event::Eof => break,
154            _ => {}
155        }
156        buf.clear();
157    }
158    if !path.is_empty() {
159        return Err(camt_err(format!(
160            "document ends inside <{}>",
161            path.join("/")
162        )));
163    }
164    drop_shared_booking_ids(&mut out);
165    Ok(out)
166}
167
168/// Clear the `booking_id` of every transaction whose ID another one in
169/// `txs` carries too: an ID that is not unique is no ID.
170pub(crate) fn drop_shared_booking_ids(txs: &mut [Transaction]) {
171    let mut count = std::collections::HashMap::<String, u32>::new();
172    for id in txs.iter().filter_map(|t| t.booking_id.as_ref()) {
173        *count.entry(id.clone()).or_default() += 1;
174    }
175    let shared = count.values().filter(|n| **n > 1).count();
176    if shared == 0 {
177        return;
178    }
179    tracing::warn!(
180        "[FinTS] {shared} booking reference(s) occur on more than one entry; \
181         those entries get no booking ID"
182    );
183    for t in txs {
184        if t.booking_id.as_ref().is_some_and(|id| count[id] > 1) {
185            t.booking_id = None;
186        }
187    }
188}
189
190/// The document must be a camt.052 account report: `Document` with
191/// `BkToCstmrAcctRpt` below it. Anything else (camt.053, an error
192/// document) is not a statement and must not be read as an empty one.
193fn check_root(path: &[String]) -> Result<()> {
194    match path {
195        [root] if root != "Document" => Err(camt_err(format!(
196            "root element is <{root}>, expected <Document> (camt.052)"
197        ))),
198        [_, message] if message != "BkToCstmrAcctRpt" => Err(camt_err(format!(
199            "document holds <{message}>, expected <BkToCstmrAcctRpt> (camt.052)"
200        ))),
201        _ => Ok(()),
202    }
203}
204
205/// The `NN` of the first `camt.052.001.NN` in `text`: a descriptor, or the
206/// namespace at the head of a document.
207pub(crate) fn camt052_version(text: &[u8]) -> Option<u32> {
208    const MARK: &[u8] = b"camt.052.001.";
209    let at = text.windows(MARK.len()).position(|w| w == MARK)? + MARK.len();
210    let digits: Vec<u8> = text[at..]
211        .iter()
212        .copied()
213        .take_while(u8::is_ascii_digit)
214        .collect();
215    std::str::from_utf8(&digits).ok()?.parse().ok()
216}
217
218/// Log when the descriptor of an answer or the namespace of its document
219/// names another camt.052 version than the one requested. The document is
220/// parsed by element name either way.
221pub(crate) fn note_version_mismatch(requested: &str, descriptor: &str, document: &[u8]) {
222    let head = &document[..document.len().min(1024)];
223    let requested = camt052_version(requested.as_bytes());
224    let descriptor = camt052_version(descriptor.as_bytes());
225    let namespace = camt052_version(head);
226    if descriptor != requested {
227        tracing::debug!(
228            "[FinTS] HICAZ descriptor names camt.052.001.{descriptor:?}, requested .{requested:?}"
229        );
230    }
231    if namespace != descriptor {
232        tracing::warn!(
233            "[FinTS] HICAZ document namespace is camt.052.001.{namespace:?}, its descriptor .{descriptor:?}; parsing by element name"
234        );
235    }
236}
237
238fn camt_err(msg: String) -> FinTSError {
239    FinTSError::Camt(msg)
240}
241
242fn on_start(path: &[String], e: &BytesStart<'_>, entry: &mut Option<Entry>) {
243    let Some(last) = path.last() else {
244        return;
245    };
246    match last.as_str() {
247        "Ntry" if ends_with(path, &["Rpt", "Ntry"]) => *entry = Some(Entry::default()),
248        "TxDtls" => {
249            if let Some(en) = entry.as_mut() {
250                en.tx_details += 1;
251            }
252        }
253        "Amt" if ends_with(path, &["Ntry", "Amt"]) => {
254            if let Some(en) = entry.as_mut() {
255                en.currency = ccy_attr(e);
256            }
257        }
258        "Amt" if ends_with(path, &["AmtDtls", "InstdAmt", "Amt"]) => {
259            if let Some(en) = entry.as_mut()
260                && en.original_currency.is_none()
261            {
262                en.original_currency = ccy_attr(e);
263            }
264        }
265        "TtlChrgsAndTaxAmt" if ends_with(path, &["Chrgs", "TtlChrgsAndTaxAmt"]) => {
266            if let Some(en) = entry.as_mut()
267                && en.fee_total_currency.is_none()
268            {
269                en.fee_total_currency = ccy_attr(e);
270            }
271        }
272        "Amt" if ends_with(path, &["Chrgs", "Rcrd", "Amt"]) => {
273            if let Some(en) = entry.as_mut()
274                && en.fee_record_currency.is_none()
275            {
276                en.fee_record_currency = ccy_attr(e);
277            }
278        }
279        _ => {}
280    }
281}
282
283/// The `Ccy` attribute of an amount element.
284fn ccy_attr(e: &BytesStart<'_>) -> Option<String> {
285    e.attributes()
286        .flatten()
287        .find(|a| local_name(a.key.as_ref()) == "Ccy")
288        .map(|a| String::from_utf8_lossy(&a.value).trim().to_string())
289}
290
291/// Element name without namespace prefix.
292fn local_name(name: &[u8]) -> String {
293    let full = String::from_utf8_lossy(name);
294    match full.rsplit_once(':') {
295        Some((_, local)) => local.to_string(),
296        None => full.into_owned(),
297    }
298}
299
300fn ends_with(path: &[String], suffix: &[&str]) -> bool {
301    path.len() >= suffix.len()
302        && path[path.len() - suffix.len()..]
303            .iter()
304            .zip(suffix)
305            .all(|(a, b)| a == b)
306}
307
308/// Fields collected for one `<Ntry>`.
309#[derive(Default)]
310struct Entry {
311    amount: Option<String>,
312    currency: Option<String>,
313    credit_debit: Option<String>,
314    reversal: bool,
315    status: Option<String>,
316    booking_date: Option<String>,
317    value_date: Option<String>,
318    bank_reference: Option<String>,
319    bank_tx_code: Option<String>,
320    additional_info: Option<String>,
321    /// Number of `<TxDtls>` seen; only the first one is mapped.
322    tx_details: u32,
323    end_to_end_id: Option<String>,
324    mandate_id: Option<String>,
325    tx_bank_reference: Option<String>,
326    proprietary_reference: Option<String>,
327    debtor_name: Option<String>,
328    debtor_iban: Option<String>,
329    debtor_bic: Option<String>,
330    creditor_name: Option<String>,
331    creditor_iban: Option<String>,
332    creditor_bic: Option<String>,
333    creditor_id: Option<String>,
334    debtor_id: Option<String>,
335    original_amount: Option<String>,
336    original_currency: Option<String>,
337    fee_total: Option<String>,
338    fee_total_currency: Option<String>,
339    fee_record: Option<String>,
340    fee_record_currency: Option<String>,
341    return_reason: Option<String>,
342    sequence_type: Option<String>,
343    ultimate_debtor: Option<String>,
344    ultimate_creditor: Option<String>,
345    purpose_code: Option<String>,
346    remittance: Option<String>,
347}
348
349fn set(slot: &mut Option<String>, text: &str) {
350    if slot.is_none() {
351        *slot = Some(text.to_string());
352    }
353}
354
355impl Entry {
356    fn on_text(&mut self, path: &[String], text: &str) {
357        let p = |suffix: &[&str]| ends_with(path, suffix);
358        // Entry level (directly under Ntry).
359        if p(&["Ntry", "Amt"]) {
360            set(&mut self.amount, text);
361        } else if p(&["Ntry", "CdtDbtInd"]) {
362            set(&mut self.credit_debit, text);
363        } else if p(&["Ntry", "RvslInd"]) {
364            self.reversal = text.eq_ignore_ascii_case("true");
365        } else if p(&["Ntry", "Sts"]) || p(&["Ntry", "Sts", "Cd"]) {
366            set(&mut self.status, text);
367        } else if p(&["Ntry", "BookgDt", "Dt"]) || p(&["Ntry", "BookgDt", "DtTm"]) {
368            set(&mut self.booking_date, text);
369        } else if p(&["Ntry", "ValDt", "Dt"]) || p(&["Ntry", "ValDt", "DtTm"]) {
370            set(&mut self.value_date, text);
371        } else if p(&["Ntry", "AcctSvcrRef"]) {
372            set(&mut self.bank_reference, text);
373        } else if p(&["Ntry", "BkTxCd", "Prtry", "Cd"]) {
374            set(&mut self.bank_tx_code, text);
375        } else if p(&["Ntry", "AddtlNtryInf"]) {
376            set(&mut self.additional_info, text);
377        }
378
379        // Fees may sit on the entry or in its details.
380        if p(&["Chrgs", "TtlChrgsAndTaxAmt"]) {
381            set(&mut self.fee_total, text);
382        } else if p(&["Chrgs", "Rcrd", "Amt"]) {
383            set(&mut self.fee_record, text);
384        }
385
386        // Transaction details: only the first TxDtls of a (batch) entry.
387        if self.tx_details != 1 || !path.iter().any(|s| s == "TxDtls") {
388            return;
389        }
390        let name =
391            |party: &str| p(&["RltdPties", party, "Nm"]) || p(&["RltdPties", party, "Pty", "Nm"]);
392        let bic = |agent: &str| {
393            p(&["RltdAgts", agent, "FinInstnId", "BIC"])
394                || p(&["RltdAgts", agent, "FinInstnId", "BICFI"])
395        };
396        if p(&["Refs", "EndToEndId"]) {
397            set(&mut self.end_to_end_id, text);
398        } else if p(&["Refs", "MndtId"]) {
399            set(&mut self.mandate_id, text);
400        } else if p(&["Refs", "AcctSvcrRef"]) {
401            set(&mut self.tx_bank_reference, text);
402        } else if p(&["Refs", "Prtry", "Ref"]) {
403            set(&mut self.proprietary_reference, text);
404        } else if p(&["TxDtls", "BkTxCd", "Prtry", "Cd"]) {
405            set(&mut self.bank_tx_code, text);
406        } else if name("Dbtr") {
407            set(&mut self.debtor_name, text);
408        } else if name("Cdtr") {
409            set(&mut self.creditor_name, text);
410        } else if name("UltmtDbtr") {
411            set(&mut self.ultimate_debtor, text);
412        } else if name("UltmtCdtr") {
413            set(&mut self.ultimate_creditor, text);
414        } else if p(&["AmtDtls", "InstdAmt", "Amt"]) {
415            set(&mut self.original_amount, text);
416        } else if p(&["RtrInf", "Rsn", "Cd"]) {
417            set(&mut self.return_reason, text);
418        } else if p(&["PmtTpInf", "SeqTp"]) {
419            set(&mut self.sequence_type, text);
420        } else if p(&["RltdPties", "Dbtr", "Id", "PrvtId", "Othr", "Id"])
421            || p(&["RltdPties", "Dbtr", "Pty", "Id", "PrvtId", "Othr", "Id"])
422            || p(&["RltdPties", "Dbtr", "Id", "OrgId", "Othr", "Id"])
423            || p(&["RltdPties", "Dbtr", "Pty", "Id", "OrgId", "Othr", "Id"])
424        {
425            set(&mut self.debtor_id, text);
426        } else if p(&["RltdPties", "DbtrAcct", "Id", "IBAN"]) {
427            set(&mut self.debtor_iban, text);
428        } else if p(&["RltdPties", "CdtrAcct", "Id", "IBAN"]) {
429            set(&mut self.creditor_iban, text);
430        } else if p(&["RltdPties", "Cdtr", "Id", "PrvtId", "Othr", "Id"])
431            || p(&["RltdPties", "Cdtr", "Pty", "Id", "PrvtId", "Othr", "Id"])
432        {
433            // The SEPA creditor identifier of a direct debit sits in the
434            // creditor's PrvtId/Othr, as in pain.008 (Anlage 3 V26.11,
435            // 7.1.7.4 Related Parties). camt.052 has no CdtrSchmeId, and an
436            // OrgId/Othr is some other organisation identifier.
437            set(&mut self.creditor_id, text);
438        } else if bic("DbtrAgt") {
439            set(&mut self.debtor_bic, text);
440        } else if bic("CdtrAgt") {
441            set(&mut self.creditor_bic, text);
442        } else if p(&["Purp", "Cd"]) {
443            set(&mut self.purpose_code, text);
444        } else if p(&["RmtInf", "Ustrd"]) {
445            // Several <Ustrd> parts are the bank's lines (comdirect sends
446            // lines of differing length, live 2026-11-19): keep them apart
447            // with a line break (owner 2026-11-19).
448            match self.remittance.as_mut() {
449                Some(r) => {
450                    r.push('\n');
451                    r.push_str(text);
452                }
453                None => self.remittance = Some(text.to_string()),
454            }
455        }
456    }
457
458    fn build(
459        self,
460        report_currency: Option<&str>,
461        report_created: Option<&str>,
462        booking_id: BookingIdSource,
463    ) -> std::result::Result<Transaction, String> {
464        let amount_text = self.amount.as_deref().ok_or("no <Amt>")?;
465        let magnitude = Decimal::from_str(amount_text.trim())
466            .map_err(|e| format!("bad amount '{amount_text}': {e}"))?;
467        let is_debit = match self.credit_debit.as_deref() {
468            Some("DBIT") => true,
469            Some("CRDT") => false,
470            other => return Err(format!("bad <CdtDbtInd> {other:?}")),
471        };
472        let amount = if is_debit { -magnitude } else { magnitude };
473
474        let value_date = self.value_date.as_deref().map(iso_date).transpose()?;
475        let booking_date = self.booking_date.as_deref().map(iso_date).transpose()?;
476        // Same rule as MT940: booking date, else value date. A pending entry
477        // may carry neither (comdirect, live 2026-11-19); it then takes the
478        // day the bank made the report. A booked entry without a date stays
479        // an error.
480        let pending_date = match (self.status.as_deref(), report_created) {
481            (Some("PDNG"), Some(created)) => iso_date(created).ok(),
482            _ => None,
483        };
484        let date = booking_date
485            .or(value_date)
486            .or(pending_date)
487            .ok_or("neither <BookgDt> nor <ValDt>")?;
488
489        let currency = self
490            .currency
491            .clone()
492            .or_else(|| report_currency.map(str::to_string))
493            .unwrap_or_else(|| "EUR".to_string());
494
495        // The counterparty: the creditor of a debit, the debtor of a credit.
496        let (name, iban, bic) = if is_debit {
497            (
498                self.creditor_name.clone(),
499                self.creditor_iban.clone(),
500                self.creditor_bic.clone(),
501            )
502        } else {
503            (
504                self.debtor_name.clone(),
505                self.debtor_iban.clone(),
506                self.debtor_bic.clone(),
507            )
508        };
509
510        // `Sts` PDNG marks a pending entry; BOOK, INFO and a missing status
511        // count as booked.
512        let pending = self.status.as_deref() == Some("PDNG");
513        let status = if pending {
514            TransactionStatus::Pending
515        } else {
516            TransactionStatus::Booked
517        };
518        let (gvc, prima_nota) = dk_bank_tx_code(self.bank_tx_code.as_deref());
519        let end_to_end_id = self
520            .end_to_end_id
521            .clone()
522            .filter(|r| !crate::formats::absent(r));
523        let mandate_id = self
524            .mandate_id
525            .clone()
526            .filter(|r| !crate::formats::absent(r));
527        let creditor_id = self
528            .creditor_id
529            .clone()
530            .filter(|r| !crate::formats::absent(r));
531        let debtor_id = self
532            .debtor_id
533            .clone()
534            .filter(|r| !crate::formats::absent(r));
535        let money = |amount: Option<&str>, ccy: Option<&str>| -> Option<(Decimal, Currency)> {
536            let a = Decimal::from_str(amount?.trim()).ok()?.abs();
537            Some((a, Currency::new(ccy.unwrap_or(&currency))))
538        };
539        let original_amount = money(
540            self.original_amount.as_deref(),
541            self.original_currency.as_deref(),
542        );
543        let fees = if self.fee_total.is_some() {
544            money(
545                self.fee_total.as_deref(),
546                self.fee_total_currency.as_deref(),
547            )
548        } else {
549            money(
550                self.fee_record.as_deref(),
551                self.fee_record_currency.as_deref(),
552            )
553        };
554        // The remittance text only. An entry without <Ustrd> has no purpose:
555        // its additional entry information is the booking text, not a
556        // second copy of it (owner 2026-11-19).
557        let purpose = self.remittance.clone();
558        let booking_id = match booking_id {
559            BookingIdSource::CamtEntryAcctSvcrRef if self.status.as_deref() == Some("BOOK") => {
560                self.bank_reference.clone()
561            }
562            _ => None,
563        };
564        let bank_reference = self
565            .tx_bank_reference
566            .clone()
567            .or_else(|| self.bank_reference.clone())
568            .or_else(|| self.proprietary_reference.clone());
569
570        let raw = serde_json::json!({
571            "source": "camt.052",
572            "booking_date": self.booking_date,
573            "value_date": self.value_date,
574            "amount": amount.to_string(),
575            "currency": currency,
576            "credit_debit": self.credit_debit,
577            "reversal": self.reversal,
578            "status": self.status,
579            "bank_tx_code": self.bank_tx_code,
580            "end_to_end_id": self.end_to_end_id,
581            "mandate_id": self.mandate_id,
582            "creditor_id": self.creditor_id,
583            "proprietary_reference": self.proprietary_reference,
584            "account_servicer_reference": self.tx_bank_reference.or(self.bank_reference),
585            "debtor_name": self.debtor_name,
586            "creditor_name": self.creditor_name,
587            "ultimate_debtor": self.ultimate_debtor,
588            "ultimate_creditor": self.ultimate_creditor,
589            "debtor_id": self.debtor_id,
590            "return_reason": self.return_reason,
591            "sequence_type": self.sequence_type,
592            "tx_details_count": self.tx_details,
593        });
594
595        Ok(Transaction {
596            date,
597            valuta_date: value_date,
598            amount,
599            currency: Currency::new(currency),
600            applicant_name: name,
601            applicant_iban: iban.map(Iban::new),
602            applicant_bic: bic.map(Bic::new),
603            purpose,
604            posting_text: self.additional_info,
605            customer_reference: None,
606            bank_reference,
607            booking_id,
608            gvc,
609            prima_nota,
610            purpose_code: self.purpose_code,
611            mandate_id,
612            creditor_id,
613            end_to_end_id,
614            debtor_id,
615            ultimate_debtor: self.ultimate_debtor.clone(),
616            ultimate_creditor: self.ultimate_creditor.clone(),
617            reversal: self.reversal,
618            original_amount,
619            fees,
620            return_reason: self.return_reason.clone(),
621            sequence_type: self.sequence_type.clone(),
622            raw,
623            status,
624        })
625    }
626}
627
628/// `2026-08-20` or `2026-08-20T10:15:00[+02:00]` → date.
629fn iso_date(s: &str) -> std::result::Result<Date, String> {
630    s.get(..10)
631        .and_then(|d| d.parse::<Date>().ok())
632        .ok_or_else(|| format!("bad date '{s}'"))
633}
634
635/// German banks fill `BkTxCd/Prtry/Cd` as `<SWIFT code>+<GVC>+<primanota>[+…]`,
636/// e.g. `NDDT+105+9208+888`. Returns (GVC, primanota) when it has that shape.
637fn dk_bank_tx_code(code: Option<&str>) -> (Option<String>, Option<String>) {
638    let Some(code) = code else {
639        return (None, None);
640    };
641    let mut parts = code.split('+');
642    let _swift = parts.next();
643    let gvc = parts
644        .next()
645        .map(str::trim)
646        .filter(|g| g.len() == 3 && g.bytes().all(|b| b.is_ascii_digit()))
647        .map(str::to_string);
648    if gvc.is_none() {
649        return (None, None);
650    }
651    let prima_nota = parts
652        .next()
653        .map(str::trim)
654        .filter(|p| !p.is_empty())
655        .map(str::to_string);
656    (gvc, prima_nota)
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662
663    fn d(y: i16, m: i8, day: i8) -> Date {
664        Date::new(y, m, day).unwrap()
665    }
666
667    fn dec(s: &str) -> Decimal {
668        Decimal::from_str(s).unwrap()
669    }
670
671    /// Synthetic report: invented names, references and DE00 IBANs.
672    const REPORT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
673<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.052.001.02">
674 <BkToCstmrAcctRpt>
675  <GrpHdr><MsgId>TEST-MSG-1</MsgId></GrpHdr>
676  <Rpt>
677   <Id>TEST-RPT-1</Id>
678   <Acct><Id><IBAN>DE00120300009900012345</IBAN></Id><Ccy>EUR</Ccy></Acct>
679   <Ntry>
680    <Amt Ccy="EUR">42.50</Amt>
681    <CdtDbtInd>DBIT</CdtDbtInd>
682    <Sts>BOOK</Sts>
683    <BookgDt><Dt>2026-03-02</Dt></BookgDt>
684    <ValDt><Dt>2026-02-27</Dt></ValDt>
685    <AcctSvcrRef>BANKREF-0001</AcctSvcrRef>
686    <BkTxCd><Prtry><Cd>NDDT+105+9208+888</Cd><Issr>DK</Issr></Prtry></BkTxCd>
687    <AddtlNtryInf>FOLGELASTSCHRIFT</AddtlNtryInf>
688    <NtryDtls><TxDtls>
689     <Refs><EndToEndId>E2E-TEST-0001</EndToEndId><MndtId>MANDATE-TEST-7</MndtId></Refs>
690     <RltdPties>
691      <Dbtr><Nm>Erika Beispiel</Nm></Dbtr>
692      <DbtrAcct><Id><IBAN>DE00120300009900012345</IBAN></Id></DbtrAcct>
693      <Cdtr><Nm>Zahlungsdienst Test GmbH</Nm>
694       <Id><PrvtId><Othr><Id>DE00ZZZ00000000001</Id></Othr></PrvtId></Id></Cdtr>
695      <CdtrAcct><Id><IBAN>DE00500000000000000001</IBAN></Id></CdtrAcct>
696      <UltmtCdtr><Nm>Beispielladen am Markt</Nm></UltmtCdtr>
697     </RltdPties>
698     <RltdAgts><CdtrAgt><FinInstnId><BIC>TESTDEFFXXX</BIC></FinInstnId></CdtrAgt></RltdAgts>
699     <Purp><Cd>IDCP</Cd></Purp>
700     <RmtInf><Ustrd>Bestellung 4711</Ustrd><Ustrd>Kundennummer 12</Ustrd></RmtInf>
701    </TxDtls></NtryDtls>
702   </Ntry>
703   <Ntry>
704    <Amt Ccy="EUR">1500.00</Amt>
705    <CdtDbtInd>CRDT</CdtDbtInd>
706    <Sts>BOOK</Sts>
707    <BookgDt><Dt>2026-03-01</Dt></BookgDt>
708    <ValDt><Dt>2026-03-01</Dt></ValDt>
709    <AddtlNtryInf>GUTSCHRIFT</AddtlNtryInf>
710    <NtryDtls><TxDtls>
711     <Refs><EndToEndId>NOTPROVIDED</EndToEndId></Refs>
712     <RltdPties>
713      <Dbtr><Nm>Musterfirma AG</Nm></Dbtr>
714      <DbtrAcct><Id><IBAN>DE00500000000000000002</IBAN></Id></DbtrAcct>
715      <UltmtDbtr><Nm>Musterfirma Lohnbuero</Nm></UltmtDbtr>
716     </RltdPties>
717     <RltdAgts><DbtrAgt><FinInstnId><BIC>TESTDEFFXXX</BIC></FinInstnId></DbtrAgt></RltdAgts>
718     <RmtInf><Ustrd>Lohn Maerz</Ustrd></RmtInf>
719    </TxDtls></NtryDtls>
720   </Ntry>
721   <Ntry>
722    <Amt>25.00</Amt>
723    <CdtDbtInd>DBIT</CdtDbtInd>
724    <Sts>PDNG</Sts>
725    <ValDt><Dt>2026-03-04</Dt></ValDt>
726    <AddtlNtryInf>DAUERAUFTRAG</AddtlNtryInf>
727   </Ntry>
728  </Rpt>
729 </BkToCstmrAcctRpt>
730</Document>"#;
731
732    /// Synthetic report in the shape DKB sends (camt.052.001.08, `Sts/Cd`,
733    /// the bank reference at entry level, live 2026-11-17): two booked
734    /// entries, one booked batch entry whose `TxDtls` carry their own
735    /// references, a pending entry with a reference and a booked one
736    /// without. References and names are invented.
737    const DKB_SHAPED: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
738<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.052.001.08">
739 <BkToCstmrAcctRpt><Rpt>
740  <Acct><Id><IBAN>DE00120300000000000201</IBAN></Id></Acct>
741  <Ntry><Amt Ccy="EUR">10.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
742   <BookgDt><Dt>2026-03-02</Dt></BookgDt><ValDt><Dt>2026-03-02</Dt></ValDt>
743   <AcctSvcrRef>TESTREF00000000000000000001</AcctSvcrRef>
744   <NtryDtls><TxDtls><RmtInf><Ustrd>Test 1</Ustrd></RmtInf></TxDtls></NtryDtls></Ntry>
745  <Ntry><Amt Ccy="EUR">20.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
746   <BookgDt><Dt>2026-03-03</Dt></BookgDt><ValDt><Dt>2026-03-03</Dt></ValDt>
747   <AcctSvcrRef>TESTREF00000000000000000002</AcctSvcrRef>
748   <NtryDtls><TxDtls><RmtInf><Ustrd>Test 2</Ustrd></RmtInf></TxDtls></NtryDtls></Ntry>
749  <Ntry><Amt Ccy="EUR">30.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
750   <BookgDt><Dt>2026-03-04</Dt></BookgDt><ValDt><Dt>2026-03-04</Dt></ValDt>
751   <AcctSvcrRef>TESTREF00000000000000000003</AcctSvcrRef>
752   <NtryDtls>
753    <TxDtls><Refs><AcctSvcrRef>TESTTX-A</AcctSvcrRef></Refs><Amt Ccy="EUR">10.00</Amt></TxDtls>
754    <TxDtls><Refs><AcctSvcrRef>TESTTX-B</AcctSvcrRef></Refs><Amt Ccy="EUR">20.00</Amt></TxDtls>
755   </NtryDtls></Ntry>
756  <Ntry><Amt Ccy="EUR">5.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>PDNG</Cd></Sts>
757   <ValDt><Dt>2026-03-05</Dt></ValDt>
758   <AcctSvcrRef>TESTREF00000000000000000004</AcctSvcrRef></Ntry>
759  <Ntry><Amt Ccy="EUR">7.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
760   <BookgDt><Dt>2026-03-05</Dt></BookgDt></Ntry>
761 </Rpt></BkToCstmrAcctRpt>
762</Document>"#;
763
764    fn booking_ids(xml: &str, rule: BookingIdSource) -> Vec<Option<String>> {
765        parse_camt052(xml.as_bytes(), rule)
766            .unwrap()
767            .into_iter()
768            .map(|t| t.booking_id)
769            .collect()
770    }
771
772    #[test]
773    fn booked_entries_get_their_entry_reference_as_booking_id() {
774        let ids = booking_ids(DKB_SHAPED, BookingIdSource::CamtEntryAcctSvcrRef);
775        assert_eq!(
776            ids,
777            [
778                Some("TESTREF00000000000000000001".to_string()),
779                Some("TESTREF00000000000000000002".to_string()),
780                // The batch entry: the entry's reference, not a TxDtls one.
781                Some("TESTREF00000000000000000003".to_string()),
782                // Pending: unverified whether it keeps the reference.
783                None,
784                // No reference.
785                None,
786            ]
787        );
788        // bank_reference is unchanged: the TxDtls reference first.
789        let txs =
790            parse_camt052(DKB_SHAPED.as_bytes(), BookingIdSource::CamtEntryAcctSvcrRef).unwrap();
791        assert_eq!(txs[2].bank_reference.as_deref(), Some("TESTTX-A"));
792        assert_eq!(
793            txs[3].bank_reference.as_deref(),
794            Some("TESTREF00000000000000000004")
795        );
796    }
797
798    #[test]
799    fn without_the_profile_rule_no_entry_gets_a_booking_id() {
800        let ids = booking_ids(DKB_SHAPED, BookingIdSource::None);
801        assert!(ids.iter().all(Option::is_none), "{ids:?}");
802        let ids = booking_ids(REPORT, BookingIdSource::None);
803        assert!(ids.iter().all(Option::is_none), "{ids:?}");
804    }
805
806    #[test]
807    fn a_reference_on_two_entries_is_no_booking_id() {
808        let twice =
809            DKB_SHAPED.replace("TESTREF00000000000000000002", "TESTREF00000000000000000001");
810        let ids = booking_ids(&twice, BookingIdSource::CamtEntryAcctSvcrRef);
811        assert_eq!(ids[0], None);
812        assert_eq!(ids[1], None);
813        assert_eq!(ids[2].as_deref(), Some("TESTREF00000000000000000003"));
814    }
815
816    #[test]
817    fn an_entry_without_explicit_booked_status_gets_no_booking_id() {
818        let no_status = DKB_SHAPED.replacen("<Sts><Cd>BOOK</Cd></Sts>", "", 1);
819        let txs =
820            parse_camt052(no_status.as_bytes(), BookingIdSource::CamtEntryAcctSvcrRef).unwrap();
821        assert_eq!(txs[0].status, TransactionStatus::Booked);
822        assert_eq!(txs[0].booking_id, None);
823        assert!(txs[1].booking_id.is_some());
824    }
825
826    #[test]
827    fn maps_debit_entry_with_ultimate_party_purpose_code_and_mandate() {
828        let txs = parse_camt052(REPORT.as_bytes(), BookingIdSource::None).unwrap();
829        assert_eq!(txs.len(), 3);
830        let tx = &txs[0];
831        assert_eq!(tx.amount, dec("-42.50"));
832        assert_eq!(tx.currency.as_str(), "EUR");
833        assert_eq!(
834            tx.applicant_name.as_deref(),
835            Some("Zahlungsdienst Test GmbH")
836        );
837        assert_eq!(
838            tx.ultimate_creditor.as_deref(),
839            Some("Beispielladen am Markt")
840        );
841        assert_eq!(tx.ultimate_debtor, None);
842        assert_eq!(
843            tx.applicant_iban.as_ref().map(|i| i.as_str()),
844            Some("DE00500000000000000001")
845        );
846        assert_eq!(
847            tx.applicant_bic.as_ref().map(|b| b.as_str()),
848            Some("TESTDEFFXXX")
849        );
850        assert_eq!(tx.purpose_code.as_deref(), Some("IDCP"));
851        assert_eq!(tx.mandate_id.as_deref(), Some("MANDATE-TEST-7"));
852        assert_eq!(tx.end_to_end_id.as_deref(), Some("E2E-TEST-0001"));
853        assert_eq!(
854            tx.customer_reference, None,
855            "CAMT has no customer reference"
856        );
857        assert!(!tx.reversal);
858        assert_eq!(tx.bank_reference.as_deref(), Some("BANKREF-0001"));
859        assert_eq!(tx.gvc.as_deref(), Some("105"));
860        assert_eq!(tx.prima_nota.as_deref(), Some("9208"));
861        assert_eq!(tx.posting_text.as_deref(), Some("FOLGELASTSCHRIFT"));
862        assert_eq!(
863            tx.purpose.as_deref(),
864            Some("Bestellung 4711\nKundennummer 12")
865        );
866        assert_eq!(tx.raw["creditor_id"], "DE00ZZZ00000000001");
867        assert_eq!(tx.status, TransactionStatus::Booked);
868    }
869
870    /// Same date semantics as MT940: `date` = booking date (BookgDt),
871    /// `valuta_date` = value date (ValDt).
872    /// One entry with the optional fields of F3, all synthetic.
873    fn rich_entry(extra_entry: &str, details: &str) -> Transaction {
874        let xml = format!(
875            r#"<Document><BkToCstmrAcctRpt><Rpt>
876<Acct><Ccy>EUR</Ccy></Acct>
877<Ntry><Amt Ccy="EUR">10.00</Amt><CdtDbtInd>CRDT</CdtDbtInd>{extra_entry}
878<Sts>BOOK</Sts><BookgDt><Dt>2026-03-01</Dt></BookgDt>
879<NtryDtls><TxDtls>{details}</TxDtls></NtryDtls></Ntry>
880</Rpt></BkToCstmrAcctRpt></Document>"#
881        );
882        parse_camt052(xml.as_bytes(), BookingIdSource::None)
883            .unwrap()
884            .remove(0)
885    }
886
887    #[test]
888    fn reversal_indicator() {
889        assert!(rich_entry("<RvslInd>true</RvslInd>", "").reversal);
890        assert!(!rich_entry("<RvslInd>false</RvslInd>", "").reversal);
891        assert!(!rich_entry("", "").reversal);
892    }
893
894    /// The SEPA creditor ID is the creditor's PrvtId/Othr/Id (Anlage 3
895    /// V26.11, 7.1.7.4), with or without the `Pty` of camt.052.001.08's
896    /// Party40Choice; an OrgId/Othr is not a creditor ID.
897    #[test]
898    fn creditor_id_from_private_id_only() {
899        let plain = rich_entry(
900            "",
901            "<RltdPties><Cdtr><Nm>C</Nm><Id><PrvtId><Othr><Id>DE00ZZZ00000000002</Id><SchmeNm><Prtry>SEPA</Prtry></SchmeNm></Othr></PrvtId></Id></Cdtr></RltdPties>",
902        );
903        assert_eq!(plain.creditor_id.as_deref(), Some("DE00ZZZ00000000002"));
904        let party = rich_entry(
905            "",
906            "<RltdPties><Cdtr><Pty><Nm>C</Nm><Id><PrvtId><Othr><Id>DE00ZZZ00000000003</Id></Othr></PrvtId></Id></Pty></Cdtr></RltdPties>",
907        );
908        assert_eq!(party.creditor_id.as_deref(), Some("DE00ZZZ00000000003"));
909        let org = rich_entry(
910            "",
911            "<RltdPties><Cdtr><Nm>C</Nm><Id><OrgId><Othr><Id>ORG-ID-1</Id></Othr></OrgId></Id></Cdtr></RltdPties>",
912        );
913        assert_eq!(org.creditor_id, None);
914    }
915
916    #[test]
917    fn debtor_id_from_private_or_organisation_id() {
918        let private = rich_entry(
919            "",
920            "<RltdPties><Dbtr><Nm>A</Nm><Id><PrvtId><Othr><Id>DEBTOR-ID-1</Id></Othr></PrvtId></Id></Dbtr></RltdPties>",
921        );
922        assert_eq!(private.debtor_id.as_deref(), Some("DEBTOR-ID-1"));
923        let org = rich_entry(
924            "",
925            "<RltdPties><Dbtr><Nm>A</Nm><Id><OrgId><Othr><Id>DEBTOR-ID-2</Id></Othr></OrgId></Id></Dbtr></RltdPties>",
926        );
927        assert_eq!(org.debtor_id.as_deref(), Some("DEBTOR-ID-2"));
928        let placeholder = rich_entry(
929            "",
930            "<RltdPties><Dbtr><Id><PrvtId><Othr><Id>NOTPROVIDED</Id></Othr></PrvtId></Id></Dbtr></RltdPties>",
931        );
932        assert_eq!(placeholder.debtor_id, None);
933    }
934
935    #[test]
936    fn original_amount_fees_return_reason_and_sequence_type() {
937        let tx = rich_entry(
938            "<Chrgs><TtlChrgsAndTaxAmt Ccy=\"EUR\">1.50</TtlChrgsAndTaxAmt></Chrgs>",
939            r#"<AmtDtls><InstdAmt><Amt Ccy="USD">11.20</Amt></InstdAmt></AmtDtls>
940<RtrInf><Rsn><Cd>MD06</Cd></Rsn></RtrInf>
941<RltdPties/><PmtTpInf><SeqTp>RCUR</SeqTp></PmtTpInf>"#,
942        );
943        assert_eq!(
944            tx.original_amount,
945            Some((dec("11.20"), Currency::new("USD")))
946        );
947        assert_eq!(tx.fees, Some((dec("1.50"), Currency::new("EUR"))));
948        assert_eq!(tx.return_reason.as_deref(), Some("MD06"));
949        assert_eq!(tx.sequence_type.as_deref(), Some("RCUR"));
950        let none = rich_entry("", "");
951        assert_eq!(none.original_amount, None);
952        assert_eq!(none.fees, None);
953        assert_eq!(none.return_reason, None);
954        assert_eq!(none.sequence_type, None);
955    }
956
957    #[test]
958    fn fee_record_is_used_without_a_total() {
959        let tx = rich_entry(
960            r#"<Chrgs><Rcrd><Amt Ccy="CHF">2.00</Amt></Rcrd></Chrgs>"#,
961            "",
962        );
963        assert_eq!(tx.fees, Some((dec("2.00"), Currency::new("CHF"))));
964    }
965
966    #[test]
967    fn camt_booking_and_value_date_not_swapped() {
968        let tx = &parse_camt052(REPORT.as_bytes(), BookingIdSource::None).unwrap()[0];
969        assert_eq!(tx.date, d(2026, 3, 2), "date is the booking date");
970        assert_eq!(
971            tx.valuta_date,
972            Some(d(2026, 2, 27)),
973            "valuta_date is the value date"
974        );
975    }
976
977    #[test]
978    fn maps_credit_entry_from_debtor_side() {
979        let tx = &parse_camt052(REPORT.as_bytes(), BookingIdSource::None).unwrap()[1];
980        assert_eq!(tx.amount, dec("1500.00"));
981        assert_eq!(tx.applicant_name.as_deref(), Some("Musterfirma AG"));
982        assert_eq!(tx.ultimate_debtor.as_deref(), Some("Musterfirma Lohnbuero"));
983        assert_eq!(tx.ultimate_creditor, None);
984        assert_eq!(tx.debtor_id, None);
985        assert_eq!(
986            tx.applicant_iban.as_ref().map(|i| i.as_str()),
987            Some("DE00500000000000000002")
988        );
989        assert_eq!(tx.end_to_end_id, None, "NOTPROVIDED is no reference");
990        assert_eq!(tx.mandate_id, None);
991    }
992
993    /// comdirect's shape (live 2026-11-19): a pending entry with no dates.
994    fn dateless(status: &str, header: &str) -> String {
995        format!(
996            r#"<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.052.001.08"><BkToCstmrAcctRpt>{header}<Rpt>
997<Acct><Id><IBAN>DE00200411550000000101</IBAN></Id></Acct>
998<Ntry><Amt Ccy="EUR">1.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>{status}</Cd></Sts>
999<NtryDtls><TxDtls><RmtInf><Ustrd>Test</Ustrd></RmtInf></TxDtls></NtryDtls></Ntry>
1000</Rpt></BkToCstmrAcctRpt></Document>"#
1001        )
1002    }
1003
1004    const CREATED: &str = "<GrpHdr><CreDtTm>2026-11-19T22:04:56.236+01:00</CreDtTm></GrpHdr>";
1005
1006    #[test]
1007    fn a_pending_entry_without_dates_takes_the_day_of_the_report() {
1008        let xml = dateless("PDNG", CREATED);
1009        let tx = &parse_camt052(xml.as_bytes(), BookingIdSource::None).unwrap()[0];
1010        assert_eq!(tx.status, TransactionStatus::Pending);
1011        assert_eq!(tx.date, d(2026, 11, 19));
1012        assert_eq!(tx.valuta_date, None);
1013    }
1014
1015    #[test]
1016    fn a_dateless_entry_is_an_error_when_booked_or_without_a_report_time() {
1017        for xml in [dateless("BOOK", CREATED), dateless("PDNG", "")] {
1018            let err = parse_camt052(xml.as_bytes(), BookingIdSource::None).unwrap_err();
1019            assert!(
1020                err.to_string().contains("neither <BookgDt> nor <ValDt>"),
1021                "{err}"
1022            );
1023        }
1024    }
1025
1026    #[test]
1027    fn pending_entry_without_booking_date_uses_value_date_and_report_currency() {
1028        let tx = &parse_camt052(REPORT.as_bytes(), BookingIdSource::None).unwrap()[2];
1029        assert_eq!(tx.status, TransactionStatus::Pending);
1030        assert_eq!(tx.date, d(2026, 3, 4));
1031        assert_eq!(tx.valuta_date, Some(d(2026, 3, 4)));
1032        assert_eq!(tx.currency.as_str(), "EUR");
1033        assert_eq!(tx.applicant_name, None);
1034        // No <Ustrd>: no purpose; the entry information is the booking text.
1035        assert_eq!(tx.purpose, None);
1036        assert_eq!(tx.posting_text.as_deref(), Some("DAUERAUFTRAG"));
1037    }
1038
1039    #[test]
1040    fn later_schema_versions_with_prefixes_and_datetimes() {
1041        let xml = r#"<?xml version="1.0"?>
1042<c:Document xmlns:c="urn:iso:std:iso:20022:tech:xsd:camt.052.001.08">
1043 <c:BkToCstmrAcctRpt><c:Rpt>
1044  <c:Acct><c:Ccy>USD</c:Ccy></c:Acct>
1045  <c:Ntry>
1046   <c:Amt>7.5</c:Amt><c:CdtDbtInd>CRDT</c:CdtDbtInd>
1047   <c:Sts><c:Cd>BOOK</c:Cd></c:Sts>
1048   <c:BookgDt><c:DtTm>2026-05-06T09:30:00+02:00</c:DtTm></c:BookgDt>
1049   <c:NtryDtls><c:TxDtls>
1050    <c:RltdPties><c:Dbtr><c:Pty><c:Nm>Pty &amp; Name</c:Nm></c:Pty></c:Dbtr></c:RltdPties>
1051    <c:RltdAgts><c:DbtrAgt><c:FinInstnId><c:BICFI>TESTDEFFXXX</c:BICFI></c:FinInstnId></c:DbtrAgt></c:RltdAgts>
1052   </c:TxDtls><c:TxDtls>
1053    <c:RltdPties><c:Dbtr><c:Pty><c:Nm>Second detail ignored</c:Nm></c:Pty></c:Dbtr></c:RltdPties>
1054   </c:TxDtls></c:NtryDtls>
1055  </c:Ntry>
1056 </c:Rpt></c:BkToCstmrAcctRpt>
1057</c:Document>"#;
1058        let txs = parse_camt052(xml.as_bytes(), BookingIdSource::None).unwrap();
1059        assert_eq!(txs.len(), 1);
1060        let tx = &txs[0];
1061        assert_eq!(tx.date, d(2026, 5, 6));
1062        assert_eq!(tx.valuta_date, None);
1063        assert_eq!(tx.currency.as_str(), "USD");
1064        assert_eq!(tx.applicant_name.as_deref(), Some("Pty & Name"));
1065        assert_eq!(
1066            tx.applicant_bic.as_ref().map(|b| b.as_str()),
1067            Some("TESTDEFFXXX")
1068        );
1069        assert_eq!(tx.raw["tx_details_count"], 2);
1070    }
1071
1072    #[test]
1073    fn empty_report_and_errors() {
1074        let empty = r#"<Document><BkToCstmrAcctRpt><Rpt><Acct><Ccy>EUR</Ccy></Acct></Rpt></BkToCstmrAcctRpt></Document>"#;
1075        assert!(
1076            parse_camt052(empty.as_bytes(), BookingIdSource::None)
1077                .unwrap()
1078                .is_empty()
1079        );
1080        assert!(parse_camt052(b"<not valid xml", BookingIdSource::None).is_err());
1081        let no_amount = "<Document><Rpt><Ntry><CdtDbtInd>CRDT</CdtDbtInd>\
1082            <BookgDt><Dt>2026-01-01</Dt></BookgDt></Ntry></Rpt></Document>";
1083        assert!(matches!(
1084            parse_camt052(no_amount.as_bytes(), BookingIdSource::None),
1085            Err(FinTSError::Camt(_))
1086        ));
1087        let bad_date = "<Document><Rpt><Ntry><Amt>1</Amt><CdtDbtInd>CRDT</CdtDbtInd>\
1088            <BookgDt><Dt>2026-02-30</Dt></BookgDt></Ntry></Rpt></Document>";
1089        assert!(parse_camt052(bad_date.as_bytes(), BookingIdSource::None).is_err());
1090    }
1091
1092    #[test]
1093    fn dk_code_split() {
1094        assert_eq!(
1095            dk_bank_tx_code(Some("NTRF+166+9310+997")),
1096            (Some("166".into()), Some("9310".into()))
1097        );
1098        assert_eq!(dk_bank_tx_code(Some("PMNT-RCDT-ESCT")), (None, None));
1099        assert_eq!(dk_bank_tx_code(None), (None, None));
1100    }
1101
1102    proptest::proptest! {
1103        #[test]
1104        fn never_panics_on_random_bytes(data in proptest::collection::vec(proptest::num::u8::ANY, 0..512)) {
1105            let _ = parse_camt052(&data, BookingIdSource::None);
1106        }
1107
1108        #[test]
1109        fn never_panics_on_xml_shaped_input(
1110            parts in proptest::collection::vec(
1111                proptest::prop_oneof![
1112                    proptest::strategy::Just("<Rpt>".to_string()),
1113                    proptest::strategy::Just("<Ntry>".to_string()),
1114                    proptest::strategy::Just("</Ntry>".to_string()),
1115                    proptest::strategy::Just("<Amt Ccy=\"EUR\">".to_string()),
1116                    proptest::strategy::Just("</Amt>".to_string()),
1117                    proptest::strategy::Just("<CdtDbtInd>DBIT</CdtDbtInd>".to_string()),
1118                    proptest::strategy::Just("<BookgDt><Dt>".to_string()),
1119                    proptest::strategy::Just("</Dt></BookgDt>".to_string()),
1120                    proptest::strategy::Just("<TxDtls><RmtInf><Ustrd>".to_string()),
1121                    proptest::strategy::Just("</Ustrd></RmtInf></TxDtls>".to_string()),
1122                    "[0-9A-Za-z<>/&;.: -]{0,12}",
1123                ],
1124                0..24,
1125            )
1126        ) {
1127            let _ = parse_camt052(parts.concat().as_bytes(), BookingIdSource::None);
1128        }
1129    }
1130}
1131
1132#[cfg(test)]
1133mod root_tests {
1134    use super::*;
1135
1136    #[test]
1137    fn rejects_other_messages() {
1138        let camt053 = br#"<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02"><BkToCstmrStmt/></Document>"#;
1139        assert!(matches!(
1140            parse_camt052(camt053, BookingIdSource::None),
1141            Err(FinTSError::Camt(_))
1142        ));
1143        let other = br#"<Foo><BkToCstmrAcctRpt/></Foo>"#;
1144        assert!(matches!(
1145            parse_camt052(other, BookingIdSource::None),
1146            Err(FinTSError::Camt(_))
1147        ));
1148        let ok = br#"<Document><BkToCstmrAcctRpt/></Document>"#;
1149        assert!(parse_camt052(ok, BookingIdSource::None).unwrap().is_empty());
1150    }
1151
1152    #[test]
1153    fn version_from_descriptor_and_namespace() {
1154        assert_eq!(
1155            camt052_version(b"urn:iso:std:iso:20022:tech:xsd:camt.052.001.02.xsd"),
1156            Some(2)
1157        );
1158        assert_eq!(camt052_version(b"camt.052.001.08"), Some(8));
1159        assert_eq!(camt052_version(b"camt.053.001.08"), None);
1160    }
1161}