Skip to main content

fints_client/jobs/transfer/
input.rs

1//! A SEPA credit transfer as the caller describes it, and its checks
2//! (docs/payments-design.md section 2).
3//!
4//! [`Transfer::check`] runs before anything is sent and returns a
5//! [`CheckedTransfer`]: the parsed IBANs and BICs, the resolved debtor name
6//! and the final end-to-end ID. It rejects; it never repairs text
7//! ([`crate::formats::sepa::transliterate`] is there for a caller that wants
8//! to offer a cleaned text).
9
10use std::fmt;
11
12use rust_decimal::Decimal;
13use serde::{Deserialize, Serialize};
14
15use crate::formats::pain001::{Pain001Input, generate_reference};
16use crate::formats::sepa::{Invalid, check_reference, first_invalid_char};
17use crate::protocol::Account;
18use crate::types::{Bic, Iban};
19
20/// Longest name of a party (Anlage 3 2.1 "Namen für beteiligte Parteien").
21const MAX_NAME: usize = 70;
22/// Longest unstructured remittance information (Anlage 3 2.2.1.7).
23const MAX_PURPOSE: usize = 140;
24/// Largest amount of an SCT / SCT Inst (Anlage 3 2.3.3).
25fn max_amount() -> Decimal {
26    Decimal::new(99_999_999_999, 2)
27}
28
29/// One SEPA credit transfer in EUR from an own account.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct Transfer {
32    /// The debtor account; must have an IBAN.
33    pub from: Account,
34    /// The debtor name; `None`: the UPD account holder name.
35    pub debtor_name: Option<String>,
36    /// At most 70 characters of the SEPA text set.
37    pub payee_name: String,
38    /// Checked by [`Iban::parse`]; spaces and lower case are accepted.
39    pub payee_iban: String,
40    /// 8 or 11 characters; `None`: IBAN-only.
41    pub payee_bic: Option<String>,
42    /// EUR, greater than zero, at most 999 999 999.99, at most two decimals.
43    pub amount: Decimal,
44    /// Unstructured remittance information, at most 140 characters of the
45    /// SEPA text set; may be empty.
46    pub purpose: String,
47    /// At most 35 characters of the SEPA reference set; `None`: the library
48    /// generates a unique one in [`Transfer::check`] (read it from
49    /// [`CheckedTransfer::end_to_end_id`] before sending).
50    pub end_to_end_id: Option<String>,
51    /// Standard or instant transfer.
52    pub instant: Instant,
53}
54
55/// Whether to send the transfer as an instant transfer (SCT Inst, HKIPZ).
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57pub enum Instant {
58    /// Standard transfer (HKCCS).
59    No,
60    /// Instant when the bank offers it, else standard; decided before sending.
61    Prefer,
62    /// Instant or nothing.
63    Require,
64}
65
66/// Which field of a [`Transfer`] is invalid.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum TransferField {
70    From,
71    DebtorName,
72    PayeeName,
73    PayeeIban,
74    PayeeBic,
75    Amount,
76    Purpose,
77    EndToEndId,
78}
79
80impl fmt::Display for TransferField {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(match self {
83            Self::From => "from",
84            Self::DebtorName => "debtor_name",
85            Self::PayeeName => "payee_name",
86            Self::PayeeIban => "payee_iban",
87            Self::PayeeBic => "payee_bic",
88            Self::Amount => "amount",
89            Self::Purpose => "purpose",
90            Self::EndToEndId => "end_to_end_id",
91        })
92    }
93}
94
95/// Why a field of a [`Transfer`] is invalid.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97#[non_exhaustive]
98pub enum InvalidReason {
99    /// A text, reference, IBAN or BIC that breaks the SEPA rules.
100    Sepa(Invalid),
101    /// The amount is zero or negative.
102    NotPositive,
103    /// The amount exceeds 999 999 999.99.
104    TooLarge,
105    /// The amount has more than two decimals.
106    Precision,
107    /// The debtor account has no IBAN (addressed nationally only).
108    NoIban,
109    /// No debtor name given and none in the UPD.
110    NoName,
111}
112
113impl From<Invalid> for InvalidReason {
114    fn from(e: Invalid) -> Self {
115        Self::Sepa(e)
116    }
117}
118
119impl fmt::Display for InvalidReason {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Sepa(e) => e.fmt(f),
123            Self::NotPositive => f.write_str("must be greater than zero"),
124            Self::TooLarge => f.write_str("must not exceed 999999999.99"),
125            Self::Precision => f.write_str("at most two decimals"),
126            Self::NoIban => f.write_str("the account has no IBAN"),
127            Self::NoName => f.write_str("no account holder name known; give one"),
128        }
129    }
130}
131
132/// A [`Transfer`] that cannot be sent: the caller's data, nothing was sent.
133/// Becomes [`FinTSError::InvalidTransfer`](crate::FinTSError::InvalidTransfer).
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct InvalidTransfer {
136    pub field: TransferField,
137    pub reason: InvalidReason,
138}
139
140impl fmt::Display for InvalidTransfer {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write!(f, "{}: {}", self.field, self.reason)
143    }
144}
145
146impl std::error::Error for InvalidTransfer {}
147
148/// A [`Transfer`] that passed [`Transfer::check`]: what goes into the
149/// pain.001, normalised.
150#[derive(Debug, Clone)]
151pub struct CheckedTransfer {
152    from: Account,
153    debtor_name: String,
154    debtor_iban: Iban,
155    debtor_bic: Option<Bic>,
156    payee_name: String,
157    payee_iban: Iban,
158    payee_bic: Option<Bic>,
159    amount: Decimal,
160    purpose: String,
161    end_to_end_id: String,
162    instant: Instant,
163}
164
165impl CheckedTransfer {
166    pub fn from(&self) -> &Account {
167        &self.from
168    }
169    /// The given name, else the UPD holder name.
170    pub fn debtor_name(&self) -> &str {
171        &self.debtor_name
172    }
173    pub fn debtor_iban(&self) -> &Iban {
174        &self.debtor_iban
175    }
176    /// `None` when the account's BIC is not a BIC (sent as `NOTPROVIDED`).
177    pub fn debtor_bic(&self) -> Option<&Bic> {
178        self.debtor_bic.as_ref()
179    }
180    pub fn payee_name(&self) -> &str {
181        &self.payee_name
182    }
183    pub fn payee_iban(&self) -> &Iban {
184        &self.payee_iban
185    }
186    pub fn payee_bic(&self) -> Option<&Bic> {
187        self.payee_bic.as_ref()
188    }
189    pub fn amount(&self) -> Decimal {
190        self.amount
191    }
192    pub fn purpose(&self) -> &str {
193        &self.purpose
194    }
195    /// The caller's, or the one generated by the check (`FC` + UTC
196    /// timestamp + 8 random characters). Store it before sending: it matches
197    /// a later booking to the order.
198    pub fn end_to_end_id(&self) -> &str {
199        &self.end_to_end_id
200    }
201    pub fn instant(&self) -> Instant {
202        self.instant
203    }
204
205    /// The flat pain.001 input; `instant` sets `LclInstrm` `INST`.
206    pub(crate) fn pain_input(&self, instant: bool) -> Pain001Input<'_> {
207        Pain001Input {
208            debtor_name: &self.debtor_name,
209            debtor_iban: &self.debtor_iban,
210            debtor_bic: self.debtor_bic.as_ref(),
211            payee_name: &self.payee_name,
212            payee_iban: &self.payee_iban,
213            payee_bic: self.payee_bic.as_ref(),
214            amount: self.amount,
215            purpose: &self.purpose,
216            end_to_end_id: &self.end_to_end_id,
217            instant,
218        }
219    }
220}
221
222fn invalid(field: TransferField, reason: impl Into<InvalidReason>) -> InvalidTransfer {
223    InvalidTransfer {
224        field,
225        reason: reason.into(),
226    }
227}
228
229/// A name or text field: not blank (when `required`), at most `max`
230/// characters, SEPA text set (Anlage 3 2.1).
231fn check_text(value: &str, max: usize, required: bool) -> Result<(), Invalid> {
232    if value.trim().is_empty() {
233        return if required || !value.is_empty() {
234            Err(Invalid::Empty)
235        } else {
236            Ok(())
237        };
238    }
239    if value.chars().count() > max {
240        return Err(Invalid::TooLong { max });
241    }
242    if let Some(ch) = first_invalid_char(value) {
243        return Err(Invalid::Character { ch });
244    }
245    Ok(())
246}
247
248fn check_amount(amount: Decimal) -> Result<(), InvalidReason> {
249    if amount <= Decimal::ZERO {
250        return Err(InvalidReason::NotPositive);
251    }
252    if amount > max_amount() {
253        return Err(InvalidReason::TooLarge);
254    }
255    if amount.normalize().scale() > 2 {
256        return Err(InvalidReason::Precision);
257    }
258    Ok(())
259}
260
261impl Transfer {
262    /// Check every field before contact (payments-design section 2) and
263    /// resolve the debtor name: the given one, else `upd_holder` (the UPD
264    /// account holder; [`crate::jobs::transfer`] passes it). The first
265    /// broken field is the error.
266    pub fn check(&self, upd_holder: Option<&str>) -> Result<CheckedTransfer, InvalidTransfer> {
267        self.check_with(upd_holder, || {
268            generate_reference(jiff::Timestamp::now(), &mut rand::rng())
269        })
270    }
271
272    /// [`check`](Self::check) with the generator of the end-to-end ID given.
273    fn check_with(
274        &self,
275        upd_holder: Option<&str>,
276        generate_id: impl FnOnce() -> String,
277    ) -> Result<CheckedTransfer, InvalidTransfer> {
278        use TransferField as F;
279        let iban = self.from.iban();
280        if iban.is_empty() {
281            return Err(invalid(F::From, InvalidReason::NoIban));
282        }
283        let debtor_iban = Iban::parse(iban).map_err(|r| invalid(F::From, r))?;
284        let debtor_name = self
285            .debtor_name
286            .as_deref()
287            .or(upd_holder.filter(|h| !h.trim().is_empty()))
288            .ok_or(invalid(F::DebtorName, InvalidReason::NoName))?;
289        check_text(debtor_name, MAX_NAME, true).map_err(|r| invalid(F::DebtorName, r))?;
290        check_text(&self.payee_name, MAX_NAME, true).map_err(|r| invalid(F::PayeeName, r))?;
291        let payee_iban = Iban::parse(&self.payee_iban).map_err(|r| invalid(F::PayeeIban, r))?;
292        let payee_bic = match &self.payee_bic {
293            Some(bic) => Some(Bic::parse(bic).map_err(|r| invalid(F::PayeeBic, r))?),
294            None => None,
295        };
296        check_amount(self.amount).map_err(|r| invalid(F::Amount, r))?;
297        check_text(&self.purpose, MAX_PURPOSE, false).map_err(|r| invalid(F::Purpose, r))?;
298        if let Some(id) = &self.end_to_end_id {
299            check_reference(id).map_err(|r| invalid(F::EndToEndId, r))?;
300        }
301        Ok(CheckedTransfer {
302            from: self.from.clone(),
303            debtor_name: debtor_name.to_string(),
304            debtor_iban,
305            // The account's BIC when it is one; else NOTPROVIDED (5.4).
306            debtor_bic: Bic::parse(self.from.bic()).ok(),
307            payee_name: self.payee_name.clone(),
308            payee_iban,
309            payee_bic,
310            amount: self.amount,
311            purpose: self.purpose.clone(),
312            end_to_end_id: self.end_to_end_id.clone().unwrap_or_else(generate_id),
313            instant: self.instant,
314        })
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use std::str::FromStr;
322
323    fn base() -> Transfer {
324        Transfer {
325            from: Account::new("DE02120300000000202051", "BYLADEM1001").unwrap(),
326            debtor_name: Some("Erika Beispiel".into()),
327            payee_name: "Max Muster".into(),
328            payee_iban: "DE89 3704 0044 0532 0130 00".into(),
329            payee_bic: Some("COBADEFFXXX".into()),
330            amount: Decimal::from_str("1.00").unwrap(),
331            purpose: "Test".into(),
332            end_to_end_id: None,
333            instant: Instant::No,
334        }
335    }
336
337    #[test]
338    fn end_to_end_id_is_generated_unique_or_kept() {
339        let a = base().check(None).unwrap();
340        let b = base().check(None).unwrap();
341        assert_ne!(a.end_to_end_id(), b.end_to_end_id());
342        for id in [a.end_to_end_id(), b.end_to_end_id()] {
343            assert!(id.chars().count() <= 35);
344            assert!(crate::formats::sepa::is_sepa_reference(id), "{id}");
345            assert_ne!(id, "NOTPROVIDED");
346        }
347        let mut t = base();
348        t.end_to_end_id = Some("MINE-1".into());
349        assert_eq!(t.check(None).unwrap().end_to_end_id(), "MINE-1");
350        let fixed = base().check_with(None, || "FIXED-ID".to_string()).unwrap();
351        assert_eq!(fixed.end_to_end_id(), "FIXED-ID");
352    }
353
354    #[test]
355    fn valid_transfer() {
356        let c = base().check(None).unwrap();
357        assert_eq!(c.payee_iban().as_str(), "DE89370400440532013000");
358        assert!(crate::formats::sepa::is_sepa_reference(c.end_to_end_id()));
359        assert_eq!(c.debtor_bic().map(Bic::as_str), Some("BYLADEM1001"));
360        let mut t = base();
361        t.payee_bic = None;
362        t.purpose = String::new();
363        t.debtor_name = None;
364        t.amount = Decimal::from_str("999999999.99").unwrap();
365        t.end_to_end_id = Some("RE-2026/11".into());
366        t.payee_name = "Müller & Söhne".into();
367        t.payee_iban = "de89 3704 0044 0532 0130 00".into();
368        let c = t.check(Some("UPD Name")).unwrap();
369        assert_eq!(c.payee_iban().as_str(), "DE89370400440532013000");
370        assert_eq!(c.end_to_end_id(), "RE-2026/11");
371        assert_eq!(c.payee_bic(), None);
372        // Trailing zeros beyond two decimals are no precision.
373        t.amount = Decimal::from_str("1.500").unwrap();
374        t.check(Some("UPD Name")).unwrap();
375        // A debtor account whose BIC is no BIC goes IBAN-only.
376        t.from = Account::new("DE02120300000000202051", "-").unwrap();
377        assert_eq!(t.check(Some("UPD Name")).unwrap().debtor_bic(), None);
378    }
379
380    /// The validation table: one broken field each, nothing else.
381    #[test]
382    fn validation_table() {
383        use InvalidReason as R;
384        use TransferField as F;
385        fn d(s: &str) -> Decimal {
386            Decimal::from_str(s).unwrap()
387        }
388        let s = R::Sepa;
389        type Breaker = Box<dyn Fn(&mut Transfer)>;
390        let cases: Vec<(Breaker, F, R)> = vec![
391            (
392                Box::new(|t| {
393                    t.from =
394                        Account::national("1234", None, &crate::Blz::new("12030000"), "X").unwrap()
395                }),
396                F::From,
397                R::NoIban,
398            ),
399            (
400                Box::new(|t| t.from = Account::new("DE00120300000000202051", "B").unwrap()),
401                F::From,
402                s(Invalid::Checksum),
403            ),
404            (
405                Box::new(|t| t.debtor_name = Some(" ".into())),
406                F::DebtorName,
407                s(Invalid::Empty),
408            ),
409            (
410                Box::new(|t| t.payee_name = String::new()),
411                F::PayeeName,
412                s(Invalid::Empty),
413            ),
414            (
415                Box::new(|t| t.payee_name = "a".repeat(71)),
416                F::PayeeName,
417                s(Invalid::TooLong { max: 70 }),
418            ),
419            (
420                Box::new(|t| t.payee_name = "Café".into()),
421                F::PayeeName,
422                s(Invalid::Character { ch: 'é' }),
423            ),
424            (
425                Box::new(|t| t.payee_iban = "DE88370400440532013000".into()),
426                F::PayeeIban,
427                s(Invalid::Checksum),
428            ),
429            (
430                Box::new(|t| t.payee_bic = Some("COBADE".into())),
431                F::PayeeBic,
432                s(Invalid::Length),
433            ),
434            (Box::new(|t| t.amount = d("0")), F::Amount, R::NotPositive),
435            (Box::new(|t| t.amount = d("-1")), F::Amount, R::NotPositive),
436            (Box::new(|t| t.amount = d("0.001")), F::Amount, R::Precision),
437            (
438                Box::new(|t| t.amount = d("1000000000.00")),
439                F::Amount,
440                R::TooLarge,
441            ),
442            (
443                Box::new(|t| t.purpose = "x".repeat(141)),
444                F::Purpose,
445                s(Invalid::TooLong { max: 140 }),
446            ),
447            (
448                Box::new(|t| t.purpose = "   ".into()),
449                F::Purpose,
450                s(Invalid::Empty),
451            ),
452            (
453                Box::new(|t| t.purpose = "50 €".into()),
454                F::Purpose,
455                s(Invalid::Character { ch: '€' }),
456            ),
457            (
458                Box::new(|t| t.end_to_end_id = Some("A//B".into())),
459                F::EndToEndId,
460                s(Invalid::Slash),
461            ),
462            (
463                Box::new(|t| t.end_to_end_id = Some("Müller".into())),
464                F::EndToEndId,
465                s(Invalid::Character { ch: 'ü' }),
466            ),
467            (
468                Box::new(|t| t.end_to_end_id = Some(String::new())),
469                F::EndToEndId,
470                s(Invalid::Empty),
471            ),
472        ];
473        for (i, (break_it, field, reason)) in cases.into_iter().enumerate() {
474            let mut t = base();
475            break_it(&mut t);
476            assert_eq!(
477                t.check(Some("UPD Name")).unwrap_err(),
478                InvalidTransfer { field, reason },
479                "case {i}"
480            );
481        }
482    }
483
484    #[test]
485    fn debtor_name_resolution() {
486        let mut t = base();
487        let name = |t: &Transfer, h| t.check(h).map(|c| c.debtor_name().to_string());
488        assert_eq!(name(&t, Some("UPD Name")).unwrap(), "Erika Beispiel");
489        t.debtor_name = None;
490        assert_eq!(name(&t, Some("UPD Name")).unwrap(), "UPD Name");
491        assert_eq!(
492            name(&t, None).unwrap_err(),
493            InvalidTransfer {
494                field: TransferField::DebtorName,
495                reason: InvalidReason::NoName
496            }
497        );
498        assert_eq!(
499            name(&t, Some("  ")).unwrap_err().reason,
500            InvalidReason::NoName
501        );
502        assert_eq!(
503            name(&t, Some("Zoë")).unwrap_err().reason,
504            InvalidReason::Sepa(Invalid::Character { ch: 'ë' })
505        );
506    }
507
508    #[test]
509    fn error_category() {
510        let mut t = base();
511        t.amount = Decimal::ZERO;
512        let e: crate::FinTSError = t.check(None).unwrap_err().into();
513        assert_eq!(e.kind(), crate::Category::InvalidInput);
514        assert_eq!(
515            e.to_string(),
516            "invalid transfer: amount: must be greater than zero"
517        );
518    }
519}