Skip to main content

fints_client/
return_code.rs

1//! Return codes ("Rückmeldungen") of HIRMG and HIRMS, Formals 2017 B.7.
2//!
3//! A [`ReturnCode`] keeps everything the bank sent in one code line: the
4//! four-digit code, its text, the reference element, the parameters, and
5//! what it refers to ([`Scope`]: the whole message for HIRMG, one customer
6//! segment for HIRMS). Its [`Class`] and [`Kind`] are derived from the
7//! stored code and parameters, so a code this client does not know loses
8//! nothing. Code meanings: Rückmeldungscodes 2026-02-03 (RM), B.1–B.4.
9
10use std::fmt;
11
12use serde::{Deserialize, Serialize};
13
14use crate::types::{SecurityFunction, SegmentType, TouchdownPoint};
15
16/// A four-digit return code (`dig 4`, Formals B.7.5.1), kept verbatim.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
18#[serde(try_from = "String", into = "String")]
19pub struct Code([u8; 4]);
20
21impl Code {
22    /// The code, if `s` is exactly four ASCII digits.
23    pub fn new(s: &str) -> Option<Self> {
24        let bytes: [u8; 4] = s.as_bytes().try_into().ok()?;
25        bytes.iter().all(u8::is_ascii_digit).then_some(Self(bytes))
26    }
27
28    /// The four digits.
29    pub fn as_str(&self) -> &str {
30        // Four ASCII digits, checked in `new`.
31        std::str::from_utf8(&self.0).unwrap_or("????")
32    }
33
34    /// The class, from the first digit (Formals B.7.5.1).
35    pub fn class(self) -> Class {
36        match self.0[0] {
37            b'0' => Class::Success,
38            b'1' => Class::Note,
39            b'3' => Class::Warning,
40            b'9' => Class::Error,
41            _ => Class::Undefined,
42        }
43    }
44}
45
46impl fmt::Display for Code {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.write_str(self.as_str())
49    }
50}
51
52impl TryFrom<String> for Code {
53    type Error = String;
54    fn try_from(s: String) -> Result<Self, String> {
55        Self::new(&s).ok_or_else(|| format!("not a four-digit return code: {s:?}"))
56    }
57}
58
59impl From<Code> for String {
60    fn from(c: Code) -> String {
61        c.as_str().to_string()
62    }
63}
64
65/// The class of a return code: its first digit (Formals B.7.5.1, RM B.1).
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum Class {
68    /// 0xxx: success.
69    Success,
70    /// 1xxx: note (defined for FinTS 4 only).
71    Note,
72    /// 3xxx: warning; never fails an order.
73    Warning,
74    /// 9xxx: error; the message or order was rejected.
75    Error,
76    /// Any other first digit: not defined by the specification.
77    Undefined,
78}
79
80/// What a return code refers to.
81#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
82pub enum Scope {
83    /// HIRMG: the whole message (Formals B.7.2).
84    Message,
85    /// HIRMS: one segment of the customer message (Formals B.7.3).
86    Segment {
87        /// The customer segment's number, from the HIRMS header's
88        /// reference ("Bezugssegment"); 0 if the bank sent none.
89        number: u16,
90        /// The code of that segment (e.g. `HKSAL`), when the sent message
91        /// is known.
92        order: Option<SegmentType>,
93    },
94}
95
96/// The meaning of a return code this client knows, derived from the code
97/// and its parameters (RM). [`Kind::Other`] for every code not listed; its
98/// code, class, text and parameters stay on the [`ReturnCode`].
99#[derive(Debug, Clone, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum Kind {
102    /// 0010: message received.
103    MessageReceived,
104    /// 0020: order executed.
105    OrderExecuted,
106    /// 0030: order received, security clearance (TAN) required.
107    TanRequired,
108    /// 0100: dialog ended.
109    DialogEnded,
110    /// 0900: TAN valid.
111    TanValid,
112    /// 0025: payee check without name deviation (VoP).
113    NoNameDeviation,
114    /// 3020: the BIC given is outdated; P1, if present, is the new one.
115    BicOutdated { new_bic: Option<String> },
116    /// 3045: instant payment status unknown yet; ask with HKIPS.
117    InstantStatusQuery,
118    /// 3046: check the account's transactions (outcome to be verified).
119    CheckTransactions,
120    /// 3070: order accepted for processing; P1, if present, is the bank's
121    /// reference.
122    ProcessingReference { reference: Option<String> },
123    /// 3010: not available. RM's examples: no new entries, information
124    /// not offered at the moment, data already up to date. After a data
125    /// request banks send it for "no entries".
126    NotAvailable,
127    /// 3040: more data available; P1 is the touchdown point.
128    Touchdown(TouchdownPoint),
129    /// 3060: some warnings in the message.
130    PartialWarnings,
131    /// 3072: new access data (RM C.6); P1 user ID, P2 customer ID (the
132    /// user ID when absent).
133    UserDataChanged {
134        user_id: Option<String>,
135        customer_id: Option<String>,
136    },
137    /// 3076: no strong customer authentication required.
138    ScaExemption,
139    /// 3090: check the payee check result (a deviation or a note).
140    VopCheckResult,
141    /// 3091: Verification of Payee not required.
142    VopNotRequired,
143    /// 3092: the bank will require Verification of Payee from P1 on.
144    VopRequiredFrom { date: Option<String> },
145    /// 3093: payee check still in progress (poll with HKVPP).
146    VopInProgress,
147    /// 3094: payee check complete.
148    VopComplete,
149    /// 3095: payee check without result.
150    VopNoResult,
151    /// 3270: the instant payment is processed as a standard SEPA transfer
152    /// (Messages C.10.2.9.1.2, HKIPZ 2 with the conversion flag).
153    ConvertedToStandard,
154    /// 3920: allowed security functions, P1..n.
155    AllowedSecurityFunctions(Vec<SecurityFunction>),
156    /// 3945: Verification of Payee approval not possible.
157    VopApprovalNotPossible,
158    /// 3955: security clearance via a separate channel (decoupled)
159    /// initiated.
160    DecoupledInitiated,
161    /// 3956: strong customer authentication (decoupled) still pending.
162    DecoupledPending,
163    /// 3957: wait for the push message (decoupled). A notice for the user;
164    /// as the answer to a status request without 0020 it means the same as
165    /// 3956: still pending.
166    DecoupledAwaitPush,
167    /// 3958: the approval app does not support the chosen procedure.
168    DecoupledMethodUnsupported,
169    /// 9000: status indifferent: it is unclear whether the message or
170    /// order was processed (RM B.4, C.7). P1 names the order (segment
171    /// code) to run to find out, e.g. `HKCAZ`. Never resubmit blindly.
172    OutcomeUnknown { query: Option<SegmentType> },
173    /// 9010: processing not possible.
174    GeneralError,
175    /// 9040: authentication of the submitter missing or faulty, order
176    /// rejected. RM also lists 9040 for a decompression error, which this
177    /// client cannot cause (it sends no compressed messages).
178    AuthenticationFailed,
179    /// 9050: message partially faulty.
180    PartialErrors,
181    /// 9075: dialog aborted, strong customer authentication required.
182    ScaRequired,
183    /// 9076: name check (Verification of Payee) required; the bank no
184    /// longer accepts payments without HKVPP/HKVPA or HKVOO.
185    VopRequired,
186    /// 9078: dialog aborted, the FinTS product is not registered.
187    ProductNotRegistered,
188    /// 9110: unknown structure.
189    UnknownStructure,
190    /// 9150: element not allowed in this order (e.g. an execution date
191    /// other than 1999-01-01 in a FinTS single order).
192    ElementNotAllowed,
193    /// 9230: insufficient funds.
194    InsufficientFunds,
195    /// 9390: duplicate submission; the order is not executed again.
196    DuplicateSubmission,
197    /// 9120: not expected.
198    NotExpected,
199    /// 9160: data element missing.
200    DataElementMissing,
201    /// 9180: no longer accepted (order version outdated).
202    NoLongerAccepted,
203    /// 9185: HBCI/FinTS version not supported.
204    ProtocolVersionUnsupported,
205    /// 9250: name check (Verification of Payee) not possible; submit again
206    /// later or with opt-out (HKVOO).
207    VopUnavailable,
208    /// 9255: real-time (instant payment) limit exceeded. P1, if present,
209    /// is a link where the user can change the limit.
210    InstantLimitExceeded { link: Option<String> },
211    /// 9311: PIN/TAN system not available.
212    PinTanUnavailable,
213    /// 9361: dialog aborted, the security procedure is no longer allowed.
214    SecurityProcedureNotAllowed,
215    /// 9370: signature authorisation not sufficient.
216    SignatureInsufficient,
217    /// 9380: user not authorised (for the order, or for the chosen TAN
218    /// procedure).
219    NotAuthorised,
220    /// 9340: signature not accepted (RM: "electronic signature wrong",
221    /// "signature faulty", "security profile unknown"). The PIN may be
222    /// wrong, or user ID, BLZ or security profile do not match; banks send
223    /// it next to a more specific code, which then names the cause.
224    SignatureInvalid,
225    /// 9942, 9910: PIN wrong. 9942 also means, in a PIN change, "new PIN
226    /// invalid / too short / too long"; RM lists 9910 also as "PIN
227    /// locked", "TAN list locked", "chip card locked".
228    PinWrong,
229    /// 9391: fetch a new customer system ID.
230    SystemIdInvalid,
231    /// 9800: dialog aborted by the bank.
232    DialogAborted,
233    /// 9930, 9931: PIN or access locked.
234    AccountLocked,
235    /// 9360 (RM): the TAN list (or signature) is locked after
236    /// `attempts_left` further failed attempts (P1). Without P1 it is the
237    /// RM text "key locked": the lock happened.
238    LockAfterAttempts { attempts_left: Option<u32> },
239    /// 9941: TAN (or signature) invalid.
240    TanInvalid,
241    /// 9943: TAN already used.
242    TanUsed,
243    /// 9951: timeout in the two-step procedure, TAN invalid.
244    TanExpired,
245    /// 9959: the SMS could not be sent; repeat.
246    SmsNotSent,
247    /// Any other code.
248    Other,
249}
250
251impl Kind {
252    /// The kind of `code` with these parameters. Empty parameters are
253    /// skipped.
254    pub fn of(code: Code, parameters: &[String]) -> Self {
255        let params: Vec<&String> = parameters.iter().filter(|p| !p.is_empty()).collect();
256        match code.as_str() {
257            "0010" => Self::MessageReceived,
258            "0020" => Self::OrderExecuted,
259            "0030" => Self::TanRequired,
260            "0100" => Self::DialogEnded,
261            "0900" => Self::TanValid,
262            "0025" => Self::NoNameDeviation,
263            "3020" => Self::BicOutdated {
264                new_bic: params.first().map(|s| s.to_string()),
265            },
266            "3045" => Self::InstantStatusQuery,
267            "3046" => Self::CheckTransactions,
268            "3070" => Self::ProcessingReference {
269                reference: params.first().map(|s| s.to_string()),
270            },
271            "3090" => Self::VopCheckResult,
272            "3092" => Self::VopRequiredFrom {
273                date: params.first().map(|s| s.to_string()),
274            },
275            "3093" => Self::VopInProgress,
276            "3094" => Self::VopComplete,
277            "3095" => Self::VopNoResult,
278            "3270" => Self::ConvertedToStandard,
279            "9150" => Self::ElementNotAllowed,
280            "9230" => Self::InsufficientFunds,
281            "9390" => Self::DuplicateSubmission,
282            "3010" => Self::NotAvailable,
283            "3040" => Self::Touchdown(TouchdownPoint::new(
284                params.first().map(|s| s.as_str()).unwrap_or(""),
285            )),
286            "3060" => Self::PartialWarnings,
287            "3072" => Self::UserDataChanged {
288                user_id: params.first().map(|s| s.to_string()),
289                customer_id: params.get(1).or(params.first()).map(|s| s.to_string()),
290            },
291            "3076" => Self::ScaExemption,
292            "3091" => Self::VopNotRequired,
293            "3920" => Self::AllowedSecurityFunctions(
294                params.into_iter().map(SecurityFunction::new).collect(),
295            ),
296            "3945" => Self::VopApprovalNotPossible,
297            "3955" => Self::DecoupledInitiated,
298            "3956" => Self::DecoupledPending,
299            "3957" => Self::DecoupledAwaitPush,
300            "3958" => Self::DecoupledMethodUnsupported,
301            "9000" => Self::OutcomeUnknown {
302                query: params.first().map(|s| SegmentType::new(s.as_str())),
303            },
304            "9010" => Self::GeneralError,
305            "9040" => Self::AuthenticationFailed,
306            "9050" => Self::PartialErrors,
307            "9075" => Self::ScaRequired,
308            "9076" => Self::VopRequired,
309            "9078" => Self::ProductNotRegistered,
310            "9110" => Self::UnknownStructure,
311            "9120" => Self::NotExpected,
312            "9160" => Self::DataElementMissing,
313            "9180" => Self::NoLongerAccepted,
314            "9185" => Self::ProtocolVersionUnsupported,
315            "9250" => Self::VopUnavailable,
316            "9255" => Self::InstantLimitExceeded {
317                link: params.first().map(|s| s.to_string()),
318            },
319            "9311" => Self::PinTanUnavailable,
320            "9360" => Self::LockAfterAttempts {
321                attempts_left: params.first().and_then(|p| p.trim().parse().ok()),
322            },
323            "9361" => Self::SecurityProcedureNotAllowed,
324            "9370" => Self::SignatureInsufficient,
325            "9380" => Self::NotAuthorised,
326            "9340" => Self::SignatureInvalid,
327            "9910" | "9942" => Self::PinWrong,
328            "9391" => Self::SystemIdInvalid,
329            "9800" => Self::DialogAborted,
330            "9930" | "9931" => Self::AccountLocked,
331            "9941" => Self::TanInvalid,
332            "9943" => Self::TanUsed,
333            "9951" => Self::TanExpired,
334            "9959" => Self::SmsNotSent,
335            _ => Self::Other,
336        }
337    }
338}
339
340/// What a caller can do about an error: one category per different
341/// reaction (docs/return-codes-design.md section 2). Every
342/// [`FinTSError`](crate::FinTSError) has one
343/// ([`FinTSError::kind`](crate::FinTSError::kind)); a bank error's comes
344/// from its selected [`ReturnCode`].
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
346#[serde(rename_all = "snake_case")]
347#[non_exhaustive]
348pub enum Category {
349    /// 9942, 9910, 9930, 9931, 9340: the PIN is wrong, the access is
350    /// locked, or the bank did not accept the signature. Ask the user;
351    /// never retry on your own (a few wrong PINs in a row lock the login).
352    Credentials(Credentials),
353    /// 9391: the bank rejected the customer system ID; the client
354    /// resynchronises once.
355    SystemId,
356    /// 9075: strong customer authentication required. The client retries
357    /// with HKTAN; this reaches the caller only if that is impossible.
358    ScaRequired,
359    /// 9941, 9943, 9951, and a TAN the user did not give or confirm in
360    /// time: get a new TAN from the user.
361    Tan,
362    /// 9800: the bank ended the dialog; open a new one.
363    DialogEnded,
364    /// 9076, 9078, 9180, 9185, 9361, and a version mismatch found before
365    /// sending: update the client or use another order or procedure.
366    Unsupported,
367    /// 9040: the bank refused the submitter's authentication. Banks also
368    /// send it when the TAN method is locked after too many challenges.
369    /// Show the bank's text; do not open another dialog on your own (each
370    /// login asks for a new challenge and can extend the lock). Retry later,
371    /// when the user asks.
372    AuthenticationRefused,
373    /// 9370, 9380: the user may not run this order or use this account.
374    NotPermitted,
375    /// 9000: unclear whether the bank processed the order (RM C.7). Never
376    /// resubmit; check the outcome another way ([`Kind::OutcomeUnknown`]
377    /// names the order to ask with).
378    OutcomeUnknown,
379    /// 9250, 9311, 9959, transport errors, timeouts, HTTP 5xx/408/429: retry
380    /// later unchanged.
381    Temporary,
382    /// 9110, 9120, 9130-9170, unreadable answers, and requests this client
383    /// cannot build or was called wrongly for: a bug in this client or in
384    /// its use; report it.
385    ClientFault,
386    /// The caller's data cannot be sent (an invalid transfer: SEPA
387    /// charset, length, IBAN, BIC, amount). Found before contact; nothing
388    /// was sent. Fix the data and retry.
389    InvalidInput,
390    /// Every other bank error (9010, 9050, 9210, ...): show code and text.
391    Rejected,
392}
393
394/// Which credentials problem ([`Category::Credentials`]).
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
396#[serde(rename_all = "snake_case")]
397pub enum Credentials {
398    /// 9942: PIN wrong.
399    PinWrong,
400    /// 9340: signature not accepted. The PIN may be wrong, or user ID, BLZ
401    /// or security profile do not match; check them all.
402    SignatureInvalid,
403    /// 9930, 9931: PIN or access locked.
404    Locked,
405    /// 9910: RM lists it both as "PIN wrong" and as "PIN locked" / "TAN
406    /// list locked"; the bank text tells the user which.
407    Unclear,
408}
409
410impl Category {
411    /// The category of a class 9 code; `None` for every other class.
412    pub fn of(code: Code, kind: &Kind) -> Option<Self> {
413        if code.class() != Class::Error {
414            return None;
415        }
416        Some(match kind {
417            Kind::PinWrong if code.as_str() == "9910" => Self::Credentials(Credentials::Unclear),
418            Kind::PinWrong => Self::Credentials(Credentials::PinWrong),
419            Kind::SignatureInvalid => Self::Credentials(Credentials::SignatureInvalid),
420            Kind::AccountLocked
421            | Kind::LockAfterAttempts {
422                attempts_left: None,
423            } => Self::Credentials(Credentials::Locked),
424            Kind::LockAfterAttempts { .. } => Self::Tan,
425            Kind::SystemIdInvalid => Self::SystemId,
426            Kind::ScaRequired => Self::ScaRequired,
427            Kind::TanInvalid | Kind::TanUsed | Kind::TanExpired => Self::Tan,
428            Kind::DialogAborted => Self::DialogEnded,
429            Kind::VopRequired
430            | Kind::ProductNotRegistered
431            | Kind::NoLongerAccepted
432            | Kind::ProtocolVersionUnsupported
433            | Kind::SecurityProcedureNotAllowed => Self::Unsupported,
434            Kind::AuthenticationFailed => Self::AuthenticationRefused,
435            Kind::SignatureInsufficient | Kind::NotAuthorised => Self::NotPermitted,
436            Kind::OutcomeUnknown { .. } => Self::OutcomeUnknown,
437            Kind::VopUnavailable | Kind::PinTanUnavailable | Kind::SmsNotSent => Self::Temporary,
438            Kind::UnknownStructure | Kind::NotExpected => Self::ClientFault,
439            // 9130-9170: syntax, length, occupancy, missing, too often.
440            _ if ("9130".."9171").contains(&code.as_str()) => Self::ClientFault,
441            _ => Self::Rejected,
442        })
443    }
444}
445
446/// One code line of HIRMG or HIRMS ("Rückmeldung"), with everything the
447/// bank sent in it.
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
449pub struct ReturnCode {
450    /// The four-digit code.
451    pub code: Code,
452    /// The bank's text, to be shown with the code (Formals B.7.5.1).
453    pub text: String,
454    /// The message (HIRMG) or the customer segment (HIRMS) it refers to.
455    pub scope: Scope,
456    /// "Bezugsdatenelement": the position of the data element the code
457    /// refers to, if the bank named one (HIRMS only).
458    pub reference_element: Option<String>,
459    /// "Rückmeldungsparameter", verbatim and in order (up to 10). An empty
460    /// parameter on the wire is an absent repetition and does not appear.
461    pub parameters: Vec<String>,
462}
463
464impl ReturnCode {
465    /// A code line without reference element and parameters.
466    pub fn new(code: Code, text: impl Into<String>, scope: Scope) -> Self {
467        Self {
468            code,
469            text: text.into(),
470            scope,
471            reference_element: None,
472            parameters: Vec::new(),
473        }
474    }
475
476    /// The same code line with these parameters.
477    pub fn with_parameters(mut self, parameters: Vec<String>) -> Self {
478        self.parameters = parameters;
479        self
480    }
481
482    /// The same code line with this reference element.
483    pub fn with_reference_element(mut self, element: impl Into<String>) -> Self {
484        self.reference_element = Some(element.into());
485        self
486    }
487
488    /// The class, from the first digit.
489    pub fn class(&self) -> Class {
490        self.code.class()
491    }
492
493    /// The typed meaning, derived from code and parameters.
494    pub fn kind(&self) -> Kind {
495        Kind::of(self.code, &self.parameters)
496    }
497
498    /// The error category of a class 9 code; `None` for other classes.
499    pub fn category(&self) -> Option<Category> {
500        Category::of(self.code, &self.kind())
501    }
502
503    /// True for a class 9 code.
504    pub fn is_error(&self) -> bool {
505        self.class() == Class::Error
506    }
507}
508
509impl fmt::Display for ReturnCode {
510    /// `9210: Keine gueltige Kontoverbindung`
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        write!(f, "{}: {}", self.code, self.text)
513    }
514}
515
516/// A message for the caller: a bank code that is neither success, error
517/// nor consumed by the protocol (Formals B.7.5.1: show every bank message),
518/// or a warning the client itself raised about an answer.
519/// Examples of bank codes: 3050 (order version outdated), 3060, 3072,
520/// 3075, 3010, 3957, 3958.
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[non_exhaustive]
523pub enum Notice {
524    /// A code line the bank sent.
525    Bank {
526        /// The dialog whose answer carried the code. The sync dialog and
527        /// the job's dialog may both carry 3060 or 3072, and each notice
528        /// says which one it came from. Within one dialog, an order's
529        /// rounds (check, execution, status requests) give an identical
530        /// notice once.
531        dialog: NoticeDialog,
532        /// The code line as the bank sent it. Its `scope` says whether it
533        /// answers the message (HIRMG) or a segment (HIRMS, with the
534        /// segment code of the order it answers, e.g. `HKSAL`).
535        code: ReturnCode,
536    },
537    /// A warning the client generated; the bank sent no code for it.
538    Client {
539        /// The dialog whose answer raised it.
540        dialog: NoticeDialog,
541        /// What the client noticed.
542        warning: ClientWarning,
543    },
544}
545
546/// What the client noticed about an answer without the bank saying so.
547/// Never an error: the answer is used as decoded.
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
549#[non_exhaustive]
550#[serde(rename_all = "snake_case")]
551pub enum ClientWarning {
552    /// The free text of the answer (HIRMG/HIRMS) contains UTF-8 byte
553    /// sequences although the answer is ISO 8859-1 (Formals B.1): umlauts
554    /// read as `ä`, `ü`, `ö`, `ß`, the euro sign as `€`. The text is
555    /// shown as decoded. Found by a heuristic, once per answer.
556    Utf8TextInLatin1,
557    /// The requested statement range began before the bank's storage
558    /// period (Speicherzeitraum of HIKAZS/HICAZS), so the request was sent
559    /// from `used` instead of `requested`. Entries before `used` are not
560    /// available from the bank.
561    RangeClamped {
562        requested: jiff::civil::Date,
563        used: jiff::civil::Date,
564    },
565}
566
567/// Which dialog of an operation a [`Notice`] came from.
568#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
569#[serde(rename_all = "snake_case")]
570pub enum NoticeDialog {
571    /// The synchronisation dialog that fetches parameters and system ID.
572    Sync,
573    /// The dialog the job (or the login) itself runs in.
574    Job,
575}
576
577impl Notice {
578    /// The notice for this bank code line, from this dialog.
579    pub fn new(dialog: NoticeDialog, code: ReturnCode) -> Self {
580        Self::Bank { dialog, code }
581    }
582
583    /// The notice for a client-side warning, from this dialog.
584    pub fn client(dialog: NoticeDialog, warning: ClientWarning) -> Self {
585        Self::Client { dialog, warning }
586    }
587
588    /// The dialog the notice came from.
589    pub fn dialog(&self) -> NoticeDialog {
590        match self {
591            Self::Bank { dialog, .. } | Self::Client { dialog, .. } => *dialog,
592        }
593    }
594
595    /// The bank's code line; `None` for a client warning.
596    pub fn code(&self) -> Option<&ReturnCode> {
597        match self {
598            Self::Bank { code, .. } => Some(code),
599            Self::Client { .. } => None,
600        }
601    }
602
603    /// The typed meaning of the bank's code; `None` for a client warning.
604    pub fn kind(&self) -> Option<Kind> {
605        self.code().map(ReturnCode::kind)
606    }
607
608    /// The client warning; `None` for a bank code.
609    pub fn client_warning(&self) -> Option<ClientWarning> {
610        match self {
611            Self::Client { warning, .. } => Some(*warning),
612            Self::Bank { .. } => None,
613        }
614    }
615
616    /// True for codes the protocol acts on itself; they are not notices.
617    /// 3090, 3093 and 3094 only in an answer to HKVPP or HKVPA (payments
618    /// design section 4); elsewhere they stay notices.
619    pub(crate) fn is_consumed(code: &ReturnCode) -> bool {
620        let payee_check = matches!(
621            &code.scope,
622            Scope::Segment { order: Some(o), .. } if matches!(o.as_str(), "HKVPP" | "HKVPA")
623        );
624        match code.kind() {
625            Kind::TanRequired
626            | Kind::Touchdown(_)
627            | Kind::ScaExemption
628            | Kind::AllowedSecurityFunctions(_)
629            | Kind::DecoupledInitiated
630            | Kind::DecoupledPending
631            | Kind::VopNotRequired
632            | Kind::VopApprovalNotPossible
633            | Kind::InstantStatusQuery => true,
634            Kind::VopCheckResult | Kind::VopInProgress | Kind::VopComplete => payee_check,
635            _ => false,
636        }
637    }
638}
639
640impl fmt::Display for NoticeDialog {
641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642        f.write_str(match self {
643            Self::Sync => "sync",
644            Self::Job => "job",
645        })
646    }
647}
648
649impl fmt::Display for ClientWarning {
650    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
651        match self {
652            Self::Utf8TextInLatin1 => f.write_str(
653                "bank text looks like UTF-8 in an ISO 8859-1 answer (umlauts garbled); shown as decoded",
654            ),
655            Self::RangeClamped { requested, used } => write!(
656                f,
657                "statement range starts {requested}, before the bank's storage period; requested from {used}"
658            ),
659        }
660    }
661}
662
663impl fmt::Display for Notice {
664    /// `3060 [sync, HIRMG]: text`, or `3072 [job, HKTAN]: text` for a code
665    /// that answers the order `HKTAN` (`HIRMS #3` if its segment is not
666    /// known). A client warning reads `client [job]: text`.
667    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668        let (dialog, code) = match self {
669            Self::Bank { dialog, code } => (dialog, code),
670            Self::Client { dialog, warning } => {
671                return write!(f, "client [{dialog}]: {warning}");
672            }
673        };
674        write!(f, "{} [{}, ", code.code, dialog)?;
675        match &code.scope {
676            Scope::Message => f.write_str("HIRMG")?,
677            Scope::Segment {
678                order: Some(order), ..
679            } => write!(f, "{order}")?,
680            Scope::Segment { number, .. } => write!(f, "HIRMS #{number}")?,
681        }
682        write!(f, "]: {}", code.text)
683    }
684}
685
686/// True if `text` (one `char` per ISO 8859-1 byte) holds a complete,
687/// valid UTF-8 multi-byte sequence read as Latin-1: a lead byte (0xC2-0xF4)
688/// followed by the right number of continuation bytes (0x80-0xBF). Real
689/// German text does not match: `Ã`, `â` and the other lead characters are
690/// not followed by a control or symbol character there.
691pub(crate) fn looks_like_utf8_as_latin1(text: &str) -> bool {
692    let bytes: Vec<u8> = match text.chars().map(u8::try_from).collect() {
693        Ok(b) => b,
694        Err(_) => return false,
695    };
696    let mut i = 0;
697    while i < bytes.len() {
698        let len = match bytes[i] {
699            0xC2..=0xDF => 2,
700            0xE0..=0xEF => 3,
701            0xF0..=0xF4 => 4,
702            _ => 1,
703        };
704        if len > 1
705            && bytes
706                .get(i..i + len)
707                .is_some_and(|s| std::str::from_utf8(s).is_ok())
708        {
709            return true;
710        }
711        i += 1;
712    }
713    false
714}
715
716#[cfg(test)]
717mod mojibake_tests {
718    use super::looks_like_utf8_as_latin1 as detect;
719
720    fn latin1(utf8: &str) -> String {
721        utf8.bytes().map(char::from).collect()
722    }
723
724    #[test]
725    fn utf8_read_as_latin1_is_found() {
726        for s in ["Zahlung für Müller", "Straße", "Betrag in €", "schön"] {
727            assert!(detect(&latin1(s)), "{s}");
728        }
729    }
730
731    #[test]
732    fn real_latin1_umlauts_are_not_found() {
733        for s in [
734            "Zahlung für Müller, Größe, Äpfel, schön, Straße",
735            "ÄÖÜ äöü ß ÂÃ ÄÅ",
736            "Überweisung ausgeführt",
737            "plain ascii",
738            "",
739        ] {
740            assert!(!detect(s), "{s}");
741        }
742    }
743}
744
745#[cfg(test)]
746mod tests {
747    use super::*;
748
749    fn kind(code: &str, params: &[&str]) -> (Class, Kind) {
750        let params: Vec<String> = params.iter().map(|s| s.to_string()).collect();
751        let c = ReturnCode::new(Code::new(code).unwrap(), "t", Scope::Message)
752            .with_parameters(params.clone());
753        assert_eq!(c.parameters, params, "{code}: parameters kept verbatim");
754        (c.class(), c.kind())
755    }
756
757    /// Every code of the inventory (docs/return-codes-design.md section 1)
758    /// with its class and kind (RM B.1-B.4).
759    #[test]
760    fn inventory() {
761        use Class::*;
762        let sf = |s: &str| SecurityFunction::new(s);
763        let cases: Vec<(&str, &[&str], Class, Kind)> = vec![
764            ("0010", &[], Success, Kind::MessageReceived),
765            ("0020", &[], Success, Kind::OrderExecuted),
766            ("0030", &[], Success, Kind::TanRequired),
767            ("0100", &[], Success, Kind::DialogEnded),
768            ("0900", &[], Success, Kind::TanValid),
769            ("0999", &[], Success, Kind::Other),
770            ("0025", &[], Success, Kind::NoNameDeviation),
771            (
772                "3020",
773                &["NEWBDEFFXXX"],
774                Warning,
775                Kind::BicOutdated {
776                    new_bic: Some("NEWBDEFFXXX".into()),
777                },
778            ),
779            ("3045", &[], Warning, Kind::InstantStatusQuery),
780            ("3046", &[], Warning, Kind::CheckTransactions),
781            (
782                "3070",
783                &["REF-1"],
784                Warning,
785                Kind::ProcessingReference {
786                    reference: Some("REF-1".into()),
787                },
788            ),
789            ("3090", &[], Warning, Kind::VopCheckResult),
790            (
791                "3092",
792                &["2026-10-09"],
793                Warning,
794                Kind::VopRequiredFrom {
795                    date: Some("2026-10-09".into()),
796                },
797            ),
798            ("3093", &[], Warning, Kind::VopInProgress),
799            ("3094", &[], Warning, Kind::VopComplete),
800            ("3095", &[], Warning, Kind::VopNoResult),
801            ("3270", &[], Warning, Kind::ConvertedToStandard),
802            ("9150", &[], Error, Kind::ElementNotAllowed),
803            ("9230", &[], Error, Kind::InsufficientFunds),
804            ("9390", &[], Error, Kind::DuplicateSubmission),
805            ("3010", &[], Warning, Kind::NotAvailable),
806            (
807                "3040",
808                &["TD1"],
809                Warning,
810                Kind::Touchdown(TouchdownPoint::new("TD1")),
811            ),
812            ("3060", &[], Warning, Kind::PartialWarnings),
813            (
814                "3072",
815                &["new-user", "new-customer"],
816                Warning,
817                Kind::UserDataChanged {
818                    user_id: Some("new-user".into()),
819                    customer_id: Some("new-customer".into()),
820                },
821            ),
822            (
823                "3072",
824                &["new-user"],
825                Warning,
826                Kind::UserDataChanged {
827                    user_id: Some("new-user".into()),
828                    customer_id: Some("new-user".into()),
829                },
830            ),
831            (
832                "3072",
833                &[],
834                Warning,
835                Kind::UserDataChanged {
836                    user_id: None,
837                    customer_id: None,
838                },
839            ),
840            ("3076", &[], Warning, Kind::ScaExemption),
841            ("3091", &[], Warning, Kind::VopNotRequired),
842            (
843                "3920",
844                &["912", "913", "940"],
845                Warning,
846                Kind::AllowedSecurityFunctions(vec![sf("912"), sf("913"), sf("940")]),
847            ),
848            ("3945", &[], Warning, Kind::VopApprovalNotPossible),
849            ("3955", &[], Warning, Kind::DecoupledInitiated),
850            ("3956", &[], Warning, Kind::DecoupledPending),
851            ("3957", &[], Warning, Kind::DecoupledAwaitPush),
852            ("3958", &[], Warning, Kind::DecoupledMethodUnsupported),
853            ("3999", &["P"], Warning, Kind::Other),
854            (
855                "9000",
856                &["HKCAZ"],
857                Error,
858                Kind::OutcomeUnknown {
859                    query: Some(SegmentType::new("HKCAZ")),
860                },
861            ),
862            ("9000", &[], Error, Kind::OutcomeUnknown { query: None }),
863            ("9010", &[], Error, Kind::GeneralError),
864            ("9040", &[], Error, Kind::AuthenticationFailed),
865            ("9050", &[], Error, Kind::PartialErrors),
866            ("9075", &[], Error, Kind::ScaRequired),
867            ("9076", &[], Error, Kind::VopRequired),
868            ("9078", &[], Error, Kind::ProductNotRegistered),
869            ("9110", &[], Error, Kind::UnknownStructure),
870            ("9120", &[], Error, Kind::NotExpected),
871            ("9160", &[], Error, Kind::DataElementMissing),
872            ("9180", &[], Error, Kind::NoLongerAccepted),
873            ("9185", &[], Error, Kind::ProtocolVersionUnsupported),
874            ("9250", &[], Error, Kind::VopUnavailable),
875            (
876                "9255",
877                &["https://bank.example/limit"],
878                Error,
879                Kind::InstantLimitExceeded {
880                    link: Some("https://bank.example/limit".into()),
881                },
882            ),
883            (
884                "9255",
885                &[],
886                Error,
887                Kind::InstantLimitExceeded { link: None },
888            ),
889            ("9311", &[], Error, Kind::PinTanUnavailable),
890            (
891                "9360",
892                &["2"],
893                Error,
894                Kind::LockAfterAttempts {
895                    attempts_left: Some(2),
896                },
897            ),
898            (
899                "9360",
900                &[],
901                Error,
902                Kind::LockAfterAttempts {
903                    attempts_left: None,
904                },
905            ),
906            ("9361", &[], Error, Kind::SecurityProcedureNotAllowed),
907            ("9370", &[], Error, Kind::SignatureInsufficient),
908            ("9380", &[], Error, Kind::NotAuthorised),
909            ("9340", &[], Error, Kind::SignatureInvalid),
910            ("9910", &[], Error, Kind::PinWrong),
911            ("9942", &[], Error, Kind::PinWrong),
912            ("9391", &[], Error, Kind::SystemIdInvalid),
913            ("9800", &[], Error, Kind::DialogAborted),
914            ("9930", &[], Error, Kind::AccountLocked),
915            ("9931", &[], Error, Kind::AccountLocked),
916            ("9941", &[], Error, Kind::TanInvalid),
917            ("9943", &[], Error, Kind::TanUsed),
918            ("9951", &[], Error, Kind::TanExpired),
919            ("9959", &[], Error, Kind::SmsNotSent),
920            // Seen at banks, no own kind.
921            ("9210", &[], Error, Kind::Other),
922            ("9999", &["A", "B"], Error, Kind::Other),
923            // FinTS 4 notes and undefined first digits keep code and class.
924            ("1234", &[], Note, Kind::Other),
925            ("5000", &[], Undefined, Kind::Other),
926        ];
927        for (code, params, class, want) in cases {
928            assert_eq!(kind(code, params), (class, want), "{code} {params:?}");
929        }
930    }
931
932    /// The category table (docs/return-codes-design.md section 2).
933    #[test]
934    fn categories() {
935        use Category::*;
936        let cases: &[(&str, Option<Category>)] = &[
937            ("0020", None),
938            ("3040", None),
939            ("3999", None),
940            ("1234", None),
941            ("5000", None),
942            (
943                "9340",
944                Some(Credentials(super::Credentials::SignatureInvalid)),
945            ),
946            ("9942", Some(Credentials(super::Credentials::PinWrong))),
947            ("9930", Some(Credentials(super::Credentials::Locked))),
948            ("9931", Some(Credentials(super::Credentials::Locked))),
949            ("9910", Some(Credentials(super::Credentials::Unclear))),
950            ("9391", Some(SystemId)),
951            ("9075", Some(ScaRequired)),
952            ("9941", Some(Tan)),
953            ("9943", Some(Tan)),
954            ("9951", Some(Tan)),
955            ("9800", Some(DialogEnded)),
956            ("9076", Some(Unsupported)),
957            ("9078", Some(Unsupported)),
958            ("9180", Some(Unsupported)),
959            ("9185", Some(Unsupported)),
960            ("9360", Some(Credentials(super::Credentials::Locked))),
961            ("9361", Some(Unsupported)),
962            ("9370", Some(NotPermitted)),
963            ("9380", Some(NotPermitted)),
964            ("9000", Some(OutcomeUnknown)),
965            ("9250", Some(Temporary)),
966            ("9311", Some(Temporary)),
967            ("9959", Some(Temporary)),
968            ("9110", Some(ClientFault)),
969            ("9120", Some(ClientFault)),
970            ("9130", Some(ClientFault)),
971            ("9140", Some(ClientFault)),
972            ("9145", Some(ClientFault)),
973            ("9150", Some(ClientFault)),
974            ("9160", Some(ClientFault)),
975            ("9170", Some(ClientFault)),
976            ("9010", Some(Rejected)),
977            ("9040", Some(AuthenticationRefused)),
978            ("9050", Some(Rejected)),
979            ("9171", Some(Rejected)),
980            ("9210", Some(Rejected)),
981            ("9230", Some(Rejected)),
982            ("9390", Some(Rejected)),
983            ("9255", Some(Rejected)),
984            ("9999", Some(Rejected)),
985        ];
986        for (code, want) in cases {
987            let c = ReturnCode::new(Code::new(code).unwrap(), "t", Scope::Message);
988            assert_eq!(c.category(), *want, "{code}");
989        }
990        // 9360 with P1 announces a lock after further attempts: a TAN
991        // problem, not yet a lock.
992        let c = ReturnCode::new(Code::new("9360").unwrap(), "t", Scope::Message)
993            .with_parameters(vec!["2".into()]);
994        assert_eq!(c.category(), Some(Tan));
995    }
996
997    #[test]
998    fn empty_parameters_are_kept_but_skipped_for_the_kind() {
999        let c = ReturnCode::new(Code::new("3072").unwrap(), "t", Scope::Message)
1000            .with_parameters(vec!["".into(), "cust".into()]);
1001        assert_eq!(c.parameters, ["", "cust"]);
1002        assert_eq!(
1003            c.kind(),
1004            Kind::UserDataChanged {
1005                user_id: Some("cust".into()),
1006                customer_id: Some("cust".into()),
1007            }
1008        );
1009    }
1010
1011    /// 3090, 3093, 3094 are consumed only in answers to HKVPP and HKVPA.
1012    #[test]
1013    fn payee_check_codes_are_consumed_only_for_hkvpp_and_hkvpa() {
1014        let on = |code: &str, order: &str| {
1015            ReturnCode::new(
1016                Code::new(code).unwrap(),
1017                "t",
1018                Scope::Segment {
1019                    number: 3,
1020                    order: Some(SegmentType::new(order)),
1021                },
1022            )
1023        };
1024        for code in ["3090", "3093", "3094"] {
1025            assert!(Notice::is_consumed(&on(code, "HKVPP")), "{code}");
1026            assert!(Notice::is_consumed(&on(code, "HKVPA")), "{code}");
1027            assert!(!Notice::is_consumed(&on(code, "HKCCS")), "{code}");
1028        }
1029        assert!(Notice::is_consumed(&on("3045", "HKTAN")));
1030        for code in ["3070", "3092", "3270", "3046", "3020"] {
1031            assert!(!Notice::is_consumed(&on(code, "HKCCS")), "{code}");
1032        }
1033    }
1034
1035    #[test]
1036    fn code_is_four_digits() {
1037        for bad in ["", "123", "12345", "XXXX", "12a4", "١٢٣٤"] {
1038            assert_eq!(Code::new(bad), None, "{bad}");
1039        }
1040        assert_eq!(Code::new("0010").unwrap().to_string(), "0010");
1041    }
1042
1043    #[test]
1044    fn serde_round_trip() {
1045        let c = ReturnCode::new(
1046            Code::new("9210").unwrap(),
1047            "Konto unbekannt",
1048            Scope::Segment {
1049                number: 4,
1050                order: Some(SegmentType::new("HKSAL")),
1051            },
1052        )
1053        .with_reference_element("3")
1054        .with_parameters(vec!["A1".into()]);
1055        let json = serde_json::to_string(&c).unwrap();
1056        assert!(json.contains("\"code\":\"9210\""), "{json}");
1057        assert_eq!(serde_json::from_str::<ReturnCode>(&json).unwrap(), c);
1058        assert!(serde_json::from_str::<Code>("\"92\"").is_err());
1059        assert_eq!(c.to_string(), "9210: Konto unbekannt");
1060    }
1061}