Skip to main content

fints_client/
types.rs

1//! FinTS data types and Data Element Group definitions.
2//!
3//! Provides typed representations of common FinTS structures
4//! that appear across multiple segments.
5
6use jiff::civil::Date;
7use rust_decimal::Decimal;
8use rust_decimal::prelude::ToPrimitive;
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12use crate::parser::RawSegment;
13
14// ── Text types ──────────────────────────────────────────────────────────────
15//
16// Each identifier of the protocol gets its own type, so that a bank code
17// cannot end up where a user ID belongs.
18
19/// Declares a text type with `new`, `as_str`, `Display` and `AsRef<str>`.
20macro_rules! text_type {
21    ($(#[$doc:meta])* $ty:ident) => {
22        $(#[$doc])*
23        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
24        pub struct $ty(String);
25
26        impl $ty {
27            /// Wraps the text as given.
28            pub fn new(text: impl Into<String>) -> Self {
29                Self(text.into())
30            }
31
32            /// The wrapped text.
33            pub fn as_str(&self) -> &str {
34                self.0.as_str()
35            }
36        }
37
38        impl fmt::Display for $ty {
39            fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
40                fmt::Display::fmt(self.0.as_str(), out)
41            }
42        }
43
44        impl AsRef<str> for $ty {
45            fn as_ref(&self) -> &str {
46                self.as_str()
47            }
48        }
49    };
50}
51
52text_type!(
53    /// Bank code (Bankleitzahl), e.g. "12030000".
54    Blz
55);
56text_type!(
57    /// FinTS user ID / login name.
58    UserId
59);
60text_type!(
61    /// System ID assigned by the bank via HKSYN.
62    SystemId
63);
64text_type!(
65    /// FinTS product registration ID.
66    ProductId
67);
68text_type!(
69    /// Dialog ID assigned by the bank in HNHBK.
70    DialogId
71);
72text_type!(
73    /// Security function code, e.g. "940" for pushTAN, "999" for PIN-only.
74    SecurityFunction
75);
76text_type!(
77    /// Task reference from HITAN, used in HKTAN process 2/S.
78    TaskReference
79);
80text_type!(
81    /// Segment type identifier, e.g. "HKSAL", "HKKAZ".
82    SegmentType
83);
84text_type!(
85    /// TAN medium name (e.g. device name for pushTAN).
86    TanMediumName
87);
88text_type!(
89    /// Touchdown/pagination point returned by the bank (code 3040).
90    TouchdownPoint
91);
92text_type!(
93    /// Segment type reference for HKTAN process 4 (e.g. "HKIDN", "HKSAL").
94    SegmentRef
95);
96text_type!(
97    /// Currency code (ISO 4217), e.g. "EUR".
98    Currency
99);
100
101impl Currency {
102    /// ISO 4217 minor-unit exponent: 0 for JPY and similar, 3 for BHD, KWD,
103    /// TND, JOD, OMR, IQD, LYD, and 2 for every other code, unknown ones
104    /// included.
105    pub fn exponent(&self) -> u32 {
106        match self.0.to_ascii_uppercase().as_str() {
107            "BIF" | "CLP" | "DJF" | "GNF" | "ISK" | "JPY" | "KMF" | "KRW" | "PYG" | "RWF"
108            | "UGX" | "UYI" | "VND" | "VUV" | "XAF" | "XOF" | "XPF" => 0,
109            "BHD" | "IQD" | "JOD" | "KWD" | "LYD" | "OMR" | "TND" => 3,
110            _ => 2,
111        }
112    }
113
114    /// `amount` in minor units (EUR 12.34 is 1234). `None` when the amount
115    /// has more decimals than [`exponent`](Self::exponent) allows (it is
116    /// never rounded) or does not fit an `i64`.
117    pub fn to_minor(&self, amount: Decimal) -> Option<i64> {
118        let amount = amount.normalize();
119        let exponent = self.exponent();
120        if amount.scale() > exponent {
121            return None;
122        }
123        let minor = amount.checked_mul(Decimal::from(10_i64.pow(exponent)))?;
124        minor.to_i64()
125    }
126}
127text_type!(
128    /// IBAN (International Bank Account Number).
129    Iban
130);
131text_type!(
132    /// BIC (Bank Identifier Code).
133    Bic
134);
135text_type!(
136    /// Human-readable bank name.
137    BankName
138);
139text_type!(
140    /// FinTS server URL.
141    FinTSUrl
142);
143text_type!(
144    /// TAN challenge text to display to the user.
145    ChallengeText
146);
147
148/// The HHD-UC challenge bytes of an optical TAN method (HITAN
149/// "Challenge HHD_UC"), as the bank sent them.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct HhdUcData(pub Vec<u8>);
152
153/// HHD-UC challenge data sorted into something a user interface can show.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155pub enum TanMedia {
156    /// A picture for the TAN app or reader to scan (photoTAN, QR-TAN),
157    /// with its media type, typically `image/png`.
158    Image { mime_type: String, data: Vec<u8> },
159    /// A chipTAN flicker code (HHD 1.4), unchanged; turning it into the
160    /// animation is up to the caller.
161    Flicker(String),
162}
163
164impl HhdUcData {
165    /// What the challenge data is.
166    ///
167    /// A matrix code is a sequence of two length-prefixed fields, each
168    /// prefix being two bytes big-endian: first the media type, then the
169    /// picture. Data that does not parse that way but is all printable
170    /// ASCII is taken as a flicker code. Everything else is `None`.
171    pub fn decode(&self) -> Option<TanMedia> {
172        let bytes = &self.0[..];
173        matrix_code(bytes).or_else(|| flicker_code(bytes))
174    }
175}
176
177/// Splits the field after a two-byte big-endian length off `input`.
178fn length_prefixed(input: &[u8]) -> Option<(&[u8], &[u8])> {
179    let (len, rest) = input.split_first_chunk::<2>()?;
180    let len = usize::from(u16::from_be_bytes(*len));
181    (rest.len() >= len).then(|| rest.split_at(len))
182}
183
184fn matrix_code(bytes: &[u8]) -> Option<TanMedia> {
185    let (media_type, rest) = length_prefixed(bytes)?;
186    let plausible = matches!(media_type.len(), 3..=100)
187        && media_type.iter().all(u8::is_ascii_graphic)
188        && media_type.contains(&b'/');
189    if !plausible {
190        return None;
191    }
192    let (picture, _) = length_prefixed(rest)?;
193    Some(TanMedia::Image {
194        mime_type: String::from_utf8_lossy(media_type).into_owned(),
195        data: picture.to_vec(),
196    })
197}
198
199fn flicker_code(bytes: &[u8]) -> Option<TanMedia> {
200    if bytes.is_empty() || bytes.iter().any(|b| !(b' '..=b'~').contains(b)) {
201        return None;
202    }
203    // Printable ASCII is valid UTF-8.
204    let text = std::str::from_utf8(bytes).ok()?;
205    Some(TanMedia::Flicker(text.trim().to_owned()))
206}
207
208/// A statement in SWIFT MT940/MT942 format, still as bytes (Windows-1252).
209#[derive(Debug, Clone, Default)]
210pub struct Mt940Data(pub Vec<u8>);
211
212impl Mt940Data {
213    /// No data yet.
214    pub fn new() -> Self {
215        Self::default()
216    }
217
218    /// The bytes collected so far.
219    pub fn as_bytes(&self) -> &[u8] {
220        self.0.as_slice()
221    }
222
223    /// True before the first page arrived (or when all pages were empty).
224    pub fn is_empty(&self) -> bool {
225        self.as_bytes().is_empty()
226    }
227
228    /// Append one more page of a statement fetched with touchdown points.
229    /// Pages are concatenated unchanged: a bank may cut the stream anywhere,
230    /// even in the middle of a field.
231    pub fn extend(&mut self, page: Vec<u8>) {
232        self.0.extend_from_slice(&page);
233    }
234}
235
236/// The user's PIN. `Debug` and `Display` never show it.
237#[derive(Clone)]
238pub struct Pin(String);
239
240impl Pin {
241    pub fn new(pin: impl Into<String>) -> Self {
242        Self(pin.into())
243    }
244
245    /// The PIN itself, for the signature head only.
246    pub fn as_str(&self) -> &str {
247        self.0.as_str()
248    }
249}
250
251const HIDDEN: &str = "****";
252
253impl fmt::Debug for Pin {
254    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
255        write!(out, "Pin({HIDDEN})")
256    }
257}
258
259impl fmt::Display for Pin {
260    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
261        out.write_str(HIDDEN)
262    }
263}
264
265// ── Values with a meaning in the protocol ───────────────────────────────────
266
267/// The placeholder Formals uses for an identifier the bank has not given
268/// out yet (system ID before synchronisation, dialog ID before the first
269/// answer).
270const NOT_YET_ASSIGNED: &str = "0";
271
272fn assigned(id: &str) -> bool {
273    !matches!(id, "" | NOT_YET_ASSIGNED)
274}
275
276impl SystemId {
277    /// The value sent before HKSYN gave the customer system an ID.
278    pub fn unassigned() -> Self {
279        Self::new(NOT_YET_ASSIGNED)
280    }
281
282    /// Whether the bank has given out this ID.
283    pub fn is_assigned(&self) -> bool {
284        assigned(&self.0)
285    }
286}
287
288impl DialogId {
289    /// The value of the first message of a dialog.
290    pub fn unassigned() -> Self {
291        Self::new(NOT_YET_ASSIGNED)
292    }
293
294    /// Whether the bank has opened the dialog under this ID.
295    pub fn is_assigned(&self) -> bool {
296        assigned(&self.0)
297    }
298}
299
300impl SecurityFunction {
301    /// Security function 999: the one-step procedure, PIN without TAN.
302    pub fn pin_only() -> Self {
303        Self::new("999")
304    }
305}
306
307/// "TAN-Prozess" of a two-step method (PIN/TAN document, HITANS).
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
309pub enum TanProcess {
310    /// Process 1: the TAN goes into the same message as the order.
311    OneStep,
312    /// Process 2 (also 3 and 4 of older versions): order first, TAN in a
313    /// later message.
314    TwoStep,
315}
316
317impl TanProcess {
318    /// From the HITANS code: `1` is one message, anything else two.
319    pub fn from_str_val(code: &str) -> Self {
320        if code == "1" {
321            Self::OneStep
322        } else {
323            Self::TwoStep
324        }
325    }
326}
327
328// ── Reading single elements ─────────────────────────────────────────────────
329
330/// Element `de` of group `deg` as text, `""` when absent.
331pub(crate) fn read_str(seg: &RawSegment, deg: usize, de: usize) -> String {
332    seg.deg(deg).get_str(de)
333}
334
335/// Element `de` of group `deg` as text, `None` when absent or empty.
336pub(crate) fn read_opt_str(seg: &RawSegment, deg: usize, de: usize) -> Option<String> {
337    Some(read_str(seg, deg, de)).filter(|text| !text.is_empty())
338}
339
340// ── What the library hands to callers ───────────────────────────────────────
341
342/// One TAN method the bank offers (an entry of HITANS).
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct TanMethod {
345    /// Security function code (e.g. "912" for pushTAN)
346    pub security_function: SecurityFunction,
347    /// TAN process type.
348    pub tan_process: TanProcess,
349    /// Human-readable name (e.g. "pushTAN-2.0")
350    pub name: String,
351    /// Whether TAN medium name must be sent
352    pub needs_tan_medium: bool,
353    /// Decoupled methods: how many status requests (HKTAN process S) the
354    /// bank accepts. HITANS uses `0` for no limit; `-1` here means the bank
355    /// did not say.
356    pub decoupled_max_polls: i32,
357    /// Decoupled methods: seconds before the first status request; `0`
358    /// when the bank did not say.
359    pub wait_before_first_poll: i32,
360    /// Decoupled methods: seconds between status requests; `0` when the
361    /// bank did not say.
362    pub wait_before_next_poll: i32,
363    /// Whether this is a decoupled method
364    pub is_decoupled: bool,
365    /// The HKTAN version to use: that of the HITANS segment listing the
366    /// method.
367    pub hktan_version: u16,
368    /// The method's DK identifier ("DK-TAN-Verfahren", earlier "ZKA"),
369    /// such as `HHD` or `Decoupled`.
370    pub zka_name: Option<String>,
371    /// HITANS 7 "Automatischer Statusabruf erlaubt". `Some(false)`: the
372    /// user confirms in the client before it asks for the status.
373    pub decoupled_auto_polling: Option<bool>,
374    /// HITANS "Challenge strukturiert": the HITAN challenge text of this
375    /// method may carry markup.
376    pub challenge_structured: bool,
377}
378
379/// The identity of an account of the UPD, stable across logins: its KTV
380/// (Kontoverbindung, HIUPD DE 1), or its IBAN when the UPD entry has no
381/// account number.
382///
383/// Normalised: the BLZ is the KTV's own (not the login's), leading zeros
384/// of the number are dropped (`0` stays `0`), an empty subaccount is no
385/// subaccount, the IBAN is upper case without spaces. Two UPD entries that
386/// share IBAN and number but differ in the subaccount (a clearing account
387/// and its depot) have different keys.
388///
389/// The string form ([`Display`](fmt::Display), [`FromStr`](std::str::FromStr),
390/// also the serde form) is `<blz>/<number>[/<subaccount>]` or
391/// `iban:<IBAN>[/<subaccount>]`; `%` and `/` inside the BLZ, number and
392/// IBAN are written `%25` and `%2F`. It round-trips and suits an app's
393/// reference to a synced account.
394#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
395pub enum AccountKey {
396    /// The KTV: bank code, account number, subaccount.
397    National {
398        blz: Blz,
399        number: String,
400        subaccount: Option<String>,
401    },
402    /// A UPD entry without account number (or without bank code): IBAN
403    /// and subaccount.
404    Iban {
405        iban: Iban,
406        subaccount: Option<String>,
407    },
408}
409
410impl AccountKey {
411    /// The key of a KTV. `None` without a number or bank code.
412    pub fn national(blz: &str, number: &str, subaccount: Option<&str>) -> Option<Self> {
413        let (blz, number) = (blz.trim(), number.trim());
414        if blz.is_empty() || number.is_empty() {
415            return None;
416        }
417        let stripped = number.trim_start_matches('0');
418        Some(Self::National {
419            blz: Blz::new(blz),
420            number: if stripped.is_empty() { "0" } else { stripped }.to_string(),
421            subaccount: normal_subaccount(subaccount),
422        })
423    }
424
425    /// The key of an account known by IBAN only. `None` for an empty IBAN.
426    pub fn iban(iban: &str, subaccount: Option<&str>) -> Option<Self> {
427        let iban: String = iban
428            .chars()
429            .filter(|c| !c.is_whitespace())
430            .collect::<String>()
431            .to_ascii_uppercase();
432        (!iban.is_empty()).then(|| Self::Iban {
433            iban: Iban::new(iban),
434            subaccount: normal_subaccount(subaccount),
435        })
436    }
437
438    /// The subaccount (Unterkontomerkmal), if any.
439    pub fn subaccount(&self) -> Option<&str> {
440        match self {
441            Self::National { subaccount, .. } | Self::Iban { subaccount, .. } => {
442                subaccount.as_deref()
443            }
444        }
445    }
446}
447
448fn normal_subaccount(subaccount: Option<&str>) -> Option<String> {
449    subaccount
450        .map(str::trim)
451        .filter(|s| !s.is_empty())
452        .map(str::to_string)
453}
454
455const KEY_IBAN_PREFIX: &str = "iban:";
456
457fn key_escape(s: &str) -> String {
458    s.replace('%', "%25").replace('/', "%2F")
459}
460
461fn key_unescape(s: &str) -> String {
462    s.replace("%2F", "/")
463        .replace("%2f", "/")
464        .replace("%25", "%")
465}
466
467impl fmt::Display for AccountKey {
468    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469        let subaccount = match self {
470            Self::National { blz, number, .. } => {
471                write!(f, "{}/{}", key_escape(blz.as_str()), key_escape(number))?;
472                self.subaccount()
473            }
474            Self::Iban { iban, .. } => {
475                write!(f, "{KEY_IBAN_PREFIX}{}", key_escape(iban.as_str()))?;
476                self.subaccount()
477            }
478        };
479        match subaccount {
480            Some(s) => write!(f, "/{s}"),
481            None => Ok(()),
482        }
483    }
484}
485
486/// Why a string is not an [`AccountKey`].
487#[derive(Debug, Clone, PartialEq, Eq)]
488pub struct AccountKeyError(String);
489
490impl fmt::Display for AccountKeyError {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        write!(f, "not an account key: {:?}", self.0)
493    }
494}
495
496impl std::error::Error for AccountKeyError {}
497
498impl std::str::FromStr for AccountKey {
499    type Err = AccountKeyError;
500
501    /// Reads the form [`Display`](fmt::Display) writes; the subaccount is
502    /// the rest after the second (IBAN form: first) `/`.
503    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
504        let err = || AccountKeyError(s.to_string());
505        let key = if let Some(rest) = s.strip_prefix(KEY_IBAN_PREFIX) {
506            let (iban, sub) = match rest.split_once('/') {
507                Some((iban, sub)) => (iban, Some(sub)),
508                None => (rest, None),
509            };
510            AccountKey::iban(&key_unescape(iban), sub)
511        } else {
512            let mut parts = s.splitn(3, '/');
513            let blz = parts.next().ok_or_else(err)?;
514            let number = parts.next().ok_or_else(err)?;
515            AccountKey::national(&key_unescape(blz), &key_unescape(number), parts.next())
516        };
517        // Only the normal form is accepted, so that one account has one string.
518        key.filter(|k| k.to_string() == s).ok_or_else(err)
519    }
520}
521
522impl Serialize for AccountKey {
523    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
524        s.collect_str(self)
525    }
526}
527
528impl<'de> Deserialize<'de> for AccountKey {
529    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
530        let s = String::deserialize(d)?;
531        s.parse().map_err(serde::de::Error::custom)
532    }
533}
534
535/// Kontoart first, else a depot by the allowed orders; see
536/// [`AccountInfo::class`](crate::jobs::AccountInfo::class).
537pub(crate) fn classify(
538    account_type: Option<u8>,
539    allows: impl Fn(&str) -> bool,
540) -> Option<(AccountClass, ClassSource)> {
541    if let Some(class) = account_type.and_then(AccountClass::from_account_type) {
542        return Some((class, ClassSource::Kontoart));
543    }
544    if allows("HKWPD") && !allows("HKSAL") && !allows("HKKAZ") && !allows("HKCAZ") {
545        return Some((AccountClass::Depot, ClassSource::AllowedJobs));
546    }
547    None
548}
549
550/// One HIUPD account as the remainder parser and the trace recorder read
551/// it. The jobs use [`crate::protocol::UpdAccount`] and
552/// [`crate::jobs::AccountInfo`].
553#[derive(Debug, Clone)]
554pub(crate) struct SepaAccount {
555    pub iban: Iban,
556    pub bic: Bic,
557    pub account_number: String,
558    pub sub_account: String,
559    pub blz: Blz,
560    pub owner: Option<String>,
561    pub product_name: Option<String>,
562    pub currency: Option<Currency>,
563    /// "Kontoart" from the UPD (HIUPD v6), 1-99. See [`classify`].
564    pub account_type: Option<u8>,
565    /// "Erlaubte Geschäftsvorfälle" of the UPD: the order codes (HKSAL, HKKAZ,
566    /// HKWPD, …) the user may send for this account. Empty when the UPD lists
567    /// none. Read by the trace recorder only.
568    #[cfg_attr(not(any(test, feature = "trace")), allow(dead_code))]
569    pub allowed_jobs: Vec<String>,
570}
571
572impl SepaAccount {
573    /// See [`classify`].
574    #[cfg(any(test, feature = "trace"))]
575    pub(crate) fn classify(&self) -> Option<(AccountClass, ClassSource)> {
576        classify(self.account_type, |job| {
577            self.allowed_jobs.iter().any(|j| j == job)
578        })
579    }
580}
581
582/// Where an [`AccountClass`] came from.
583#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
584pub enum ClassSource {
585    /// The Kontoart of the UPD.
586    Kontoart,
587    /// No Kontoart; deduced from the orders the UPD allows.
588    AllowedJobs,
589}
590
591/// What kind of account a UPD entry is, from its "Kontoart" (Formals, data
592/// dictionary). The spec assigns each tens range one kind; the values
593/// inside a range are the bank's own.
594#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
595pub enum AccountClass {
596    /// Kontoart 1 to 9, current account (Kontokorrent-/Girokonto).
597    Checking,
598    /// Kontoart 10 to 19, savings account.
599    Savings,
600    /// Kontoart 20 to 29, time deposit (Festgeld).
601    FixedDeposit,
602    /// Kontoart 30 to 39, securities account.
603    Depot,
604    /// Kontoart 40 to 49, loan.
605    Loan,
606    /// Kontoart 50 to 59, credit card.
607    CreditCard,
608    /// Kontoart 60 to 69, fund account held at an investment company.
609    FundDepot,
610    /// Kontoart 70 to 79, building savings contract (Bausparen).
611    HomeSavings,
612    /// Kontoart 80 to 89, insurance contract.
613    Insurance,
614    /// Kontoart 90 to 99, anything else.
615    Other,
616}
617
618impl AccountClass {
619    /// Kind by tens range, in order of the ranges 1-9, 10-19, ... 90-99.
620    const BY_TENS: [Self; 10] = [
621        Self::Checking,
622        Self::Savings,
623        Self::FixedDeposit,
624        Self::Depot,
625        Self::Loan,
626        Self::CreditCard,
627        Self::FundDepot,
628        Self::HomeSavings,
629        Self::Insurance,
630        Self::Other,
631    ];
632
633    /// The kind for a Kontoart; `None` outside 1 to 99.
634    pub fn from_account_type(account_type: u8) -> Option<Self> {
635        if !(1..=99).contains(&account_type) {
636            return None;
637        }
638        Some(Self::BY_TENS[usize::from(account_type / 10)])
639    }
640}
641
642/// Account balance.
643#[derive(Debug, Clone, Serialize, Deserialize)]
644pub struct AccountBalance {
645    pub amount: Decimal,
646    /// Date of the booked balance; `None` if the bank left it out.
647    pub date: Option<Date>,
648    /// The balance's currency; the account currency if the bank left it out.
649    pub currency: Currency,
650    pub credit_line: Option<Decimal>,
651    pub available: Option<Decimal>,
652    /// Pending (vorgemerkter) balance amount, if provided by the bank.
653    pub pending_amount: Option<Decimal>,
654    /// Date of the pending balance, if provided.
655    pub pending_date: Option<Date>,
656}
657
658/// A time the bank stamped on its data: the bank's wall clock, and its UTC
659/// offset when the bank sent one. FinTS carries no time zones (Formals
660/// `tim` is the sender's local time); SWIFT `:13D:` adds a fixed offset,
661/// the older `:13:` (HBCI 2.2 IX.2.9) has none. Not serde (jiff's
662/// `Offset` is not); like [`jobs::Statement`](crate::jobs::Statement).
663#[derive(Debug, Clone, Copy, PartialEq, Eq)]
664pub struct BankTime {
665    /// Date and time as the bank wrote them.
666    pub datetime: jiff::civil::DateTime,
667    /// The offset from UTC the bank gave; `None` when it gave none.
668    pub offset: Option<jiff::tz::Offset>,
669}
670
671impl BankTime {
672    /// The instant, when the bank gave an offset. Without one the wall
673    /// clock is the bank's (German banks: Europe/Berlin), which the library
674    /// does not guess.
675    pub fn timestamp(&self) -> Option<jiff::Timestamp> {
676        self.offset.and_then(|o| o.to_timestamp(self.datetime).ok())
677    }
678}
679
680/// Whether a transaction is booked or pending (vorgemerkt).
681#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub enum TransactionStatus {
683    Booked,
684    Pending,
685}
686
687// ── Securities / Depot types ────────────────────────────────────────────────
688
689text_type!(
690    /// ISIN (International Securities Identification Number), e.g. "DE0005140008".
691    Isin
692);
693text_type!(
694    /// WKN (Wertpapierkennnummer), e.g. "514000".
695    Wkn
696);
697
698/// A single securities position in a depot.
699#[derive(Debug, Clone, Serialize, Deserialize)]
700pub struct SecurityHolding {
701    /// ISIN of the security.
702    pub isin: Option<Isin>,
703    /// WKN (German securities identification number).
704    pub wkn: Option<Wkn>,
705    /// Human-readable name of the security.
706    pub name: String,
707    /// Number of shares/units held (can be fractional for funds).
708    pub quantity: Decimal,
709    /// Current market price per unit.
710    pub price: Option<Decimal>,
711    /// Currency of the price.
712    pub price_currency: Option<Currency>,
713    /// Date of the price quote.
714    pub price_date: Option<Date>,
715    /// Total market value (quantity * price).
716    pub market_value: Option<Decimal>,
717    /// Currency of the market value.
718    pub market_value_currency: Option<Currency>,
719    /// Original purchase value (Einstandswert), if available.
720    pub acquisition_value: Option<Decimal>,
721    /// Purchase (acquisition) date, from the German structured MT535
722    /// `:70E::HOLD` narrative.
723    pub acquisition_date: Option<Date>,
724    /// Purchase price per unit (percent of face amount for bonds).
725    pub acquisition_price: Option<Decimal>,
726    /// Currency of the purchase price; `None` for percent prices.
727    pub acquisition_price_currency: Option<Currency>,
728    /// Profit/loss amount, if available.
729    pub profit_loss: Option<Decimal>,
730    /// Exchange/market where the price was quoted.
731    pub exchange: Option<String>,
732    /// Depot number this holding belongs to.
733    pub depot_id: Option<String>,
734    /// Date the statement holding this position was made for (MT535
735    /// `:98A::STAT` or `:98C::STAT` in the general block), if the bank sent one.
736    pub statement_date: Option<Date>,
737    /// Raw parsed data for debugging/extension.
738    pub raw: serde_json::Value,
739}
740
741/// Whether securities came into or left the depot (MT536 `:22H::REDE`).
742#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
743pub enum DepotTransactionDirection {
744    /// `RECE`: received (purchase, inbound transfer).
745    Receive,
746    /// `DELI`: delivered (sale, outbound transfer).
747    Deliver,
748    /// Not given or not recognised.
749    Unknown,
750}
751
752/// One depot transaction (securities movement) from an MT536 statement.
753#[derive(Debug, Clone, Serialize, Deserialize)]
754pub struct DepotTransaction {
755    pub isin: Option<Isin>,
756    pub wkn: Option<Wkn>,
757    /// Description of the security.
758    pub name: String,
759    /// Posted quantity: pieces, or face amount for bonds (see `raw["quantity_type"]`).
760    pub quantity: Decimal,
761    /// Posted amount, signed as the bank sends it (`N` = negative).
762    pub amount: Option<Decimal>,
763    pub currency: Option<Currency>,
764    pub direction: DepotTransactionDirection,
765    /// Transaction type indicator (`:22F::TRAN`), e.g. `SETT`, `CORP`.
766    pub transaction_type: Option<String>,
767    /// Effective settlement date (`ESET`).
768    pub effective_date: Option<Date>,
769    /// Trade date (`TRAD`).
770    pub trade_date: Option<Date>,
771    /// Settlement date (`SETT`).
772    pub settlement_date: Option<Date>,
773    /// Deal price per unit (percent of face amount when no currency).
774    pub price: Option<Decimal>,
775    pub price_currency: Option<Currency>,
776    /// Reversal (Storno) of an earlier transaction.
777    pub is_reversal: bool,
778    /// Free text from `:70E:`, lines joined with `\n`.
779    pub details: Option<String>,
780    /// Depot number from the statement header.
781    pub depot_id: Option<String>,
782    /// Raw parsed data for debugging/extension.
783    pub raw: serde_json::Value,
784}
785
786/// A parsed transaction.
787///
788/// A camt entry (`Ntry`) with several `TxDtls` (a batch booking) maps to
789/// one `Transaction`, built from the first `TxDtls`: the counterparty and
790/// purpose fields describe only that part of the batch. The amount is the
791/// entry's, and `booking_id` is the entry's own reference.
792#[derive(Debug, Clone, Serialize, Deserialize)]
793pub struct Transaction {
794    /// Booking date (Buchungstag): the MT940 entry date, or the value date
795    /// when the bank leaves the entry date out. A pending CAMT entry with
796    /// neither date takes the day the bank made the report (`CreDtTm`).
797    pub date: Date,
798    /// Value date (Valuta, Wertstellung).
799    pub valuta_date: Option<Date>,
800    /// Signed from the account holder's view: negative = debit.
801    pub amount: Decimal,
802    pub currency: Currency,
803    pub applicant_name: Option<String>,
804    pub applicant_iban: Option<Iban>,
805    pub applicant_bic: Option<Bic>,
806    /// Remittance text: the SEPA `SVWZ+` value of MT940 `:86:`, or CAMT
807    /// `Ustrd` (`None` when the entry has none; its `AddtlNtryInf` is the
808    /// `posting_text`). In MT940 without SEPA keywords, the whole `:86:` text. The keywords themselves and the
809    /// other SEPA fields have their own fields; MT940 keeps the joined
810    /// `:86:` text in `raw["tag86"]`. Characters are as the bank sent them.
811    pub purpose: Option<String>,
812    /// Booking text (Buchungstext), e.g. "SEPA-BASISLASTSCHRIFT".
813    pub posting_text: Option<String>,
814    /// Customer reference (Kundenreferenz) from MT940 `:61:`; `None` for
815    /// "NONREF". CAMT has no such field: always `None` there (the end-to-end
816    /// ID is `end_to_end_id`).
817    pub customer_reference: Option<String>,
818    /// Bank reference from `:61:` (after `//`), or CAMT `AcctSvcrRef`
819    /// (transaction level before entry level), if the bank sends one. Not
820    /// known to be unique: for de-duplication use `booking_id`.
821    pub bank_reference: Option<String>,
822    /// The bank's own ID of this booking, set only where the bank's profile
823    /// ([`BookingIdSource`](crate::banks::BookingIdSource)) names a reference
824    /// the bank keeps unique and stable: no two transactions of a statement
825    /// share it, and the bank does not reuse it for another booking. Safe
826    /// as a key for de-duplication across fetches.
827    ///
828    /// `None` for banks without such a reference, for every MT940 booking,
829    /// for pending bookings (whether a booking keeps its reference from
830    /// pending to booked is unverified at any bank), for an entry without
831    /// the reference, and for a reference that occurs more than once in
832    /// one statement.
833    pub booking_id: Option<String>,
834    /// The DK business transaction code (Geschäftsvorfallcode, three
835    /// digits) at the start of `:86:`; `166` is a SEPA credit transfer
836    /// received.
837    pub gvc: Option<String>,
838    /// The bank's Primanota number, subfield `?10` of `:86:`.
839    pub prima_nota: Option<String>,
840    /// ISO 20022 purpose code (e.g. `SALA`, `IDCP`): `PURP+` or `Purp/Cd`.
841    pub purpose_code: Option<String>,
842    /// SEPA direct debit mandate reference (`MREF+`, `MndtId`). `None` for
843    /// a placeholder such as `NONREF`.
844    pub mandate_id: Option<String>,
845    /// SEPA end-to-end reference (`EREF+`, `EndToEndId`). `None` for a
846    /// placeholder such as `NOTPROVIDED`.
847    pub end_to_end_id: Option<String>,
848    /// SEPA creditor ID of a direct debit (`CRED+` of MT940 `:86:`, CAMT
849    /// `Cdtr/Id/PrvtId/Othr/Id`). `None` for a placeholder.
850    pub creditor_id: Option<String>,
851    /// SEPA identifier of the debtor (`DEBT+` of MT940 `:86:`, CAMT
852    /// `Dbtr/Id`): the originator ID of a transfer or the debtor's own ID.
853    /// `None` for a placeholder.
854    pub debtor_id: Option<String>,
855    /// The ultimate debtor (Abweichender Zahlungspflichtiger) when it
856    /// differs from the direct one: CAMT `UltmtDbtr/Nm`; MT940 `ABWA+` of a
857    /// transfer, `ABWE+` of a direct debit. For an R-transaction (return,
858    /// reversal) the original payment's roles.
859    pub ultimate_debtor: Option<String>,
860    /// The ultimate creditor (Abweichender Zahlungsempfänger): CAMT
861    /// `UltmtCdtr/Nm`; MT940 `ABWE+` of a transfer, `ABWA+` of a direct
862    /// debit.
863    pub ultimate_creditor: Option<String>,
864    /// Whether the booking is a reversal (Storno): CAMT `RvslInd` true,
865    /// MT940 `:61:` mark `RC` or `RD`.
866    pub reversal: bool,
867    /// Original amount before conversion or before a return, with its
868    /// currency (always positive): CAMT `AmtDtls/InstdAmt/Amt`; MT940 `OAMT+`,
869    /// which carries no currency, so the statement currency is used.
870    pub original_amount: Option<(Decimal, Currency)>,
871    /// Fees or compensation charged on the booking, positive: CAMT `Chrgs`
872    /// (`TtlChrgsAndTaxAmt`, else the first `Rcrd/Amt`); MT940 `COAM+` in the
873    /// statement currency.
874    pub fees: Option<(Decimal, Currency)>,
875    /// Return or rejection reason code (e.g. `AC04`, `MD06`): CAMT
876    /// `RtrInf/Rsn/Cd`; MT940 the code after the `REJECT`/`RETURN` marker in
877    /// `SVWZ+`.
878    pub return_reason: Option<String>,
879    /// Direct debit sequence type (`FRST`, `RCUR`, `OOFF`, `FNAL`): CAMT
880    /// `PmtTpInf/SeqTp`. MT940 has no such field.
881    pub sequence_type: Option<String>,
882    pub raw: serde_json::Value,
883    /// Whether this transaction is booked or pending.
884    pub status: TransactionStatus,
885}
886
887#[cfg(test)]
888mod tests {
889    use super::*;
890
891    #[test]
892    fn currency_to_minor() {
893        let d = |s: &str| s.parse::<Decimal>().unwrap();
894        let eur = Currency::new("EUR");
895        assert_eq!(eur.to_minor(d("12.34")), Some(1234));
896        assert_eq!(eur.to_minor(d("12.3400")), Some(1234));
897        assert_eq!(eur.to_minor(d("12.345")), None);
898        assert_eq!(eur.to_minor(d("-0.5")), Some(-50));
899        assert_eq!(Currency::new("JPY").to_minor(d("100")), Some(100));
900        assert_eq!(Currency::new("JPY").to_minor(d("1.5")), None);
901        assert_eq!(Currency::new("KWD").to_minor(d("1.234")), Some(1234));
902        assert_eq!(Currency::new("XYZ").to_minor(d("1.23")), Some(123));
903        assert_eq!(eur.to_minor(Decimal::MAX), None);
904        assert_eq!(eur.to_minor(d("92233720368547758.07")), Some(i64::MAX));
905        assert_eq!(eur.to_minor(d("92233720368547758.08")), None);
906    }
907
908    /// Two-byte big-endian length, then the bytes.
909    fn field(bytes: &[u8]) -> Vec<u8> {
910        let mut out = u16::try_from(bytes.len()).unwrap().to_be_bytes().to_vec();
911        out.extend_from_slice(bytes);
912        out
913    }
914
915    #[test]
916    fn matrix_code_gives_the_picture() {
917        let picture = b"\x89PNG-synthetic";
918        let challenge = [field(b"image/png"), field(picture)].concat();
919        let expected = TanMedia::Image {
920            mime_type: "image/png".to_owned(),
921            data: picture.to_vec(),
922        };
923        assert_eq!(HhdUcData(challenge).decode(), Some(expected));
924    }
925
926    #[test]
927    fn printable_challenge_is_a_flicker_code() {
928        let code = "0248A0120452019980812345678";
929        let decoded = HhdUcData(format!(" {code} ").into_bytes()).decode();
930        assert_eq!(decoded, Some(TanMedia::Flicker(code.to_owned())));
931    }
932
933    #[test]
934    fn short_or_unprintable_challenge_is_none() {
935        let mut cut_off = [field(b"image/png"), field(&[7; 40])].concat();
936        cut_off.truncate(cut_off.len() - 1);
937        for challenge in [cut_off, Vec::new(), vec![0x00, 0x01, 0xff]] {
938            assert_eq!(HhdUcData(challenge).decode(), None);
939        }
940    }
941
942    #[test]
943    fn kontoart_ranges() {
944        let class = AccountClass::from_account_type;
945        assert_eq!(class(1), Some(AccountClass::Checking));
946        assert_eq!(class(9), Some(AccountClass::Checking));
947        assert_eq!(class(10), Some(AccountClass::Savings));
948        assert_eq!(class(35), Some(AccountClass::Depot));
949        assert_eq!(class(99), Some(AccountClass::Other));
950        assert_eq!(class(0), None);
951        assert_eq!(class(100), None);
952    }
953
954    fn class(kontoart: Option<u8>, jobs: &[&str]) -> Option<(AccountClass, ClassSource)> {
955        classify(kontoart, |job| jobs.contains(&job))
956    }
957
958    #[test]
959    fn kontoart_wins_over_allowed_jobs() {
960        assert_eq!(
961            class(Some(1), &["HKWPD"]),
962            Some((AccountClass::Checking, ClassSource::Kontoart))
963        );
964        assert_eq!(
965            class(Some(30), &["HKSAL"]),
966            Some((AccountClass::Depot, ClassSource::Kontoart))
967        );
968    }
969
970    #[test]
971    fn no_kontoart_hkwpd_only_is_depot() {
972        assert_eq!(
973            class(None, &["HKWPD", "HKPRO"]),
974            Some((AccountClass::Depot, ClassSource::AllowedJobs))
975        );
976    }
977
978    #[test]
979    fn no_kontoart_hkwpd_with_account_jobs_is_not_depot() {
980        for other in ["HKSAL", "HKKAZ", "HKCAZ"] {
981            assert_eq!(class(None, &["HKWPD", other]), None, "{other}");
982        }
983    }
984
985    #[test]
986    fn nothing_known_is_unclassified() {
987        assert_eq!(class(None, &[]), None);
988        assert_eq!(class(None, &["HKSAL"]), None);
989        // Out of range counts as no Kontoart.
990        assert_eq!(class(Some(0), &[]), None);
991        assert_eq!(
992            class(Some(0), &["HKWPD"]),
993            Some((AccountClass::Depot, ClassSource::AllowedJobs))
994        );
995    }
996
997    #[test]
998    fn account_key_is_normalised() {
999        let k = AccountKey::national(" 12345678", "0000000301", Some("")).unwrap();
1000        assert_eq!(
1001            k,
1002            AccountKey::National {
1003                blz: Blz::new("12345678"),
1004                number: "301".into(),
1005                subaccount: None,
1006            }
1007        );
1008        assert_eq!(k, AccountKey::national("12345678", "301", None).unwrap());
1009        assert_eq!(
1010            AccountKey::national("12345678", "000", Some(" 01 ")).unwrap(),
1011            AccountKey::National {
1012                blz: Blz::new("12345678"),
1013                number: "0".into(),
1014                subaccount: Some("01".into()),
1015            }
1016        );
1017        assert_eq!(AccountKey::national("", "301", None), None);
1018        assert_eq!(AccountKey::national("12345678", " ", None), None);
1019        assert_eq!(
1020            AccountKey::iban("de00 1234 5678 0000 0003 01", Some("")).unwrap(),
1021            AccountKey::Iban {
1022                iban: Iban::new("DE00123456780000000301"),
1023                subaccount: None,
1024            }
1025        );
1026        assert_eq!(AccountKey::iban("", None), None);
1027        // Same IBAN and number, another subaccount: another account.
1028        assert_ne!(
1029            k,
1030            AccountKey::national("12345678", "301", Some("01")).unwrap()
1031        );
1032    }
1033
1034    #[test]
1035    fn account_key_string_round_trips() {
1036        let keys = [
1037            (
1038                AccountKey::national("12345678", "0301", None),
1039                "12345678/301",
1040            ),
1041            (
1042                AccountKey::national("12345678", "301", Some("01")),
1043                "12345678/301/01",
1044            ),
1045            (
1046                AccountKey::national("12345678", "30/1", Some("A/B")),
1047                "12345678/30%2F1/A/B",
1048            ),
1049            (
1050                AccountKey::iban("DE00123456780000000301", None),
1051                "iban:DE00123456780000000301",
1052            ),
1053            (
1054                AccountKey::iban("DE00123456780000000301", Some("TOKEN/1")),
1055                "iban:DE00123456780000000301/TOKEN/1",
1056            ),
1057        ];
1058        for (key, text) in keys {
1059            let key = key.unwrap();
1060            assert_eq!(key.to_string(), text);
1061            assert_eq!(text.parse::<AccountKey>().unwrap(), key, "{text}");
1062            let json = serde_json::to_string(&key).unwrap();
1063            assert_eq!(json, format!("\"{text}\""));
1064            assert_eq!(serde_json::from_str::<AccountKey>(&json).unwrap(), key);
1065        }
1066        for bad in [
1067            "",
1068            "12345678",
1069            "12345678/",
1070            "/301",
1071            "12345678/0301",
1072            "12345678/301/",
1073            "iban:",
1074            "iban:de00",
1075        ] {
1076            assert!(bad.parse::<AccountKey>().is_err(), "{bad:?}");
1077        }
1078    }
1079
1080    #[test]
1081    fn account_classes() {
1082        assert_eq!(
1083            AccountClass::from_account_type(1),
1084            Some(AccountClass::Checking)
1085        );
1086        assert_eq!(
1087            AccountClass::from_account_type(10),
1088            Some(AccountClass::Savings)
1089        );
1090        assert_eq!(
1091            AccountClass::from_account_type(39),
1092            Some(AccountClass::Depot)
1093        );
1094        assert_eq!(
1095            AccountClass::from_account_type(55),
1096            Some(AccountClass::CreditCard)
1097        );
1098        assert_eq!(AccountClass::from_account_type(0), None);
1099        assert_eq!(
1100            AccountClass::from_account_type(9),
1101            Some(AccountClass::Checking)
1102        );
1103        assert_eq!(
1104            AccountClass::from_account_type(20),
1105            Some(AccountClass::FixedDeposit)
1106        );
1107        assert_eq!(
1108            AccountClass::from_account_type(49),
1109            Some(AccountClass::Loan)
1110        );
1111        assert_eq!(
1112            AccountClass::from_account_type(60),
1113            Some(AccountClass::FundDepot)
1114        );
1115        assert_eq!(
1116            AccountClass::from_account_type(79),
1117            Some(AccountClass::HomeSavings)
1118        );
1119        assert_eq!(
1120            AccountClass::from_account_type(89),
1121            Some(AccountClass::Insurance)
1122        );
1123        assert_eq!(
1124            AccountClass::from_account_type(99),
1125            Some(AccountClass::Other)
1126        );
1127        assert_eq!(AccountClass::from_account_type(100), None);
1128    }
1129}