Skip to main content

fints_client/jobs/
capabilities.rs

1//! What a bank offers per account, from the BPD, the UPD and the versions
2//! we implement, without sending anything.
3//!
4//! Only the BPD blocks a job (no common version, see [`Support`]). The UPD
5//! allowance is shown, never enforced: the bank's answer decides.
6
7use serde::{Deserialize, Serialize};
8
9use super::{Format, StatementFormat, choose_statement_format, find_upd_account};
10use crate::protocol::{
11    Account, Allowance, BankParams, TanOverrides, UpdAccount, VersionMismatch, order_tan,
12};
13use crate::segments::Order;
14use crate::types::{AccountKey, Iban, SegmentType};
15
16/// The jobs [`Capabilities`] reports on.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[non_exhaustive]
19pub enum JobKind {
20    Balance,
21    Transactions,
22    Holdings,
23    DepotTransactions,
24    Transfer,
25    InstantTransfer,
26    InstantStatus,
27}
28
29impl JobKind {
30    /// Every job, in the order of [`Capabilities`].
31    pub const ALL: [JobKind; 7] = [
32        JobKind::Balance,
33        JobKind::Transactions,
34        JobKind::Holdings,
35        JobKind::DepotTransactions,
36        JobKind::Transfer,
37        JobKind::InstantTransfer,
38        JobKind::InstantStatus,
39    ];
40
41    /// The order codes that run the job: HKKAZ and HKCAZ for transactions.
42    pub(crate) fn codes(self) -> &'static [&'static str] {
43        match self {
44            JobKind::Transactions => &["HKKAZ", "HKCAZ"],
45            JobKind::Balance => &["HKSAL"],
46            JobKind::Holdings => &["HKWPD"],
47            JobKind::DepotTransactions => &["HKWDU"],
48            JobKind::Transfer => &["HKCCS"],
49            JobKind::InstantTransfer => &["HKIPZ"],
50            JobKind::InstantStatus => &["HKIPS"],
51        }
52    }
53
54    fn order(self) -> Order {
55        match self {
56            JobKind::Balance => Order::Balance,
57            JobKind::Transactions => Order::Transactions,
58            JobKind::Holdings => Order::Holdings,
59            JobKind::DepotTransactions => Order::DepotTransactions,
60            JobKind::Transfer => Order::Transfer,
61            JobKind::InstantTransfer => Order::InstantTransfer,
62            JobKind::InstantStatus => Order::InstantStatus,
63        }
64    }
65}
66
67/// Whether the BPD lets us send a job.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
69#[non_exhaustive]
70pub enum Support {
71    /// The job would be sent as `code` in `version`. For
72    /// [`JobKind::Transactions`] `code` is `HKCAZ` or `HKKAZ`, whichever
73    /// [`transactions`](super::transactions) with `Format::Auto` would
74    /// use, and `formats` lists the camt formats the bank offers (empty
75    /// for MT940 and every other job).
76    Available {
77        code: &'static str,
78        version: u16,
79        formats: Vec<String>,
80        /// The bank's storage period in days (Speicherzeitraum of
81        /// HIKAZS/HICAZS) for [`JobKind::Transactions`]; `None` for every
82        /// other job or when the BPD gives none. A statement range that
83        /// starts earlier is clamped by [`transactions`](super::transactions).
84        days_stored: Option<u32>,
85    },
86    /// The BPD has no parameter segment for the job.
87    NotOffered,
88    /// The BPD offers versions, none of which we implement.
89    VersionMismatch {
90        offered: Vec<u16>,
91        implemented: Vec<u16>,
92    },
93    /// No BPD is known (no dialog has run, nothing cached).
94    NoBpd,
95}
96
97/// One job on one account.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
99pub struct JobCapability {
100    pub job: JobKind,
101    pub support: Support,
102    /// What the UPD says about the order in `support` (for transactions,
103    /// the order that would be used). Information only: `No` does not stop
104    /// the job. `Unknown` also when the UPD is not known, see
105    /// [`SessionState::capabilities`](crate::SessionState::capabilities).
106    pub upd: Allowance,
107    /// Whether the order needs a TAN: HIPINS, learned codes and the
108    /// caller's overrides. `None` when nothing says.
109    pub tan_required: Option<bool>,
110}
111
112/// The jobs of one account.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
114pub struct AccountCapabilities {
115    /// The UPD entry's key when the UPD names the account (the same as
116    /// [`AccountInfo::key`](super::AccountInfo::key)), else the key the
117    /// account's own number and BLZ, or IBAN, give.
118    pub key: AccountKey,
119    /// Whether the UPD names the account.
120    pub in_upd: bool,
121    /// One entry per [`JobKind::ALL`].
122    pub jobs: Vec<JobCapability>,
123    /// The payee check (VoP): `None` when the BPD has no HIVPPS.
124    pub payee_check: Option<VopSupport>,
125}
126
127/// What the BPD says about the payee check (HIVPPS).
128#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
129pub struct VopSupport {
130    /// "VOP-pflichtige Zahlungsverkehrsaufträge": the orders that go with
131    /// an HKVPP.
132    pub required_for: Vec<SegmentType>,
133}
134
135impl AccountCapabilities {
136    /// The entry for `job`.
137    pub fn job(&self, job: JobKind) -> Option<&JobCapability> {
138        self.jobs.iter().find(|j| j.job == job)
139    }
140}
141
142/// What the bank offers, per account.
143///
144/// Built without a dialog from a stored [`SessionState`](crate::SessionState),
145/// or from an open [`Dialog`](super::Dialog). A bank that sends the UPD for
146/// one dialog only (version 0) leaves no UPD in the session state: from
147/// there the accounts must be named by the caller and every allowance is
148/// `Unknown`; the dialog knows the UPD.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
150pub struct Capabilities {
151    pub accounts: Vec<AccountCapabilities>,
152}
153
154impl Capabilities {
155    /// Reports `accounts`, or the UPD's accounts when `accounts` is empty.
156    pub(crate) fn build(
157        params: &BankParams,
158        overrides: &TanOverrides,
159        accounts: &[Account],
160    ) -> Capabilities {
161        let accounts = if accounts.is_empty() {
162            params
163                .upd()
164                .map(|u| u.accounts().iter().collect::<Vec<_>>())
165                .unwrap_or_default()
166                .into_iter()
167                .filter_map(|a| Some(account_capabilities(params, overrides, a.key()?, Some(a))))
168                .collect()
169        } else {
170            accounts
171                .iter()
172                .map(|a| {
173                    let upd = find_upd_account(params, a);
174                    let key = upd.and_then(UpdAccount::key).unwrap_or_else(|| key_of(a));
175                    account_capabilities(params, overrides, key, upd)
176                })
177                .collect()
178        };
179        Capabilities { accounts }
180    }
181}
182
183/// The key of an account the UPD does not name: number, subaccount and
184/// BLZ, else IBAN and subaccount.
185fn key_of(a: &Account) -> AccountKey {
186    let sub = a.subaccount();
187    a.blz()
188        .zip(a.account_number())
189        .and_then(|(blz, number)| AccountKey::national(blz, number, sub))
190        .or_else(|| AccountKey::iban(a.iban(), sub))
191        .unwrap_or_else(|| AccountKey::Iban {
192            iban: Iban::new(a.iban()),
193            subaccount: None,
194        })
195}
196
197fn account_capabilities(
198    params: &BankParams,
199    overrides: &TanOverrides,
200    key: AccountKey,
201    upd: Option<&UpdAccount>,
202) -> AccountCapabilities {
203    let allowance = |code: &str| match (params.upd(), upd) {
204        (Some(u), Some(a)) => u.allows(a, code),
205        _ => Allowance::Unknown,
206    };
207    let jobs = JobKind::ALL
208        .iter()
209        .map(|&job| {
210            let mut order = job.order();
211            if job == JobKind::Transactions
212                && matches!(
213                    choose_statement_format(params, Format::Auto, || allowance("HKCAZ")),
214                    Ok(StatementFormat::Camt)
215                )
216            {
217                order = Order::Camt;
218            }
219            let support = match params.order_version(order) {
220                Ok(version) => Support::Available {
221                    code: order.code(),
222                    version,
223                    formats: if order == Order::Camt {
224                        params
225                            .bpd()
226                            .map(|b| b.camt_formats().to_vec())
227                            .unwrap_or_default()
228                    } else {
229                        Vec::new()
230                    },
231                    days_stored: (job == JobKind::Transactions)
232                        .then(|| params.days_stored(order))
233                        .flatten(),
234                },
235                Err(crate::FinTSError::VersionMismatch(VersionMismatch {
236                    offered,
237                    implemented,
238                    ..
239                })) => {
240                    if offered.is_empty() {
241                        Support::NotOffered
242                    } else {
243                        Support::VersionMismatch {
244                            offered,
245                            implemented,
246                        }
247                    }
248                }
249                Err(_) => Support::NoBpd,
250            };
251            let code = order.code();
252            let tan = order_tan(
253                &SegmentType::new(code),
254                true,
255                params.bpd().and_then(|b| b.tan_required(code)),
256                overrides,
257                &params.tan_required_learned,
258            );
259            JobCapability {
260                job,
261                support,
262                upd: allowance(code),
263                tan_required: match tan.reason {
264                    crate::protocol::TanReason::Unlisted => None,
265                    _ => Some(tan.hktan),
266                },
267            }
268        })
269        .collect();
270    AccountCapabilities {
271        key,
272        in_upd: upd.is_some(),
273        jobs,
274        payee_check: params.bpd().and_then(|b| b.vop()).map(|v| VopSupport {
275            required_for: v.required_for.clone(),
276        }),
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use crate::codec::wire::tokenize;
284    use crate::protocol::{TanOverride, TanOverrides};
285    use crate::session::SessionState;
286    use crate::types::{Blz, SystemId, UserId};
287
288    const IBAN: &str = "DE00123456781234567890";
289
290    fn params(bpd: &str, upd: &str) -> BankParams {
291        let mut p = BankParams::new();
292        if !bpd.is_empty() {
293            let wire = format!("HIBPA:1:3:4+1+280:1+Bank+1+1+300'{bpd}");
294            p.set_bpd(tokenize(wire.as_bytes()).unwrap());
295        }
296        if !upd.is_empty() {
297            p.set_upd(tokenize(upd.as_bytes()).unwrap());
298        }
299        p
300    }
301
302    fn upd(version: u8, usage: u8, allowed: &str) -> String {
303        format!(
304            "HIUPA:5:4:4+USER0001+{version}+{usage}'HIUPD:6:6:4+1234567890::280:12345678+{IBAN}+CUST0001+1+EUR+Erika Beispiel++Girokonto++{allowed}'"
305        )
306    }
307
308    fn account() -> Account {
309        Account::new(IBAN, "TESTDEFFXXX").unwrap()
310    }
311
312    fn caps(p: &BankParams, accounts: &[Account]) -> Capabilities {
313        Capabilities::build(p, &TanOverrides::default(), accounts)
314    }
315
316    fn of(c: &Capabilities, job: JobKind) -> &JobCapability {
317        c.accounts[0].job(job).unwrap()
318    }
319
320    const BPD: &str = "HISALS:2:6:4+1+1+0'HIKAZS:3:7:4+1+1+0'HICAZS:4:1:4+1+1+0+450:N:N:urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.02'HIWPDS:5:9:4+1+1+0'";
321
322    #[test]
323    fn closed_upd_steers_to_mt940_and_shows_no() {
324        let p = params(BPD, &upd(5, 0, "HKSAL:1+HKKAZ:1"));
325        let c = caps(&p, &[]);
326        assert_eq!(c.accounts.len(), 1);
327        assert!(c.accounts[0].in_upd);
328        let bal = of(&c, JobKind::Balance);
329        assert_eq!(bal.upd, Allowance::Yes);
330        assert_eq!(
331            bal.support,
332            Support::Available {
333                code: "HKSAL",
334                version: 6,
335                formats: vec![],
336                days_stored: None
337            }
338        );
339        // HKCAZ is offered but not listed in a closed UPD: MT940.
340        let tx = of(&c, JobKind::Transactions);
341        assert_eq!(tx.upd, Allowance::Yes);
342        assert!(matches!(
343            &tx.support,
344            Support::Available {
345                code: "HKKAZ",
346                version: 7,
347                ..
348            }
349        ));
350        // Version 9 only: we do not implement it. UPD `No` is shown.
351        let h = of(&c, JobKind::Holdings);
352        assert_eq!(h.upd, Allowance::No);
353        assert_eq!(
354            h.support,
355            Support::VersionMismatch {
356                offered: vec![9],
357                implemented: Order::Holdings.implemented().to_vec()
358            }
359        );
360        assert_eq!(of(&c, JobKind::InstantStatus).support, Support::NotOffered);
361    }
362
363    #[test]
364    fn open_upd_prefers_camt_with_its_formats() {
365        let p = params(BPD, &upd(5, 1, "HKSAL:1"));
366        let c = caps(&p, &[]);
367        let tx = of(&c, JobKind::Transactions);
368        assert_eq!(tx.upd, Allowance::Unknown);
369        let Support::Available {
370            code,
371            version,
372            formats,
373            days_stored,
374        } = &tx.support
375        else {
376            panic!("{tx:?}")
377        };
378        assert_eq!((*code, *version), ("HKCAZ", 1));
379        assert_eq!(*days_stored, Some(450));
380        assert_eq!(formats.len(), 1);
381        assert!(formats[0].contains("camt.052"));
382    }
383
384    #[test]
385    fn named_accounts_unknown_to_the_upd_are_unknown() {
386        let p = params(BPD, &upd(5, 0, "HKSAL:1"));
387        let other = Account::new("DE00123456780000000001", "TESTDEFFXXX").unwrap();
388        let c = caps(&p, &[other]);
389        assert!(!c.accounts[0].in_upd);
390        assert_eq!(of(&c, JobKind::Balance).upd, Allowance::Unknown);
391    }
392
393    #[test]
394    fn dialog_only_upd_is_in_the_dialog_not_the_session() {
395        let p = params(BPD, &upd(0, 0, "HKSAL:1"));
396        // The dialog knows the UPD.
397        assert_eq!(of(&caps(&p, &[]), JobKind::Holdings).upd, Allowance::No);
398        // The stored session state does not: no accounts of its own, and
399        // `Unknown` for the ones the caller names.
400        let state = SessionState::capture(
401            &Blz::new("12345678"),
402            &UserId::new("USER0001"),
403            &SystemId::new("0"),
404            &p,
405        );
406        assert!(state.capabilities(&[]).accounts.is_empty());
407        let c = state.capabilities(&[account()]);
408        assert!(!c.accounts[0].in_upd);
409        assert_eq!(of(&c, JobKind::Holdings).upd, Allowance::Unknown);
410        assert!(matches!(
411            of(&c, JobKind::Balance).support,
412            Support::Available { version: 6, .. }
413        ));
414    }
415
416    #[test]
417    fn stored_upd_gives_the_same_answer_as_the_dialog() {
418        let p = params(BPD, &upd(5, 0, "HKSAL:1"));
419        let state = SessionState::capture(
420            &Blz::new("12345678"),
421            &UserId::new("USER0001"),
422            &SystemId::new("0"),
423            &p,
424        );
425        assert_eq!(state.capabilities(&[]), caps(&p, &[]));
426    }
427
428    #[test]
429    fn no_bpd_refuses_everything_and_shows_the_upd() {
430        let p = params("", &upd(5, 0, "HKSAL:1"));
431        let c = caps(&p, &[]);
432        for j in &c.accounts[0].jobs {
433            assert_eq!(j.support, Support::NoBpd, "{:?}", j.job);
434        }
435        assert_eq!(of(&c, JobKind::Balance).upd, Allowance::Yes);
436        // No BPD and no UPD: nothing to report unless the caller names accounts.
437        let p = params("", "");
438        assert!(caps(&p, &[]).accounts.is_empty());
439        assert_eq!(
440            caps(&p, &[account()]).accounts[0].jobs.len(),
441            JobKind::ALL.len()
442        );
443    }
444
445    #[test]
446    fn tan_requirement_from_learning_and_overrides() {
447        let mut p = params(BPD, &upd(5, 1, "HKSAL:1"));
448        assert_eq!(of(&caps(&p, &[]), JobKind::Balance).tan_required, None);
449        p.tan_required_learned.insert(SegmentType::new("HKSAL"));
450        assert_eq!(
451            of(&caps(&p, &[]), JobKind::Balance).tan_required,
452            Some(true)
453        );
454        let overrides: TanOverrides = [(SegmentType::new("HKSAL"), TanOverride::Never)]
455            .into_iter()
456            .collect();
457        let c = Capabilities::build(&p, &overrides, &[]);
458        assert_eq!(of(&c, JobKind::Balance).tan_required, Some(false));
459    }
460}