Skip to main content

fints_client/jobs/
accounts.rs

1//! The accounts of the UPD as the caller sees them after the login.
2
3use serde::{Deserialize, Serialize};
4use tracing::warn;
5
6use super::JobKind;
7use crate::error::{FinTSError, Result};
8use crate::protocol::{Account, AccountLimit, Upd, UpdAccount};
9use crate::types::{AccountClass, AccountKey, Bic, ClassSource, Currency, Iban, classify};
10
11/// One account of the UPD (HIUPD), ready to run jobs on with
12/// [`AccountInfo::account`].
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub struct AccountInfo {
15    /// The account's identity, stable across logins (see [`AccountKey`]).
16    pub key: AccountKey,
17    /// `None` when the UPD gives none (a depot or card at some banks).
18    pub iban: Option<Iban>,
19    /// The UPD's BIC when it has one, else the bank's.
20    pub bic: Bic,
21    /// Kontonummer, as the bank sent it.
22    pub number: Option<String>,
23    /// Unterkontomerkmal, as the bank sent it.
24    pub subaccount: Option<String>,
25    /// Name des Kontoinhabers 1 and 2, those given.
26    pub owner: Vec<String>,
27    pub product_name: Option<String>,
28    pub currency: Option<Currency>,
29    /// Kontoart (HIUPD 6) as the bank sent it; see [`AccountInfo::class`].
30    pub account_type: Option<u8>,
31    /// What kind of account this is, and where the answer comes from:
32    ///
33    /// 1. The Kontoart, by the ranges of the FinTS Formals data dictionary
34    ///    ("Kontoart"): [`ClassSource::Kontoart`].
35    /// 2. With no Kontoart (or one outside 1-99): a depot when the UPD
36    ///    allows HKWPD and none of HKSAL, HKKAZ, HKCAZ:
37    ///    [`ClassSource::AllowedJobs`].
38    /// 3. Otherwise `None`: the library does not guess a checking account.
39    ///
40    /// `product_name` and `account_type` stay as the bank sent them, so a
41    /// caller can reclassify by what only it knows.
42    pub class: Option<(AccountClass, ClassSource)>,
43    /// Kontolimit.
44    pub limit: Option<AccountLimit>,
45    /// The jobs whose order the UPD lists for the account (Erlaubte
46    /// Geschäftsvorfälle), in the order of [`JobKind::ALL`]; transactions
47    /// when it lists HKKAZ or HKCAZ. Empty when it lists none.
48    pub allowed: Vec<JobKind>,
49}
50
51impl AccountInfo {
52    /// The entries of `upd`, with `bank_bic` where the UPD has no BIC. An
53    /// entry with neither account number nor IBAN is left out (logged).
54    pub(crate) fn from_upd(upd: &Upd, bank_bic: &Bic) -> Vec<AccountInfo> {
55        upd.accounts()
56            .iter()
57            .filter_map(|a| {
58                let info = Self::from_upd_account(a, bank_bic);
59                if info.is_none() {
60                    warn!("[FinTS] A UPD account has neither number nor IBAN; left out");
61                }
62                info
63            })
64            .collect()
65    }
66
67    fn from_upd_account(a: &UpdAccount, bank_bic: &Bic) -> Option<AccountInfo> {
68        let lists = |code: &str| a.allowed.keys().any(|c| c.as_str() == code);
69        Some(AccountInfo {
70            key: a.key()?,
71            iban: a.iban.clone(),
72            bic: a.bic.clone().unwrap_or_else(|| bank_bic.clone()),
73            number: a.account_number.clone(),
74            subaccount: a.sub_account.clone(),
75            owner: a.owner.clone(),
76            product_name: a.product_name.clone(),
77            currency: a.currency.clone(),
78            account_type: a.account_type,
79            class: classify(a.account_type, lists),
80            limit: a.limit.clone(),
81            allowed: JobKind::ALL
82                .into_iter()
83                .filter(|j| j.codes().iter().any(|c| lists(c)))
84                .collect(),
85        })
86    }
87
88    /// May the user run `job` on this account, by the UPD? `true` when the
89    /// UPD lists no orders at all (nothing is known), else only for a
90    /// listed one. Information only: the jobs never check it.
91    pub fn allows(&self, job: JobKind) -> bool {
92        self.allowed.is_empty() || self.allowed.contains(&job)
93    }
94
95    /// Whether this is a securities depot by [`AccountInfo::class`].
96    pub fn is_depot(&self) -> bool {
97        matches!(self.class, Some((AccountClass::Depot, _)))
98    }
99
100    /// The account to run jobs on: by IBAN with the national parts of the
101    /// UPD, or nationally (number, subaccount, BLZ) without an IBAN.
102    /// Fails when the BIC is empty, or for an account without IBAN whose
103    /// key has no BLZ.
104    pub fn account(&self) -> Result<Account> {
105        let bic = self.bic.as_str();
106        match (&self.iban, &self.key) {
107            (Some(iban), AccountKey::National { blz, .. }) => {
108                let number = self.number.as_deref().unwrap_or_default();
109                Ok(Account::new(iban.as_str(), bic)?.with_national(
110                    number,
111                    self.subaccount.as_deref(),
112                    blz,
113                ))
114            }
115            (Some(iban), AccountKey::Iban { .. }) => {
116                Ok(Account::new(iban.as_str(), bic)?.with_subaccount(self.subaccount.as_deref()))
117            }
118            (None, AccountKey::National { blz, .. }) => Account::national(
119                self.number.as_deref().unwrap_or_default(),
120                self.subaccount.as_deref(),
121                blz,
122                bic,
123            ),
124            (None, AccountKey::Iban { .. }) => Err(FinTSError::Dialog(
125                "the account has neither IBAN nor bank code".into(),
126            )),
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::codec::wire::tokenize;
135
136    fn infos(hiupd: &str) -> Vec<AccountInfo> {
137        let upd = Upd::from_segments(
138            &tokenize(format!("HIUPA:5:4:4+USER0001+1+0'{hiupd}").as_bytes()).unwrap(),
139        )
140        .unwrap();
141        AccountInfo::from_upd(&upd, &Bic::new("TESTDEFFXXX"))
142    }
143
144    /// A clearing account and its depot under one IBAN and number, told
145    /// apart by the subaccount; a card without IBAN; an entry by IBAN only.
146    #[test]
147    fn upd_entries_become_account_infos() {
148        let a = infos(
149            "HIUPD:6:6:4+0000000301::280:12345678+DE00123456780000000301+CUST0001+1+EUR+Erika Beispiel++Girokonto+T:1000,:EUR+HKSAL:1+HKCAZ:1'\
150             HIUPD:7:6:4+0000000301:01:280:12345678+DE00123456780000000301+CUST0001++EUR+Erika Beispiel++Depot++HKWPD:1'\
151             HIUPD:8:6:4+4111000000000001:CARD01:280:12345678++CUST0001+50+EUR+Erika Beispiel++Karte++DKKKU:1'\
152             HIUPD:9:6:4++DE00123456780000000999+CUST0001+10+EUR+Erika Beispiel++Tagesgeld++HKSAL:1'",
153        );
154        assert_eq!(a.len(), 4);
155        assert_eq!(a[0].key.to_string(), "12345678/301");
156        assert_eq!(
157            a[0].class,
158            Some((AccountClass::Checking, ClassSource::Kontoart))
159        );
160        assert_eq!(a[0].allowed, [JobKind::Balance, JobKind::Transactions]);
161        assert!(a[0].limit.is_some());
162        assert_eq!(a[0].bic.as_str(), "TESTDEFFXXX");
163        assert_eq!(a[1].key.to_string(), "12345678/301/01");
164        assert_ne!(a[0].key, a[1].key);
165        assert!(a[1].is_depot());
166        assert!(!a[1].allows(JobKind::Balance));
167        assert_eq!(a[2].key.to_string(), "12345678/4111000000000001/CARD01");
168        assert!(a[2].allowed.is_empty(), "an order this client does not run");
169        assert_eq!(a[3].key.to_string(), "iban:DE00123456780000000999");
170
171        let clearing = a[0].account().unwrap();
172        assert_eq!(clearing.iban(), "DE00123456780000000301");
173        assert_eq!(clearing.subaccount(), None);
174        let depot = a[1].account().unwrap();
175        assert_eq!(depot.subaccount(), Some("01"));
176        let card = a[2].account().unwrap();
177        assert_eq!(card.iban(), "");
178        assert_eq!(card.account_number(), Some("4111000000000001"));
179        assert_eq!(a[3].account().unwrap().iban(), "DE00123456780000000999");
180    }
181
182    /// Each entry's account finds its own entry again, also when they share
183    /// IBAN and number; an account built by hand from the shared IBAN finds
184    /// the entry without subaccount.
185    #[test]
186    fn accounts_find_their_own_upd_entry() {
187        let hiupd = "HIUPD:6:6:4+0000000301::280:12345678+DE00123456780000000301+CUST0001+1+EUR+Erika Beispiel++Girokonto++HKSAL:1+HKCAZ:1'\
188             HIUPD:7:6:4+0000000301:01:280:12345678+DE00123456780000000301+CUST0001++EUR+Erika Beispiel++Depot++HKWPD:1'\
189             HIUPD:9:6:4++DE00123456780000000999+CUST0001+10+EUR+Erika Beispiel++Tagesgeld++HKSAL:1'";
190        let upd = Upd::from_segments(
191            &tokenize(format!("HIUPA:5:4:4+USER0001+1+0'{hiupd}").as_bytes()).unwrap(),
192        )
193        .unwrap();
194        for info in AccountInfo::from_upd(&upd, &Bic::new("TESTDEFFXXX")) {
195            let found = upd.find(&info.account().unwrap()).expect("found");
196            assert_eq!(found.key().as_ref(), Some(&info.key));
197        }
198        let by_hand = Account::new("DE00123456780000000301", "TESTDEFFXXX").unwrap();
199        assert_eq!(
200            upd.find(&by_hand).and_then(UpdAccount::key),
201            infos(hiupd).first().map(|i| i.key.clone())
202        );
203    }
204}