Skip to main content

fints_client/
jobs.rs

1//! Jobs as steps (docs/jobs-step-design.md).
2//!
3//! Every job returns a [`Step`]: `Done` with the value and the bank's
4//! notices, or `NeedTan` with a [`TanChallenge`] and a typed [`Resume`]
5//! ticket; a [`transfer`] may also pause on its payee check
6//! (`NeedVopConfirmation`, `VopPending`). The caller answers on the
7//! [`Dialog`]: [`Dialog::submit_tan`] for a typed TAN, [`Dialog::poll`]
8//! (one status request per call) for a decoupled confirmation or an
9//! unfinished payee check, [`Dialog::confirm_vop`] for a payee check
10//! result, or [`Dialog::cancel`]. The library never sleeps and never calls
11//! back: the caller waits the bank's `first_wait` / `next_wait` between
12//! polls and decides when to give up.
13//!
14//! ```rust,no_run
15//! use fints_client::jobs::{self, BankClient, Credentials, Step, TanKind};
16//! # async fn example(client: BankClient, creds: Credentials,
17//! #     state: fints_client::SessionState) -> fints_client::Result<()> {
18//! let (mut dialog, mut step) = jobs::open(&client, &creds, &state).await?;
19//! let opened = loop {
20//!     match step {
21//!         Step::Done(done) => break done.value,
22//!         Step::NeedTan(challenge, resume) => match challenge.kind {
23//!             TanKind::Decoupled { .. } => {
24//!                 // sleep first_wait / next_wait, then:
25//!                 step = dialog.poll(resume).await?;
26//!             }
27//!             TanKind::Typed { .. } => {
28//!                 let tan = "123456"; // ask the user
29//!                 step = dialog.submit_tan(resume, tan).await?;
30//!             }
31//!         },
32//!         // Only a transfer pauses on its payee check.
33//!         Step::NeedVopConfirmation(_, resume) => step = dialog.confirm_vop(resume).await?,
34//!         Step::VopPending(_, resume) => step = dialog.poll(resume).await?,
35//!     }
36//! };
37//! # let _ = opened;
38//! let state = dialog.end().await?; // persist (encrypted)
39//! # let _ = state;
40//! # Ok(())
41//! # }
42//! ```
43
44use std::marker::PhantomData;
45use std::time::Duration;
46
47use jiff::{
48    Timestamp,
49    civil::{Date, DateTime},
50};
51use serde::{Deserialize, Serialize};
52use tracing::{debug, info, warn};
53
54use crate::banks::{BankConfig, BookingIdSource, InitMode};
55use crate::error::{FinTSError, Result};
56use crate::formats::mt940::{parse_mt940, parse_mt942};
57use crate::protocol::{
58    self, Account, Allowance, BankParams, InitResult, Open, Response, Segment, UpdAccount,
59};
60use crate::return_code::{Category, ClientWarning, Kind, Notice, NoticeDialog, ReturnCode};
61use crate::segments::Order;
62use crate::segments::read::{extract_camt_data, extract_mt940_data, parse_hiwdu, parse_hiwpd};
63use crate::session::SessionState;
64use crate::transport::SharedTransport;
65use crate::types::*;
66
67// ═══════════════════════════════════════════════════════════════════════════════
68// Client and credentials
69// ═══════════════════════════════════════════════════════════════════════════════
70
71/// A bank to talk to: its configuration (URL, BLZ, TAN overrides), the
72/// product ID registered with the Deutsche Kreditwirtschaft, and the
73/// transport (default: HTTPS with feature `http`).
74#[derive(Clone)]
75pub struct BankClient {
76    config: BankConfig,
77    product_id: ProductId,
78    transport: Option<SharedTransport>,
79    quirks: Option<std::sync::Arc<dyn Fn() -> crate::quirks::QuirkChain + Send + Sync>>,
80    now: Option<DateTime>,
81}
82
83impl BankClient {
84    pub fn new(config: BankConfig, product_id: ProductId) -> Self {
85        Self {
86            config,
87            product_id,
88            transport: None,
89            quirks: None,
90            now: None,
91        }
92    }
93
94    /// Pin the local time for everything the library reads from the clock:
95    /// the HNSHK and HNVSK stamps, the pain.001 `CreDtTm` and the date of the
96    /// day (the storage-period clamp of [`transactions`]) in this client's
97    /// dialogs. For tests and replays, which must not depend on the real
98    /// clock; the default is the system's local time. Paused-dialog timing
99    /// (`expires_at`, `not_before`) stays on real timestamps.
100    pub fn with_now(mut self, now: DateTime) -> Self {
101        self.now = Some(now);
102        self
103    }
104
105    /// The pinned local time ([`BankClient::with_now`]), else the system's.
106    /// A consumer that computes date ranges uses it, so its tests can pin
107    /// the clock the same way.
108    pub fn now(&self) -> DateTime {
109        self.now
110            .unwrap_or_else(|| jiff::ZonedDateTime::now().datetime())
111    }
112
113    /// The date of [`BankClient::now`].
114    pub fn today(&self) -> Date {
115        self.now().date()
116    }
117
118    /// Send through `transport` instead of the default.
119    pub fn with_transport(mut self, transport: SharedTransport) -> Self {
120        self.transport = Some(transport);
121        self
122    }
123
124    /// Repair the bank's answers with the chain `quirks` builds (one per
125    /// dialog) instead of the default chain.
126    pub fn with_quirks(
127        mut self,
128        quirks: impl Fn() -> crate::quirks::QuirkChain + Send + Sync + 'static,
129    ) -> Self {
130        self.quirks = Some(std::sync::Arc::new(quirks));
131        self
132    }
133
134    pub fn config(&self) -> &BankConfig {
135        &self.config
136    }
137
138    /// The user ID as the bank gets it: completed by the profile's rule.
139    pub(crate) fn effective_user_id(&self, user_id: &UserId) -> UserId {
140        let Some(rule) = &self.config.profile.user_id else {
141            return user_id.clone();
142        };
143        match rule.apply(user_id.as_str()) {
144            std::borrow::Cow::Borrowed(_) => user_id.clone(),
145            std::borrow::Cow::Owned(full) => {
146                debug!(
147                    "[FinTS] User ID completed by the {} profile: {} -> {}",
148                    self.config.profile.id,
149                    "*".repeat(user_id.as_str().chars().count()),
150                    "*".repeat(full.chars().count()),
151                );
152                UserId::new(full)
153            }
154        }
155    }
156
157    fn new_dialog(&self, creds: &Credentials) -> Result<protocol::Dialog<protocol::New>> {
158        let c = &self.config;
159        let dialog = protocol::Dialog::new(
160            c.url.as_str(),
161            &c.blz,
162            &self.effective_user_id(&creds.user_id),
163            &creds.pin,
164            &self.product_id,
165        )?
166        .with_tan_overrides(c.profile.tan_overrides.clone());
167        let dialog = match &self.quirks {
168            Some(q) => dialog.with_quirks(q()),
169            None => dialog,
170        }
171        .with_now(self.now);
172        Ok(match &self.transport {
173            Some(t) => dialog.with_transport(t.clone()),
174            None => dialog,
175        })
176    }
177}
178
179impl std::fmt::Debug for BankClient {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        f.debug_struct("BankClient")
182            .field("config", &self.config)
183            .finish_non_exhaustive()
184    }
185}
186
187/// User ID and PIN. `Debug` shows neither.
188#[derive(Clone)]
189pub struct Credentials {
190    pub user_id: UserId,
191    pub pin: Pin,
192}
193
194impl Credentials {
195    pub fn new(user_id: UserId, pin: Pin) -> Self {
196        Self { user_id, pin }
197    }
198}
199
200impl std::fmt::Debug for Credentials {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        f.write_str("Credentials(****)")
203    }
204}
205
206// ═══════════════════════════════════════════════════════════════════════════════
207// Step, challenge, resume ticket
208// ═══════════════════════════════════════════════════════════════════════════════
209
210/// The outcome of one call: the job is done, the bank wants a TAN, or a
211/// transfer's payee check needs the user or more time.
212#[must_use]
213#[derive(Debug)]
214pub enum Step<T> {
215    Done(Completed<T>),
216    /// Answer with [`Dialog::submit_tan`] (typed) or [`Dialog::poll`]
217    /// (decoupled), or drop the job with [`Dialog::cancel`].
218    NeedTan(TanChallenge, Resume<T>),
219    /// The payee check is not a clean match: show the result (and the
220    /// bank's explanation), then [`Dialog::confirm_vop`] or
221    /// [`Dialog::cancel`].
222    NeedVopConfirmation(VopConfirmation, Resume<T>),
223    /// The payee check is still running: [`Dialog::poll`] at or after
224    /// `not_before`, or [`Dialog::cancel`].
225    VopPending(VopWait, Resume<T>),
226}
227
228/// A finished job: its value and every notice of every message it sent,
229/// those before a `NeedTan` included (return-codes design §4).
230#[derive(Debug, Clone)]
231pub struct Completed<T> {
232    pub value: T,
233    pub notices: Vec<Notice>,
234}
235
236/// The ticket to resume the job a step paused. The dialog checks it
237/// against its pending job ([`FinTSError::WrongResume`]).
238#[derive(Debug)]
239pub struct Resume<T> {
240    ticket: Ticket,
241    _value: PhantomData<fn() -> T>,
242}
243
244/// What a paused job is resumed by: the bank's task reference for a TAN,
245/// a random nonce for the payee check waits (no task reference exists).
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247enum Ticket {
248    Task(TaskReference),
249    Local(u64),
250}
251
252impl Ticket {
253    fn local() -> Self {
254        Self::Local(rand::random())
255    }
256}
257
258/// What a paused job waits for.
259#[derive(Debug, Clone, Serialize, Deserialize)]
260enum Wait {
261    Tan(TanChallenge),
262    VopConfirmation(VopConfirmation),
263    VopPoll(VopWait),
264}
265
266/// What the bank asks the user to do.
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct TanChallenge {
269    /// The bank's text to show.
270    pub challenge: ChallengeText,
271    /// The bank's HITANS "Challenge strukturiert" for the TAN method in
272    /// use (PIN/TAN, data dictionary, DE "Challenge"): when `true`,
273    /// `challenge` may carry the tags `<br> <p> <b> <i> <u> <ul> <ol> <li>
274    /// <a href>`, not nested. When `false` it is plain text.
275    pub challenge_markup: bool,
276    pub kind: TanKind,
277    /// Until when the bank accepts the answer (HITAN "Gültigkeitsdatum und
278    /// -uhrzeit für Challenge"), in the bank's local time as sent; `None`
279    /// when the bank gives none.
280    pub valid_until: Option<DateTime>,
281    /// Decoupled challenges: the earliest time for the next [`Dialog::poll`],
282    /// the time the bank's answer arrived plus the HITANS wait that applies
283    /// (`first_wait` before the first poll, `next_wait` after each further
284    /// 3956). `None` when the bank gives no wait, and for typed challenges.
285    /// It is a wall-clock time and survives freeze and thaw; sleep until it
286    /// instead of for a fixed duration.
287    pub not_before: Option<Timestamp>,
288    /// A transfer's payee check result, to show with the TAN prompt or app
289    /// approval (VoP E.8.1 point 3); `None` for every other job and for a
290    /// transfer without a payee check.
291    pub payee_check: Option<VopResult>,
292    /// Why the challenge came back: the bank rejected the TAN typed for
293    /// it and keeps the order for another one. `None` on the first ask.
294    pub rejected: Option<Box<TanRejected>>,
295}
296
297/// A typed TAN the bank rejected while keeping the order
298/// ([`Dialog::submit_tan`]; docs/jobs-step-design.md §2).
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300pub struct TanRejected {
301    /// The bank's rejection to show, code and text (9941 "TAN ungültig").
302    pub code: ReturnCode,
303    /// Further TANs the bank says it will check before it locks (9360 P1);
304    /// `None` when it does not say.
305    pub attempts_left: Option<u32>,
306    /// Wrong TANs for this order so far, from 1.
307    pub count: u32,
308}
309
310/// How the challenge is answered.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312pub enum TanKind {
313    /// The user types a TAN: [`Dialog::submit_tan`]. `media` is the
314    /// flicker code or photoTAN/QR image to show, if the challenge has one.
315    Typed { media: Option<TanMedia> },
316    /// The user confirms in an app: [`Dialog::poll`]. The waits and the
317    /// poll limit are the bank's HITANS v7 values (`None` when it gives
318    /// none); `polls_done` counts the status requests sent so far.
319    ///
320    /// `auto_polling_allowed`: when `Some(false)` the caller must not call
321    /// [`Dialog::poll`] on a timer. The bank then expects the user to
322    /// trigger each status request (a button, pressing Enter).
323    Decoupled {
324        first_wait: Option<Duration>,
325        next_wait: Option<Duration>,
326        max_polls: Option<u32>,
327        polls_done: u32,
328        auto_polling_allowed: Option<bool>,
329    },
330}
331
332impl TanChallenge {
333    fn from_bank(
334        challenge: &protocol::TanChallenge,
335        params: &BankParams,
336        arrived: Timestamp,
337    ) -> Self {
338        let mut not_before = None;
339        // 3955 alone makes a challenge decoupled; the method does not.
340        let kind = if challenge.decoupled {
341            let p = params.decoupled_params();
342            not_before = not_before_after(arrived, p.wait_before_first_poll);
343            TanKind::Decoupled {
344                first_wait: p.wait_before_first_poll,
345                next_wait: p.wait_before_next_poll,
346                max_polls: p.max_polls,
347                polls_done: 0,
348                auto_polling_allowed: p.auto_polling_allowed,
349            }
350        } else {
351            TanKind::Typed {
352                media: challenge
353                    .challenge_hhduc
354                    .as_ref()
355                    .and_then(HhdUcData::decode),
356            }
357        };
358        Self {
359            challenge: challenge.challenge.clone(),
360            challenge_markup: challenge.challenge_markup || params.challenge_structured(),
361            kind,
362            valid_until: challenge.valid_until,
363            not_before,
364            payee_check: None,
365            rejected: None,
366        }
367    }
368}
369
370/// `arrived` plus the bank's wait; `None` when the bank gives no wait.
371/// Adds `new` to `notices`, skipping a notice already there (same dialog,
372/// code, scope, text and parameters). Every message of an order's TAN and
373/// status rounds can carry the same 3060; the caller sees it once.
374pub(crate) fn extend_notices(notices: &mut Vec<Notice>, new: Vec<Notice>) {
375    for notice in new {
376        if !notices.contains(&notice) {
377            notices.push(notice);
378        }
379    }
380}
381
382fn not_before_after(arrived: Timestamp, wait: Option<Duration>) -> Option<Timestamp> {
383    let wait = jiff::SignedDuration::try_from(wait?).ok()?;
384    arrived.checked_add(wait).ok()
385}
386
387// ═══════════════════════════════════════════════════════════════════════════════
388// Job values
389// ═══════════════════════════════════════════════════════════════════════════════
390
391/// The value of [`open`]: what the login learned and decided.
392#[derive(Debug, Clone)]
393pub struct Opened {
394    /// Accounts of the UPD, in its order.
395    pub accounts: Vec<AccountInfo>,
396    /// TAN methods the BPD offers (buildable HITANS versions).
397    pub tan_methods: Vec<TanMethod>,
398    /// Security functions the bank allows this user (3920).
399    pub allowed_security_functions: Vec<SecurityFunction>,
400    /// The TAN method the login chose (the one the dialog uses, with the
401    /// bank's name for it); `None` for PIN only (999) or a method the BPD
402    /// does not announce. The same as in the session state after
403    /// [`Dialog::end`].
404    pub selected_tan_method: Option<TanMethod>,
405}
406
407/// The value type of a job; implemented for the value of every job.
408pub trait JobValue: sealed::Sealed + Sized {}
409impl JobValue for Opened {}
410impl JobValue for Option<AccountBalance> {}
411impl JobValue for Statement {}
412impl JobValue for Vec<SecurityHolding> {}
413impl JobValue for Vec<DepotTransaction> {}
414impl JobValue for TransferReceipt {}
415impl JobValue for InstantStatus {}
416
417mod sealed {
418    use super::*;
419
420    /// Which job a pending job is.
421    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
422    pub enum Job {
423        Open,
424        Balance,
425        Transactions,
426        Holdings,
427        DepotTransactions,
428        Transfer,
429        InstantStatus,
430    }
431
432    /// A finished job's value, whatever the job.
433    pub enum Value {
434        Opened(Opened),
435        Balance(Option<AccountBalance>),
436        Statement(Statement),
437        Holdings(Vec<SecurityHolding>),
438        DepotTransactions(Vec<DepotTransaction>),
439        Transfer(TransferReceipt),
440        InstantStatus(InstantStatus),
441    }
442
443    pub trait Sealed: Sized {
444        const JOB: Job;
445        fn from_value(value: Value) -> Option<Self>;
446    }
447
448    impl Sealed for Opened {
449        const JOB: Job = Job::Open;
450        fn from_value(value: Value) -> Option<Self> {
451            match value {
452                Value::Opened(v) => Some(v),
453                _ => None,
454            }
455        }
456    }
457
458    impl Sealed for Option<AccountBalance> {
459        const JOB: Job = Job::Balance;
460        fn from_value(value: Value) -> Option<Self> {
461            match value {
462                Value::Balance(v) => Some(v),
463                _ => None,
464            }
465        }
466    }
467}
468
469macro_rules! sealed_value {
470    ($($ty:ty => $job:ident, $variant:ident;)*) => {$(
471        impl Sealed for $ty {
472            const JOB: Job = Job::$job;
473            fn from_value(value: Value) -> Option<Self> {
474                match value {
475                    Value::$variant(v) => Some(v),
476                    _ => None,
477                }
478            }
479        }
480    )*};
481}
482sealed_value! {
483    Statement => Transactions, Statement;
484    Vec<SecurityHolding> => Holdings, Holdings;
485    Vec<DepotTransaction> => DepotTransactions, DepotTransactions;
486    TransferReceipt => Transfer, Transfer;
487    InstantStatus => InstantStatus, InstantStatus;
488}
489use sealed::{Job, Sealed, Value};
490
491mod accounts;
492pub use accounts::AccountInfo;
493mod capabilities;
494pub use capabilities::{
495    AccountCapabilities, Capabilities, JobCapability, JobKind, Support, VopSupport,
496};
497mod paused;
498pub use paused::{AnyResume, PAUSED_DIALOG_FORMAT, PausedDialog, PausedFormat, ResumeKind};
499mod instant_status;
500pub use instant_status::{InstantStatus, SepaOrderStatus, StatusSource, instant_status};
501mod transfer;
502pub use transfer::{
503    CheckedTransfer, Instant, InvalidReason, InvalidTransfer, PayeeOutcome, PayeeResult, SentAs,
504    Transfer, TransferField, TransferReceipt, TransferStatus, VopConfirmation, VopResult, VopWait,
505    transfer,
506};
507use transfer::{PaymentIds, PaymentJob};
508
509/// A booking date range, both days inclusive.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
511pub struct Range {
512    pub from: Date,
513    pub to: Date,
514}
515
516impl Range {
517    pub fn new(from: Date, to: Date) -> Self {
518        Self { from, to }
519    }
520}
521
522/// Which statement format [`transactions`] asks the bank for.
523#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
524pub enum Format {
525    /// camt.052 (HKCAZ) when the bank offers a version we build and the UPD
526    /// does not rule it out for the account, else MT940 (HKKAZ). Decided
527    /// before anything is sent; a bank that rejects HKCAZ is an error, not
528    /// a reason to try MT940.
529    #[default]
530    Auto,
531    /// camt.052 (HKCAZ) only.
532    Camt,
533    /// MT940/MT942 (HKKAZ) only.
534    Mt940,
535}
536
537/// The format a statement came in.
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
539pub enum StatementFormat {
540    Camt,
541    Mt940,
542}
543
544/// What a statement answer says about pending (vorgemerkte) entries. Only
545/// [`Pending::Reported`] is a complete list: a caller that deletes stored
546/// pending entries which the bank no longer lists must do so on `Reported`
547/// only.
548#[derive(Debug, Clone)]
549#[non_exhaustive]
550pub enum Pending {
551    /// The answer carried the pending part (camt pending document, MT942)
552    /// and it parsed; the entries are marked
553    /// [`TransactionStatus::Pending`]. Empty when nothing is pending.
554    Reported(Vec<Transaction>),
555    /// The answer had no pending part: the bank does not report pending
556    /// entries in this format, or none for this request.
557    NotSent,
558    /// The bank sent a pending part that did not parse (banks fill MT942 in
559    /// ways the grammar does not always accept), or an MT942 whose
560    /// `:90D:`/`:90C:` counts do not match its bookings (the list would not
561    /// be complete; a sum that does not match is only logged); the booked
562    /// entries are unaffected. `kind`
563    /// and `message` are those of the parse error.
564    Unreadable { kind: Category, message: String },
565}
566
567impl Pending {
568    /// The entries when the list is complete ([`Pending::Reported`]).
569    pub fn reported(&self) -> Option<&[Transaction]> {
570        match self {
571            Self::Reported(t) => Some(t),
572            _ => None,
573        }
574    }
575}
576
577/// The value of [`transactions`].
578#[derive(Debug, Clone)]
579pub struct Statement {
580    /// Booked entries, in the bank's order, all pages.
581    pub booked: Vec<Transaction>,
582    /// Pending entries and whether the list is complete.
583    pub pending: Pending,
584    /// When the bank made the pending list: the MT942 Erstellungszeitpunkt
585    /// (`:13D:` with offset, `:13:` without; HBCI 2.2 IX.2.9), the earliest
586    /// one when the pages carry several. Set only with
587    /// [`Pending::Reported`] from an MT942 that has one; `None` for camt.
588    /// A caller can tell an old list (a bank that answers from a cache)
589    /// from a fresh one.
590    pub pending_created_at: Option<BankTime>,
591    /// The format the bank was asked for.
592    pub format: StatementFormat,
593}
594
595/// A job and its inputs, as plain data. Paging jobs also carry their
596/// touchdown point and the pages received so far, so a job that pauses for
597/// a TAN on any page keeps them.
598#[derive(Debug, Clone, Serialize, Deserialize)]
599enum JobInput {
600    /// The dialog initialisation (login).
601    Open,
602    /// HKSAL for an account.
603    Balance { account: Account },
604    /// HKKAZ or HKCAZ.
605    Transactions {
606        account: Account,
607        range: Range,
608        format: StatementFormat,
609        touchdown: Option<TouchdownPoint>,
610        /// Booked statement data of the pages so far (MT940: raw bytes
611        /// joined as sent; camt: one XML document per element).
612        booked: Vec<Vec<u8>>,
613        pending: Vec<Vec<u8>>,
614        /// Whether a page carried the pending part, possibly empty.
615        pending_sent: bool,
616        /// The status of an instant payment read from the statement (no
617        /// HKIPS): the end-to-end ID to look for. The job's value is then
618        /// an [`InstantStatus`].
619        find_payment: Option<String>,
620    },
621    /// HKWPD.
622    Holdings {
623        account: Account,
624        currency: Option<Currency>,
625        touchdown: Option<TouchdownPoint>,
626        found: Vec<SecurityHolding>,
627    },
628    /// HKWDU.
629    DepotTransactions {
630        account: Account,
631        range: Option<Range>,
632        touchdown: Option<TouchdownPoint>,
633        found: Vec<DepotTransaction>,
634    },
635    /// HKCCS or HKIPZ with the payee check.
636    Transfer(Box<PaymentJob>),
637    /// HKIPS; `min_wait` (seconds) is HIIPSS "Mindestwartezeit".
638    InstantStatus {
639        account: Account,
640        descriptors: Vec<String>,
641        order_id: String,
642        min_wait: Option<u32>,
643    },
644}
645
646/// `outcome` of a message that carried a payment's order or TAN (`ids`):
647/// every error but a class 9 rejection is an unknown outcome.
648fn after_order<T>(ids: Option<&PaymentIds>, outcome: Result<T>) -> Result<T> {
649    match ids {
650        Some(ids) => outcome.map_err(|e| ids.after_order(e)),
651        None => outcome,
652    }
653}
654
655impl JobInput {
656    /// The payment's IDs when the job is a transfer.
657    fn payment_ids(&self) -> Option<PaymentIds> {
658        match self {
659            Self::Transfer(p) => Some(p.ids()),
660            _ => None,
661        }
662    }
663
664    /// What a request of this job carries.
665    fn in_flight(&self) -> InFlight {
666        match self.payment_ids() {
667            Some(ids) => InFlight::Payment(ids),
668            None => InFlight::Message,
669        }
670    }
671
672    /// Segments that go before HKTAN in the next TAN message.
673    fn tan_extra(&self) -> Vec<Segment> {
674        match self {
675            Self::Transfer(p) => p.tan_extra(),
676            _ => Vec::new(),
677        }
678    }
679
680    fn job(&self) -> Job {
681        match self {
682            Self::Open => Job::Open,
683            Self::Balance { .. } => Job::Balance,
684            Self::Transactions {
685                find_payment: Some(_),
686                ..
687            } => Job::InstantStatus,
688            Self::Transactions { .. } => Job::Transactions,
689            Self::Holdings { .. } => Job::Holdings,
690            Self::DepotTransactions { .. } => Job::DepotTransactions,
691            Self::Transfer(_) => Job::Transfer,
692            Self::InstantStatus { .. } => Job::InstantStatus,
693        }
694    }
695
696    /// The order segment (for the current page) and its response's data
697    /// segment. `None` for the login and for a transfer, which has no data
698    /// segment and is never sent again (payments design 3.5).
699    fn order(&self) -> Option<(Segment, &'static str, &'static str)> {
700        Some(match self {
701            Self::Open | Self::Transfer(_) => return None,
702            Self::Balance { account } => (
703                Segment::Balance {
704                    account: account.clone(),
705                },
706                "HKSAL",
707                "HISAL",
708            ),
709            Self::Transactions {
710                account,
711                range,
712                format,
713                touchdown,
714                ..
715            } => match format {
716                StatementFormat::Mt940 => (
717                    Segment::Transactions {
718                        account: account.clone(),
719                        start_date: range.from,
720                        end_date: range.to,
721                        touchdown: touchdown.clone(),
722                    },
723                    "HKKAZ",
724                    "HIKAZ",
725                ),
726                StatementFormat::Camt => (
727                    Segment::CamtTransactions {
728                        account: account.clone(),
729                        start_date: range.from,
730                        end_date: range.to,
731                        touchdown: touchdown.clone(),
732                    },
733                    "HKCAZ",
734                    "HICAZ",
735                ),
736            },
737            Self::Holdings {
738                account,
739                currency,
740                touchdown,
741                ..
742            } => (
743                Segment::Holdings {
744                    account: account.clone(),
745                    currency: currency.clone(),
746                    touchdown: touchdown.clone(),
747                },
748                "HKWPD",
749                "HIWPD",
750            ),
751            Self::DepotTransactions {
752                account,
753                range,
754                touchdown,
755                ..
756            } => (
757                Segment::DepotTransactions {
758                    account: account.clone(),
759                    start_date: range.map(|r| r.from),
760                    end_date: range.map(|r| r.to),
761                    touchdown: touchdown.clone(),
762                },
763                "HKWDU",
764                "HIWDU",
765            ),
766            Self::InstantStatus {
767                account,
768                descriptors,
769                order_id,
770                ..
771            } => (
772                Segment::InstantStatus {
773                    account: account.clone(),
774                    descriptors: descriptors.clone(),
775                    order_id: order_id.clone(),
776                },
777                "HKIPS",
778                "HIIPS",
779            ),
780        })
781    }
782
783    /// Take the page `response` carries into the job. `true`: the bank
784    /// has more (3040) and the job's touchdown point now names it. A bank
785    /// repeating the touchdown point it was just given would loop forever:
786    /// the job ends there, and the bank's 3040 goes to `notices`.
787    fn absorb(
788        &mut self,
789        response: &Response,
790        requested_camt: &str,
791        notices: &mut Vec<Notice>,
792    ) -> bool {
793        let next = response.touchdown();
794        let (current, more) = match self {
795            Self::Open | Self::Balance { .. } | Self::Transfer(_) | Self::InstantStatus { .. } => {
796                return false;
797            }
798            Self::Transactions {
799                format,
800                touchdown,
801                booked,
802                pending,
803                pending_sent,
804                ..
805            } => {
806                match format {
807                    StatementFormat::Mt940 => {
808                        let page = extract_mt940_data(&response.segments);
809                        booked.push(page.booked);
810                        pending.push(page.pending);
811                        *pending_sent |= page.pending_sent;
812                    }
813                    StatementFormat::Camt => {
814                        let page = extract_camt_data(&response.segments);
815                        for (descriptor, document) in page.descriptors.iter().zip(&page.booked) {
816                            crate::camt::note_version_mismatch(
817                                requested_camt,
818                                descriptor,
819                                document,
820                            );
821                        }
822                        booked.extend(page.booked);
823                        pending.extend(page.pending);
824                        *pending_sent |= page.pending_sent;
825                    }
826                }
827                (touchdown, next)
828            }
829            Self::Holdings {
830                touchdown, found, ..
831            } => {
832                found.extend(parse_hiwpd(&response.segments));
833                (touchdown, next)
834            }
835            Self::DepotTransactions {
836                touchdown, found, ..
837            } => {
838                found.extend(parse_hiwdu(&response.segments));
839                (touchdown, next)
840            }
841        };
842        match more {
843            Some(point) if current.as_ref() == Some(&point) => {
844                warn!("[FinTS] The bank repeated touchdown point {point}; stopping");
845                notices.extend(
846                    response
847                        .all_codes()
848                        .filter(|c| matches!(c.kind(), Kind::Touchdown(_)))
849                        .map(|c| Notice::new(NoticeDialog::Job, c.clone())),
850                );
851                false
852            }
853            Some(point) => {
854                info!("[FinTS] Touchdown {point}: more data");
855                *current = Some(point);
856                true
857            }
858            None => false,
859        }
860    }
861
862    /// The job's value, once the last page is in. `response` is that page.
863    /// `booking_id` is the bank profile's rule for statements.
864    fn finish(self, response: &Response, booking_id: BookingIdSource) -> Result<Value> {
865        Ok(match self {
866            Self::Open | Self::Transfer(_) => {
867                return Err(FinTSError::Internal("not a read order".into()));
868            }
869            Self::Balance { .. } => Value::Balance(
870                response
871                    .find_segment("HISAL")
872                    .and_then(crate::segments::read::balance),
873            ),
874            Self::Transactions {
875                format,
876                booked,
877                pending,
878                pending_sent,
879                find_payment,
880                ..
881            } => {
882                let statement =
883                    parse_statement(format, &booked, &pending, pending_sent, booking_id)?;
884                match find_payment {
885                    Some(id) => {
886                        Value::InstantStatus(instant_status::from_statement(&statement, &id))
887                    }
888                    None => Value::Statement(statement),
889                }
890            }
891            Self::Holdings { found, .. } => Value::Holdings(found),
892            Self::DepotTransactions { found, .. } => Value::DepotTransactions(found),
893            Self::InstantStatus { min_wait, .. } => {
894                Value::InstantStatus(instant_status::read(response, min_wait)?)
895            }
896        })
897    }
898}
899
900/// Parse the statement data of all pages. Booked data that does not parse
901/// fails the job; pending data that does not parse is
902/// [`Pending::Unreadable`], and no pending part at all is
903/// [`Pending::NotSent`].
904///
905/// `booking_id` (the profile's rule) applies to the booked part only: a
906/// pending booking gets no ID, and an ID shared by two booked entries of
907/// the statement (on different pages) is dropped from both.
908fn parse_statement(
909    format: StatementFormat,
910    booked: &[Vec<u8>],
911    pending: &[Vec<u8>],
912    pending_sent: bool,
913    booking_id: BookingIdSource,
914) -> Result<Statement> {
915    let (booked, pending) =
916        match format {
917            // Banks split the MT940 stream at any byte, also inside a field:
918            // pages are joined as they are.
919            StatementFormat::Mt940 => (
920                parse_mt940(&booked.concat(), TransactionStatus::Booked),
921                parse_mt942(&pending.concat()).map(|p| (p.transactions, p.created)),
922            ),
923            StatementFormat::Camt => (
924                booked
925                    .iter()
926                    .try_fold(Vec::new(), |mut all, doc| {
927                        all.extend(crate::camt::parse_camt052(doc, booking_id)?);
928                        Ok(all)
929                    })
930                    .map(|mut all: Vec<Transaction>| {
931                        crate::camt::drop_shared_booking_ids(&mut all);
932                        all
933                    }),
934                pending
935                    .iter()
936                    .try_fold(Vec::new(), |mut all, doc| {
937                        let none = BookingIdSource::None;
938                        all.extend(crate::camt::parse_camt052(doc, none)?.into_iter().map(
939                            |mut t| {
940                                t.status = TransactionStatus::Pending;
941                                t
942                            },
943                        ));
944                        Ok(all)
945                    })
946                    .map(|all| (all, None)),
947            ),
948        };
949    let (pending, pending_created_at) = match pending {
950        _ if !pending_sent => (Pending::NotSent, None),
951        Ok((pending, created)) => (Pending::Reported(pending), created),
952        Err(e) => (
953            Pending::Unreadable {
954                kind: e.kind(),
955                message: e.to_string(),
956            },
957            None,
958        ),
959    };
960    Ok(Statement {
961        booked: booked?,
962        pending,
963        pending_created_at,
964        format,
965    })
966}
967
968/// The job a paused dialog waits on: plain data, no transport, no clock.
969/// Part of a [`PausedDialog`].
970#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct PendingJob {
972    ticket: Ticket,
973    wait: Wait,
974    job: JobInput,
975    /// Notices of the job's messages so far.
976    notices: Vec<Notice>,
977}
978
979impl PendingJob {
980    /// The TAN challenge the job waits on; `None` while a transfer waits
981    /// on its payee check.
982    pub fn challenge(&self) -> Option<&TanChallenge> {
983        match &self.wait {
984            Wait::Tan(c) => Some(c),
985            _ => None,
986        }
987    }
988
989    /// The payee check result a transfer waits to have confirmed.
990    pub fn vop(&self) -> Option<&VopConfirmation> {
991        match &self.wait {
992            Wait::VopConfirmation(c) => Some(c),
993            _ => None,
994        }
995    }
996
997    /// The unfinished payee check a transfer waits on.
998    pub fn vop_wait(&self) -> Option<&VopWait> {
999        match &self.wait {
1000            Wait::VopPoll(w) => Some(w),
1001            _ => None,
1002        }
1003    }
1004
1005    /// The bank's task reference of a TAN wait.
1006    fn task_reference(&self) -> Result<TaskReference> {
1007        match &self.ticket {
1008            Ticket::Task(t) => Ok(t.clone()),
1009            Ticket::Local(_) => Err(FinTSError::Internal(
1010                "TAN wait without task reference".into(),
1011            )),
1012        }
1013    }
1014}
1015
1016/// Where a dialog is.
1017#[derive(Debug, Clone)]
1018pub enum Phase {
1019    /// Ready for a job.
1020    Open,
1021    /// A job waits for a TAN, a decoupled confirmation or a payee check.
1022    Paused(Box<PendingJob>),
1023    /// Over; every job returns [`FinTSError::DialogEnded`].
1024    Ended,
1025}
1026
1027/// A job's progress inside the dialog, before it is typed for the caller.
1028enum Outcome {
1029    Done(Value, Vec<Notice>),
1030    Paused(Wait, Ticket),
1031}
1032
1033impl Outcome {
1034    fn into_step<T: Sealed>(self) -> Result<Step<T>> {
1035        match self {
1036            Self::Done(value, notices) => T::from_value(value)
1037                .map(|value| Step::Done(Completed { value, notices }))
1038                .ok_or_else(|| FinTSError::Internal("job finished with another value".into())),
1039            Self::Paused(wait, ticket) => {
1040                let resume = Resume {
1041                    ticket,
1042                    _value: PhantomData,
1043                };
1044                Ok(match wait {
1045                    Wait::Tan(c) => Step::NeedTan(c, resume),
1046                    Wait::VopConfirmation(c) => Step::NeedVopConfirmation(c, resume),
1047                    Wait::VopPoll(w) => Step::VopPending(w, resume),
1048                })
1049            }
1050        }
1051    }
1052}
1053
1054// ═══════════════════════════════════════════════════════════════════════════════
1055// Dialog
1056// ═══════════════════════════════════════════════════════════════════════════════
1057
1058/// An open dialog with the bank. Holds the paused job, if any; the caller
1059/// owns it and passes it to every job. End it with [`Dialog::end`] to get
1060/// the updated [`SessionState`].
1061///
1062/// **Not cancel-safe.** The futures of [`open`], of every job and of
1063/// [`Dialog::submit_tan`], [`Dialog::poll`] and [`Dialog::confirm_vop`]
1064/// must run to completion: dropping one mid-request (`select!`, a
1065/// timeout around the call) loses what was sent. The dialog then ends;
1066/// when the request carried a transfer's order or TAN, the next call
1067/// returns [`FinTSError::PaymentOutcomeUnknown`] with the payment's IDs
1068/// once, and [`FinTSError::DialogEnded`] after that. Cancel between calls
1069/// (in the wait until `not_before`) with [`Dialog::cancel`]; timeouts
1070/// belong in the transport.
1071pub struct Dialog {
1072    inner: protocol::Dialog<Open>,
1073    /// The bank's BIC, for UPD accounts without one of their own.
1074    bic: Bic,
1075    /// The bank profile's rule for [`Transaction::booking_id`].
1076    booking_id: BookingIdSource,
1077    phase: Phase,
1078    /// Wall clock of the last response from the bank.
1079    last_message_at: Timestamp,
1080    /// A request is in flight. Still set on the next call when the caller
1081    /// dropped the future: the message number is then unknown, and a
1082    /// payment's outcome too.
1083    in_flight: Option<InFlight>,
1084}
1085
1086/// What the request in flight carried.
1087#[derive(Debug, Clone)]
1088enum InFlight {
1089    /// Nothing that moves money.
1090    Message,
1091    /// A payment order or its TAN: a dropped future leaves the outcome
1092    /// unknown.
1093    Payment(PaymentIds),
1094}
1095
1096/// What [`Dialog::cancel`] left behind at the bank.
1097#[must_use]
1098#[derive(Debug, Clone, PartialEq, Eq)]
1099pub enum Cancelled {
1100    /// Nothing the bank could execute is pending: a read job, the login,
1101    /// or a transfer at its payee check ([`Step::NeedVopConfirmation`],
1102    /// [`Step::VopPending`]), which the bank executes only after the
1103    /// execution order.
1104    NothingSent,
1105    /// The transfer's order went out and waits for its TAN: the bank may
1106    /// still execute it (the user approves in the app after the cancel).
1107    /// Treat it like [`FinTSError::PaymentOutcomeUnknown`]: check the
1108    /// account by these IDs before sending it again.
1109    OrderSubmitted {
1110        end_to_end_id: String,
1111        message_id: String,
1112    },
1113}
1114
1115impl std::fmt::Debug for Dialog {
1116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1117        let phase = match &self.phase {
1118            Phase::Open => "Open",
1119            Phase::Paused(_) => "Paused",
1120            Phase::Ended => "Ended",
1121        };
1122        f.debug_struct("Dialog")
1123            .field("blz", self.inner.blz())
1124            .field("phase", &phase)
1125            .field("last_message_at", &self.last_message_at)
1126            .finish_non_exhaustive()
1127    }
1128}
1129
1130/// Open a dialog: synchronise first when `state` has no system ID or BPD
1131/// (a stored system ID without BPD is kept, see below), then the dialog
1132/// initialisation with HKTAN process 4. The step is `Done` on an SCA
1133/// exemption, else `NeedTan` for the login. Login notices (3072, …) arrive
1134/// on the step's `Done`.
1135///
1136/// `state` from another bank or user is ignored. A stored system ID
1137/// without BPD is reused through a parameter probe instead of HKSYN (which
1138/// would assign a new one). If the bank rejects the stored system ID
1139/// (9391), the setup runs once more with a full synchronisation.
1140pub async fn open(
1141    client: &BankClient,
1142    creds: &Credentials,
1143    state: &SessionState,
1144) -> Result<(Dialog, Step<Opened>)> {
1145    let state = state_for(client, creds, state);
1146    match open_once(client, creds, state).await {
1147        Err(e)
1148            if e.kind() == Category::SystemId
1149                && state.is_some_and(|s| s.system_id.is_assigned()) =>
1150        {
1151            warn!("[FinTS] Bank rejected cached system ID ({e}); re-synchronizing");
1152            open_once(client, creds, None).await
1153        }
1154        other => other,
1155    }
1156}
1157
1158async fn open_once(
1159    client: &BankClient,
1160    creds: &Credentials,
1161    state: Option<&SessionState>,
1162) -> Result<(Dialog, Step<Opened>)> {
1163    if let InitMode::Direct { security_function } = &client.config().profile.init {
1164        return open_direct(client, creds, state, security_function).await;
1165    }
1166    let mut notices = Vec::new();
1167    let (mut params, system_id) = match state.filter(|s| s.can_skip_sync()) {
1168        Some(s) => {
1169            info!(
1170                "[FinTS] Using cached BPD v{} / UPD v{} and system ID: no sync dialog",
1171                s.bpd_version, s.upd_version
1172            );
1173            (s.to_params(), s.system_id.clone())
1174        }
1175        None => fetch_params(client, creds, state, &mut notices).await?,
1176    };
1177    // TAN preferences from the state apply whether or not we synced.
1178    if let Some(s) = state {
1179        // A choice in the state wins; without one, keep what params has.
1180        params.preferred_security_function = s
1181            .tan_method
1182            .clone()
1183            .or(params.preferred_security_function.take());
1184        params.selected_tan_medium = s.tan_medium.clone().or(params.selected_tan_medium.take());
1185        params.select_security_function();
1186    }
1187
1188    let init = client
1189        .new_dialog(creds)?
1190        .with_system_id(&system_id)
1191        .with_params(&params)
1192        .init()
1193        .await?;
1194    let (inner, challenge) = match init {
1195        InitResult::Opened(open) => (open, None),
1196        InitResult::TanRequired(pending, challenge) => (pending.transition(), Some(challenge)),
1197    };
1198    let mut dialog = Dialog {
1199        inner,
1200        bic: client.config().bic.clone(),
1201        booking_id: client.config().profile.booking_id,
1202        phase: Phase::Open,
1203        last_message_at: Timestamp::now(),
1204        in_flight: None,
1205    };
1206    notices.extend(dialog.inner.take_notices());
1207    let outcome = match challenge {
1208        Some(challenge) => dialog.pause(JobInput::Open, &challenge, notices),
1209        None => Outcome::Done(Value::Opened(dialog.opened()), notices),
1210    };
1211    let step = outcome.into_step()?;
1212    Ok((dialog, step))
1213}
1214
1215/// [`InitMode::Direct`]: no synchronisation dialog; the business dialog
1216/// opens PIN-only with the stored system ID or a client-generated one and
1217/// the configured security function, and the bank sends its parameters in
1218/// it.
1219async fn open_direct(
1220    client: &BankClient,
1221    creds: &Credentials,
1222    state: Option<&SessionState>,
1223    security_function: &str,
1224) -> Result<(Dialog, Step<Opened>)> {
1225    let system_id = state
1226        .map(|s| &s.system_id)
1227        .filter(|s| s.is_assigned())
1228        .cloned()
1229        .unwrap_or_else(|| SystemId::new(format!("{:016X}", rand::random::<u64>())));
1230    let (inner, _) = client
1231        .new_dialog(creds)?
1232        .with_system_id(&system_id)
1233        .with_security_function(SecurityFunction::new(security_function))
1234        .init_no_tan()
1235        .await?;
1236    let mut dialog = Dialog {
1237        inner,
1238        bic: client.config().bic.clone(),
1239        booking_id: client.config().profile.booking_id,
1240        phase: Phase::Open,
1241        last_message_at: Timestamp::now(),
1242        in_flight: None,
1243    };
1244    let notices = dialog.inner.take_notices();
1245    let step = Outcome::Done(Value::Opened(dialog.opened()), notices).into_step()?;
1246    Ok((dialog, step))
1247}
1248
1249/// `state` when it belongs to the client's bank and to the user of
1250/// `creds`. Both user IDs are compared as the bank gets them (completed by
1251/// the profile's rule), so a state made with the short form of a user ID
1252/// matches a login with either form.
1253fn state_for<'a>(
1254    client: &BankClient,
1255    creds: &Credentials,
1256    state: &'a SessionState,
1257) -> Option<&'a SessionState> {
1258    let matches = state.blz == client.config().blz
1259        && client.effective_user_id(&state.user_id) == client.effective_user_id(&creds.user_id);
1260    if !matches {
1261        warn!("[FinTS] Ignoring session state: it belongs to another bank or user");
1262    }
1263    matches.then_some(state)
1264}
1265
1266/// Learn the bank's parameters and the TAN methods it allows this user,
1267/// without opening a business dialog, so the caller can choose a method
1268/// ([`SessionState::with_tan_method`], [`SessionState::with_tan_medium`])
1269/// before [`open`].
1270///
1271/// With a stored system ID the parameter probe runs (HKIDN + HKVVB, PIN
1272/// only, which keeps the system ID), else the synchronisation dialog
1273/// (HKSYN). Neither carries HKTAN, so no TAN is asked for and the result is
1274/// not a [`Step`]. The returned state has the BPD, the UPD, the system ID
1275/// and the allowed security functions (3920); [`SessionState::tan_methods`]
1276/// lists the methods. `tan_method` holds the caller's preference when the
1277/// bank allows it, else the method [`open`] would choose itself (the
1278/// highest decoupled one). TAN medium and learned TAN codes of `state` are
1279/// kept. A user ID change the bank reports (3072) is in `user_id` and
1280/// `previous_user_id`; the notices of the dialog are in the result
1281/// ([`Completed::notices`]; none when nothing is sent).
1282///
1283/// `state` from another bank or user is ignored, as in [`open`]. With
1284/// [`InitMode::Direct`] (no synchronisation dialog, a fixed security
1285/// function) nothing is sent: the state comes back with `tan_method` set to
1286/// the profile's security function, which [`open`] uses whatever the
1287/// caller sets. A rejected system ID (9391) is an error here; [`open`]
1288/// recovers from it, or [`SessionState::reset`] and synchronise again.
1289pub async fn synchronise(
1290    client: &BankClient,
1291    creds: &Credentials,
1292    state: &SessionState,
1293) -> Result<Completed<SessionState>> {
1294    let config = client.config();
1295    let user_id = client.effective_user_id(&creds.user_id);
1296    let state = state_for(client, creds, state);
1297    if let InitMode::Direct { security_function } = &config.profile.init {
1298        let mut state = state
1299            .cloned()
1300            .unwrap_or_else(|| SessionState::new(&config.blz, &user_id));
1301        state.tan_method = Some(SecurityFunction::new(security_function));
1302        return Ok(Completed {
1303            value: state,
1304            notices: Vec::new(),
1305        });
1306    }
1307    let mut notices = Vec::new();
1308    let (mut params, system_id) = fetch_params(client, creds, state, &mut notices).await?;
1309    for n in &notices {
1310        info!("[FinTS] Synchronisation: {n}");
1311    }
1312    if let Some(s) = state {
1313        params.preferred_security_function = s.tan_method.clone();
1314        params.selected_tan_medium = s.tan_medium.clone();
1315        params
1316            .tan_required_learned
1317            .extend(s.tan_required_learned.iter().cloned());
1318        params.select_security_function();
1319    }
1320    Ok(Completed {
1321        value: SessionState::capture(&config.blz, &user_id, &system_id, &params),
1322        notices,
1323    })
1324}
1325
1326/// Parameters and system ID without a usable state: a parameter probe
1327/// with a stored system ID, else a synchronisation dialog.
1328async fn fetch_params(
1329    client: &BankClient,
1330    creds: &Credentials,
1331    state: Option<&SessionState>,
1332    notices: &mut Vec<Notice>,
1333) -> Result<(BankParams, SystemId)> {
1334    let stored = state.map(|s| &s.system_id).filter(|s| s.is_assigned());
1335    if let Some(sid) = stored {
1336        match client
1337            .new_dialog(creds)?
1338            .with_system_id(sid)
1339            .probe_parameters()
1340            .await
1341        {
1342            Ok(found) => {
1343                info!("[FinTS] Reusing the stored system ID; no sync dialog");
1344                return Ok(found);
1345            }
1346            Err(e) if matches!(e.kind(), Category::Credentials(_) | Category::SystemId) => {
1347                return Err(e);
1348            }
1349            Err(e) => warn!(
1350                "[FinTS] Parameter probe with the stored system ID failed ({e}); synchronizing"
1351            ),
1352        }
1353    }
1354    let mut sync = client.new_dialog(creds)?;
1355    if let Some(sid) = stored {
1356        sync = sync.with_system_id(sid);
1357    }
1358    let (mut synced, _) = sync.sync().await?;
1359    notices.extend(synced.take_notices());
1360    let (params, system_id) = synced.end().await?;
1361    let system_id = if system_id.is_assigned() {
1362        system_id
1363    } else {
1364        stored.cloned().unwrap_or_else(SystemId::unassigned)
1365    };
1366    Ok((params, system_id))
1367}
1368
1369/// The balance of `account` (HKSAL). `None` when the bank answers with
1370/// success but without HISAL (3010 "no entries", which is a notice).
1371pub async fn balance(
1372    dialog: &mut Dialog,
1373    account: &Account,
1374) -> Result<Step<Option<AccountBalance>>> {
1375    dialog
1376        .start(JobInput::Balance {
1377            account: account.clone(),
1378        })
1379        .await?
1380        .into_step()
1381}
1382
1383/// The transactions of `account` booked in `range`: all touchdown pages,
1384/// in one call. The format follows `format` ([`Format::Auto`] prefers
1385/// camt.052); a TAN can be required on any page, and the job then pauses
1386/// with the pages so far. A failure on a later page fails the job and drops
1387/// the pages: retry with a narrower range.
1388///
1389/// A `range.from` before today minus the bank's storage period
1390/// ([`Support::Available`]'s `days_stored`) is raised to that day, and the
1391/// notices of the step carry [`ClientWarning::RangeClamped`]. Today is the
1392/// system's local date unless the client pins it ([`BankClient::with_now`]).
1393///
1394/// Fails with [`FinTSError::NoBpd`] or [`FinTSError::VersionMismatch`]
1395/// (for the chosen format) before anything is sent. A UPD that does not
1396/// list the order never blocks it.
1397pub async fn transactions(
1398    dialog: &mut Dialog,
1399    account: &Account,
1400    range: Range,
1401    format: Format,
1402) -> Result<Step<Statement>> {
1403    let today = dialog.inner.now().date();
1404    transactions_on(dialog, account, range, format, today).await
1405}
1406
1407async fn transactions_on(
1408    dialog: &mut Dialog,
1409    account: &Account,
1410    range: Range,
1411    format: Format,
1412    today: Date,
1413) -> Result<Step<Statement>> {
1414    let format = choose_format(dialog.bank_params(), account, format)?;
1415    let order = match format {
1416        StatementFormat::Mt940 => Order::Transactions,
1417        StatementFormat::Camt => Order::Camt,
1418    };
1419    let days = dialog.bank_params().days_stored(order);
1420    let (range, clamped) = clamp_range(range, today, days);
1421    let notices = clamped
1422        .map(|requested| {
1423            let warning = ClientWarning::RangeClamped {
1424                requested,
1425                used: range.from,
1426            };
1427            warn!("[FinTS] {warning}");
1428            Notice::client(NoticeDialog::Job, warning)
1429        })
1430        .into_iter()
1431        .collect();
1432    dialog
1433        .start_with(
1434            JobInput::Transactions {
1435                account: account.clone(),
1436                range,
1437                format,
1438                touchdown: None,
1439                booked: Vec::new(),
1440                pending: Vec::new(),
1441                pending_sent: false,
1442                find_payment: None,
1443            },
1444            notices,
1445        )
1446        .await?
1447        .into_step()
1448}
1449
1450/// `range` with `from` raised to `today - days_stored`; the second value
1451/// is the `from` that was asked for when it was raised. `to` is raised
1452/// along when the whole range lies before the storage period.
1453fn clamp_range(range: Range, today: Date, days_stored: Option<u32>) -> (Range, Option<Date>) {
1454    let Some(oldest) = days_stored
1455        .and_then(|d| today.checked_sub(jiff::Span::new().days(i64::from(d))).ok())
1456        .filter(|oldest| range.from < *oldest)
1457    else {
1458        return (range, None);
1459    };
1460    (Range::new(oldest, range.to.max(oldest)), Some(range.from))
1461}
1462
1463/// The statement format to ask for, decided from the BPD and UPD.
1464fn choose_format(
1465    params: &BankParams,
1466    account: &Account,
1467    wanted: Format,
1468) -> Result<StatementFormat> {
1469    choose_statement_format(params, wanted, || upd_allowance(params, account, "HKCAZ"))
1470}
1471
1472/// [`choose_format`] with the UPD's word on HKCAZ given lazily, so that
1473/// [`Capabilities`] (which knows the UPD account) decides the same way.
1474fn choose_statement_format(
1475    params: &BankParams,
1476    wanted: Format,
1477    camt_allowance: impl FnOnce() -> Allowance,
1478) -> Result<StatementFormat> {
1479    match wanted {
1480        Format::Camt => Ok(StatementFormat::Camt),
1481        Format::Mt940 => Ok(StatementFormat::Mt940),
1482        Format::Auto => match params.order_version(Order::Camt) {
1483            Ok(_) if camt_allowance() == Allowance::No => {
1484                info!("[FinTS] The UPD does not list HKCAZ for the account; using MT940");
1485                Ok(StatementFormat::Mt940)
1486            }
1487            Ok(_) => Ok(StatementFormat::Camt),
1488            Err(FinTSError::VersionMismatch(why)) => {
1489                info!("[FinTS] camt not available ({why}); using MT940");
1490                Ok(StatementFormat::Mt940)
1491            }
1492            Err(e) => Err(e),
1493        },
1494    }
1495}
1496
1497/// The UPD account that `account` names ([`Upd::find`]: by key,
1498/// subaccount included).
1499fn find_upd_account<'a>(params: &'a BankParams, account: &Account) -> Option<&'a UpdAccount> {
1500    params.upd()?.find(account)
1501}
1502
1503/// What the UPD says about `code` for `account`; `Unknown` when the UPD
1504/// does not name the account.
1505fn upd_allowance(params: &BankParams, account: &Account, code: &str) -> Allowance {
1506    match (params.upd(), find_upd_account(params, account)) {
1507        (Some(upd), Some(a)) => upd.allows(a, code),
1508        _ => Allowance::Unknown,
1509    }
1510}
1511
1512/// The securities in the depot `account` (HKWPD, MT535): all touchdown
1513/// pages. `currency` asks for the valuation currency.
1514pub async fn holdings(
1515    dialog: &mut Dialog,
1516    account: &Account,
1517    currency: Option<Currency>,
1518) -> Result<Step<Vec<SecurityHolding>>> {
1519    dialog
1520        .start(JobInput::Holdings {
1521            account: account.clone(),
1522            currency,
1523            touchdown: None,
1524            found: Vec::new(),
1525        })
1526        .await?
1527        .into_step()
1528}
1529
1530/// The securities movements of the depot `account` (HKWDU, MT536): all
1531/// touchdown pages. Without `range` the bank chooses the period.
1532pub async fn depot_transactions(
1533    dialog: &mut Dialog,
1534    account: &Account,
1535    range: Option<Range>,
1536) -> Result<Step<Vec<DepotTransaction>>> {
1537    dialog
1538        .start(JobInput::DepotTransactions {
1539            account: account.clone(),
1540            range,
1541            touchdown: None,
1542            found: Vec::new(),
1543        })
1544        .await?
1545        .into_step()
1546}
1547
1548impl Dialog {
1549    /// Where the dialog is.
1550    pub fn phase(&self) -> &Phase {
1551        &self.phase
1552    }
1553
1554    /// The paused job, if any.
1555    pub fn pending(&self) -> Option<&PendingJob> {
1556        match &self.phase {
1557            Phase::Paused(p) => Some(p.as_ref()),
1558            _ => None,
1559        }
1560    }
1561
1562    /// Wall clock of the bank's last response.
1563    pub fn last_message_at(&self) -> Timestamp {
1564        self.last_message_at
1565    }
1566
1567    /// What the bank offers per account (`accounts`, or the UPD's accounts
1568    /// when empty), from this dialog's BPD and UPD, the learned TAN codes
1569    /// and the client's TAN overrides. Sends nothing.
1570    pub fn capabilities(&self, accounts: &[Account]) -> Capabilities {
1571        Capabilities::build(self.bank_params(), self.inner.tan_overrides(), accounts)
1572    }
1573
1574    /// The bank and user parameters as the dialog knows them now.
1575    #[cfg(feature = "tooling")]
1576    pub fn bank_params(&self) -> &BankParams {
1577        self.inner.bank_params()
1578    }
1579
1580    #[cfg(not(feature = "tooling"))]
1581    pub(crate) fn bank_params(&self) -> &BankParams {
1582        self.inner.bank_params()
1583    }
1584
1585    /// Send the TAN for the paused job (HKTAN process 2, PIN/TAN B.4.2),
1586    /// for the login and for any order. The bank's confirmation carries
1587    /// the order's data; if it does not, a read order is sent once more (a
1588    /// transfer never). A transfer whose payee check the bank wants
1589    /// released sends HKVPA with its first TAN message.
1590    ///
1591    /// A wrong TAN the bank rejects with 9941 alone (the order kept, the
1592    /// dialog open) gives `NeedTan` again for the same order, with
1593    /// [`TanChallenge::rejected`] set: show the bank's text and ask again,
1594    /// or [`Dialog::cancel`]. Nothing is resent unless the caller submits
1595    /// another TAN. Any other rejection fails the job (the order deleted,
1596    /// the access locked, the dialog ended): an order's dialog stays open
1597    /// unless the bank ended it, a login's dialog ends. On a transfer
1598    /// every error but a class 9 rejection is
1599    /// [`FinTSError::PaymentOutcomeUnknown`].
1600    ///
1601    /// Not cancel-safe (see [`Dialog`]).
1602    pub async fn submit_tan<T: JobValue>(
1603        &mut self,
1604        resume: Resume<T>,
1605        tan: &str,
1606    ) -> Result<Step<T>> {
1607        let pending = self.pending_for(&resume)?;
1608        match &pending.wait {
1609            Wait::Tan(c) if matches!(c.kind, TanKind::Decoupled { .. }) => {
1610                return Err(FinTSError::Dialog(
1611                    "decoupled challenge: confirm in the app and poll".into(),
1612                ));
1613            }
1614            Wait::Tan(_) => {}
1615            _ => {
1616                return Err(FinTSError::Dialog(
1617                    "the job waits for its payee check, not for a TAN".into(),
1618                ));
1619            }
1620        }
1621        let mut pending = self.take_pending();
1622        let ids = pending.job.payment_ids();
1623        let outcome = async {
1624            let task_reference = pending.task_reference()?;
1625            let extra = pending.job.tan_extra();
1626            self.in_flight = Some(pending.job.in_flight());
1627            let response = self.inner.send_tan(&extra, &task_reference, tan).await;
1628            let response = self.settle(&pending.job, response)?;
1629            // HKVPA goes with the first TAN message only, as with a
1630            // decoupled approval.
1631            if let JobInput::Transfer(p) = &mut pending.job {
1632                p.tan_extra_sent();
1633            }
1634            if !matches!(self.phase, Phase::Ended)
1635                && let Some((code, attempts_left)) = response.tan_rejection()
1636                && let Wait::Tan(challenge) = &mut pending.wait
1637            {
1638                let count = challenge.rejected.as_ref().map_or(0, |r| r.count) + 1;
1639                warn!(
1640                    "[FinTS] TAN rejected ({} {}); the bank keeps the order for another TAN",
1641                    code.code, code.text
1642                );
1643                challenge.rejected = Some(Box::new(TanRejected {
1644                    code,
1645                    attempts_left,
1646                    count,
1647                }));
1648                extend_notices(&mut pending.notices, self.inner.take_notices());
1649                let outcome = Outcome::Paused(pending.wait.clone(), pending.ticket.clone());
1650                self.phase = Phase::Paused(Box::new(pending));
1651                return Ok(outcome);
1652            }
1653            self.confirmed(pending, response).await
1654        }
1655        .await;
1656        after_order(ids.as_ref(), outcome)?.into_step()
1657    }
1658
1659    /// One decoupled status request for the paused job (HKTAN process S;
1660    /// process 2 before HKTAN 7). Still pending (3956): `NeedTan` again
1661    /// with `polls_done + 1` and a new `not_before`. Once the bank's
1662    /// `max_polls` are used up, [`FinTSError::DecoupledMaxPolls`] without
1663    /// sending, and the job is dropped; on a transfer that error is
1664    /// [`FinTSError::PaymentOutcomeUnknown`] (the bank may still execute
1665    /// it), as is every error of a transfer's status request but a class 9
1666    /// rejection. The library does not wait; sleep `first_wait` /
1667    /// `next_wait` before calling (or until `not_before`). When the
1668    /// challenge's `auto_polling_allowed` is `Some(false)` the caller must
1669    /// not poll automatically: the bank expects the user to trigger each
1670    /// status request. `poll` itself does not check it.
1671    ///
1672    /// On a transfer's unfinished payee check ([`Step::VopPending`]) it
1673    /// sends the next HKVPP instead; HKVPA goes with a transfer's first
1674    /// decoupled status request when the bank wants the check released.
1675    ///
1676    /// Not cancel-safe (see [`Dialog`]).
1677    pub async fn poll<T: JobValue>(&mut self, resume: Resume<T>) -> Result<Step<T>> {
1678        let pending = self.pending_for(&resume)?;
1679        let (max_polls, polls_done) = match &pending.wait {
1680            Wait::VopPoll(_) => {
1681                let pending = self.take_pending();
1682                return self.vop_poll(pending).await?.into_step();
1683            }
1684            Wait::VopConfirmation(_) => {
1685                return Err(FinTSError::Dialog(
1686                    "payee check result: confirm_vop or cancel".into(),
1687                ));
1688            }
1689            Wait::Tan(TanChallenge {
1690                kind:
1691                    TanKind::Decoupled {
1692                        max_polls,
1693                        polls_done,
1694                        ..
1695                    },
1696                ..
1697            }) => (*max_polls, *polls_done),
1698            Wait::Tan(_) => {
1699                return Err(FinTSError::Dialog(
1700                    "typed TAN challenge: submit the TAN".into(),
1701                ));
1702            }
1703        };
1704        let mut pending = self.take_pending();
1705        let ids = pending.job.payment_ids();
1706        if let Some(max) = max_polls.filter(|max| polls_done >= *max) {
1707            self.job_failed(&pending.job);
1708            return Err(match ids {
1709                Some(ids) => {
1710                    warn!("[FinTS] Transfer approval not confirmed within {max} status requests");
1711                    ids.unknown()
1712                }
1713                None => FinTSError::DecoupledMaxPolls(max),
1714            });
1715        }
1716        let outcome = async {
1717            let task_reference = pending.task_reference()?;
1718            let extra = pending.job.tan_extra();
1719            self.in_flight = Some(pending.job.in_flight());
1720            let response = self.inner.send_tan_status(&extra, &task_reference).await;
1721            let response = self.settle(&pending.job, response)?;
1722            if let JobInput::Transfer(p) = &mut pending.job {
1723                p.tan_extra_sent();
1724            }
1725            for c in response.all_codes() {
1726                info!("[FinTS] Poll: {} - {}", c.code, c.text);
1727            }
1728            if response.is_decoupled_pending() {
1729                extend_notices(&mut pending.notices, self.inner.take_notices());
1730                if let Wait::Tan(challenge) = &mut pending.wait
1731                    && let TanKind::Decoupled {
1732                        polls_done,
1733                        next_wait,
1734                        ..
1735                    } = &mut challenge.kind
1736                {
1737                    *polls_done += 1;
1738                    let next_wait = *next_wait;
1739                    challenge.not_before = not_before_after(Timestamp::now(), next_wait);
1740                }
1741                let outcome = Outcome::Paused(pending.wait.clone(), pending.ticket.clone());
1742                self.phase = Phase::Paused(Box::new(pending));
1743                return Ok(outcome);
1744            }
1745            self.confirmed(pending, response).await
1746        }
1747        .await;
1748        after_order(ids.as_ref(), outcome)?.into_step()
1749    }
1750
1751    /// Drop the paused job without sending anything. After an order the
1752    /// dialog is open for other jobs; after the login it has ended
1753    /// ([`Dialog::end`] still sends HKEND).
1754    ///
1755    /// The result says what is left at the bank. A read, the login and a
1756    /// transfer at its payee check are [`Cancelled::NothingSent`]: the bank
1757    /// lets the task expire (and a transfer's VOP-ID: a corrected payee
1758    /// name is a new transfer). A transfer waiting for its TAN is
1759    /// [`Cancelled::OrderSubmitted`]: its order is at the bank, and a late
1760    /// approval in the app may still execute it.
1761    pub fn cancel<T: JobValue>(&mut self, resume: Resume<T>) -> Result<Cancelled> {
1762        self.pending_for(&resume)?;
1763        let pending = self.take_pending();
1764        if pending.job.job() == Job::Open {
1765            self.phase = Phase::Ended;
1766        }
1767        Ok(match &pending.job {
1768            JobInput::Transfer(p) => p.cancelled(&pending.wait),
1769            _ => Cancelled::NothingSent,
1770        })
1771    }
1772
1773    /// End the dialog (HKEND, unless the bank already ended it) and return
1774    /// the updated session state: system ID, BPD/UPD, TAN method, codes
1775    /// learned from 9075. A paused dialog ends the same way. When a
1776    /// transfer's request was dropped mid-flight, it fails with
1777    /// [`FinTSError::PaymentOutcomeUnknown`] instead and sends nothing.
1778    pub async fn end(mut self) -> Result<SessionState> {
1779        self.check_in_flight()?;
1780        self.inner.end_quietly().await;
1781        Ok(self.capture_state())
1782    }
1783
1784    /// A snapshot of the session state as it is now: system ID, BPD/UPD,
1785    /// TAN method, codes learned from 9075. It sends nothing and changes
1786    /// nothing, so the dialog stays usable.
1787    ///
1788    /// The host stores it after [`open`] and after each job. A crash then
1789    /// keeps a freshly assigned system ID and the updated BPD/UPD, which
1790    /// [`Dialog::end`] would only hand over at the end. The snapshot is the
1791    /// state [`Dialog::end`] returns, minus whatever the dialog changes
1792    /// later.
1793    ///
1794    /// It also works while a transfer's request is in flight (a dropped
1795    /// future): it takes `&self` and sends nothing, and the pending
1796    /// [`FinTSError::PaymentOutcomeUnknown`] stays for the next call that
1797    /// sends, [`Dialog::end`] or [`Dialog::freeze`].
1798    pub fn session_state(&self) -> SessionState {
1799        self.capture_state()
1800    }
1801
1802    fn capture_state(&self) -> SessionState {
1803        SessionState::capture(
1804            self.inner.blz(),
1805            self.inner.user_id(),
1806            self.inner.system_id(),
1807            self.inner.bank_params(),
1808        )
1809    }
1810
1811    // ── Internals ──────────────────────────────────────────────────────
1812
1813    fn opened(&self) -> Opened {
1814        let p = self.inner.bank_params();
1815        Opened {
1816            accounts: p
1817                .upd()
1818                .map(|u| AccountInfo::from_upd(u, &self.bic))
1819                .unwrap_or_default(),
1820            tan_methods: p.tan_methods.clone(),
1821            allowed_security_functions: p.allowed_security_functions.clone(),
1822            selected_tan_method: p.selected_tan_method().cloned(),
1823        }
1824    }
1825
1826    /// A request was dropped mid-flight: the message number is unknown,
1827    /// so the dialog ends. When the request carried a payment, its outcome
1828    /// is unknown too: this call says so, the next one finds the dialog
1829    /// ended.
1830    fn check_in_flight(&mut self) -> Result<()> {
1831        let Some(in_flight) = self.in_flight.take() else {
1832            return Ok(());
1833        };
1834        warn!("[FinTS] A request was dropped mid-flight; the dialog has ended");
1835        self.end_locally();
1836        match in_flight {
1837            InFlight::Message => Ok(()),
1838            InFlight::Payment(ids) => Err(ids.unknown()),
1839        }
1840    }
1841
1842    /// The dialog is over and the bank will not take another message in it.
1843    fn end_locally(&mut self) {
1844        self.phase = Phase::Ended;
1845        self.inner.forget_dialog();
1846    }
1847
1848    /// Check before a new job: open, not paused, not ended.
1849    fn ready(&mut self) -> Result<()> {
1850        self.check_in_flight()?;
1851        match self.phase {
1852            Phase::Open => Ok(()),
1853            Phase::Paused(_) => Err(FinTSError::DialogPaused),
1854            Phase::Ended => Err(FinTSError::DialogEnded),
1855        }
1856    }
1857
1858    /// The pending job `resume` belongs to.
1859    fn pending_for<T: Sealed>(&mut self, resume: &Resume<T>) -> Result<&PendingJob> {
1860        self.check_in_flight()?;
1861        match &self.phase {
1862            Phase::Paused(p) if p.ticket == resume.ticket && p.job.job() == T::JOB => Ok(p),
1863            Phase::Ended => Err(FinTSError::DialogEnded),
1864            _ => Err(FinTSError::WrongResume),
1865        }
1866    }
1867
1868    fn take_pending(&mut self) -> PendingJob {
1869        match std::mem::replace(&mut self.phase, Phase::Open) {
1870            Phase::Paused(p) => *p,
1871            other => {
1872                self.phase = other;
1873                unreachable!("take_pending after pending_for")
1874            }
1875        }
1876    }
1877
1878    /// A job failed: an order leaves the dialog open, a failed login ends it.
1879    fn job_failed(&mut self, job: &JobInput) {
1880        if job.job() == Job::Open {
1881            self.phase = Phase::Ended;
1882        }
1883    }
1884
1885    /// After a request: record the response time, end the dialog when the
1886    /// bank did (9800) or the message state is unknown (transport error,
1887    /// unreadable answer).
1888    fn settle(&mut self, job: &JobInput, sent: Result<Response>) -> Result<Response> {
1889        self.settle_message(job.job() == Job::Open, sent)
1890    }
1891
1892    /// [`Dialog::settle`] for any message; `login` when a failure ends
1893    /// the dialog.
1894    fn settle_message(&mut self, login: bool, sent: Result<Response>) -> Result<Response> {
1895        self.in_flight = None;
1896        match sent {
1897            Ok(response) => {
1898                self.last_message_at = Timestamp::now();
1899                if response
1900                    .all_codes()
1901                    .any(|c| c.kind() == Kind::DialogAborted)
1902                {
1903                    self.end_locally();
1904                }
1905                Ok(response)
1906            }
1907            Err(e) => {
1908                if matches!(
1909                    e,
1910                    FinTSError::Transport { .. }
1911                        | FinTSError::Timeout
1912                        | FinTSError::Http { .. }
1913                        | FinTSError::Parse(_)
1914                        | FinTSError::InvalidResponse(_)
1915                        | FinTSError::Io(_)
1916                ) {
1917                    self.end_locally();
1918                } else if login {
1919                    self.phase = Phase::Ended;
1920                }
1921                Err(e)
1922            }
1923        }
1924    }
1925
1926    /// Pause on `challenge`; returns the `NeedTan` outcome.
1927    fn pause(
1928        &mut self,
1929        job: JobInput,
1930        challenge: &protocol::TanChallenge,
1931        notices: Vec<Notice>,
1932    ) -> Outcome {
1933        let tan = TanChallenge::from_bank(challenge, self.inner.bank_params(), Timestamp::now());
1934        let ticket = Ticket::Task(challenge.task_reference.clone());
1935        self.pause_on(job, Wait::Tan(tan), ticket, notices)
1936    }
1937
1938    /// Pause the job on `wait`; returns the matching outcome.
1939    fn pause_on(
1940        &mut self,
1941        job: JobInput,
1942        wait: Wait,
1943        ticket: Ticket,
1944        notices: Vec<Notice>,
1945    ) -> Outcome {
1946        let outcome = Outcome::Paused(wait.clone(), ticket.clone());
1947        self.phase = Phase::Paused(Box::new(PendingJob {
1948            ticket,
1949            wait,
1950            job,
1951            notices,
1952        }));
1953        outcome
1954    }
1955
1956    /// Start a job on an open dialog.
1957    async fn start(&mut self, job: JobInput) -> Result<Outcome> {
1958        self.start_with(job, Vec::new()).await
1959    }
1960
1961    /// [`start`](Self::start) with notices the client raised before
1962    /// sending.
1963    async fn start_with(&mut self, job: JobInput, notices: Vec<Notice>) -> Result<Outcome> {
1964        self.ready()?;
1965        // Nothing from earlier calls belongs to this job.
1966        self.inner.take_notices();
1967        self.send_order(job, notices).await
1968    }
1969
1970    /// Send the job's order (with HKTAN as `order_tan` decides, and the
1971    /// 9075 retry) and handle the answer: a challenge pauses the job, an
1972    /// error fails it, a page with more to come sends the next one, else
1973    /// the job is done.
1974    async fn send_order(&mut self, mut job: JobInput, mut notices: Vec<Notice>) -> Result<Outcome> {
1975        loop {
1976            let Some((segment, code, _)) = job.order() else {
1977                return Err(FinTSError::Internal("the login is not an order".into()));
1978            };
1979            self.in_flight = Some(InFlight::Message);
1980            let response = self.inner.send_order(segment, code).await;
1981            let response = self.settle(&job, response)?;
1982            notices.extend(self.inner.take_notices());
1983            if let Some(challenge) = response.order_tan_challenge()? {
1984                return Ok(self.pause(job, &challenge, notices));
1985            }
1986            response.check_errors()?;
1987            if !job.absorb(
1988                &response,
1989                &self.inner.bank_params().camt052_format(),
1990                &mut notices,
1991            ) {
1992                return Ok(Outcome::Done(
1993                    job.finish(&response, self.booking_id)?,
1994                    notices,
1995                ));
1996            }
1997        }
1998    }
1999
2000    /// The bank answered a TAN or a status request with something other
2001    /// than "still pending".
2002    async fn confirmed(&mut self, mut pending: PendingJob, response: Response) -> Result<Outcome> {
2003        extend_notices(&mut pending.notices, self.inner.take_notices());
2004        if let Err(e) = response.check_errors() {
2005            self.job_failed(&pending.job);
2006            return Err(e);
2007        }
2008        // A transfer ends with the answer to its TAN: never resent.
2009        if let JobInput::Transfer(p) = &pending.job {
2010            let receipt = p.receipt(&response, self.inner.bank_params(), self.inner.now().date());
2011            return Ok(Outcome::Done(Value::Transfer(receipt), pending.notices));
2012        }
2013        self.inner.ingest(&response);
2014        let PendingJob {
2015            mut job,
2016            mut notices,
2017            ..
2018        } = pending;
2019        match job.order() {
2020            None => Ok(Outcome::Done(Value::Opened(self.opened()), notices)),
2021            // 3010: "no entries", a complete answer without a data segment.
2022            Some((_, _, data))
2023                if response.find_segment(data).is_some()
2024                    || response.has_no_entries()
2025                    || (matches!(job, JobInput::InstantStatus { .. })
2026                        && response.has(Kind::InstantStatusQuery)) =>
2027            {
2028                if job.absorb(
2029                    &response,
2030                    &self.inner.bank_params().camt052_format(),
2031                    &mut notices,
2032                ) {
2033                    self.send_order(job, notices).await
2034                } else {
2035                    Ok(Outcome::Done(
2036                        job.finish(&response, self.booking_id)?,
2037                        notices,
2038                    ))
2039                }
2040            }
2041            Some((_, code, data)) => {
2042                info!("[FinTS] {code}: confirmation carried no {data}; sending the order again");
2043                self.send_order(job, notices).await
2044            }
2045        }
2046    }
2047}
2048
2049#[cfg(test)]
2050mod tests {
2051    use super::*;
2052    use jiff::civil::date;
2053
2054    #[test]
2055    fn range_is_clamped_to_the_storage_period() {
2056        let today = date(2026, 11, 18);
2057        let r = |from, to| Range::new(from, to);
2058        // 60 days before 2026-11-18 is 2026-09-19.
2059        let (clamped, asked) = clamp_range(r(date(2026, 1, 1), today), today, Some(60));
2060        assert_eq!(clamped, r(date(2026, 9, 19), today));
2061        assert_eq!(asked, Some(date(2026, 1, 1)));
2062        // Inside the period, on its edge, no period known: untouched.
2063        for (from, days) in [
2064            (date(2026, 10, 1), Some(60)),
2065            (date(2026, 9, 19), Some(60)),
2066            (date(2000, 1, 1), None),
2067        ] {
2068            assert_eq!(
2069                clamp_range(r(from, today), today, days),
2070                (r(from, today), None)
2071            );
2072        }
2073        // A range wholly before the period becomes one day.
2074        let (clamped, _) = clamp_range(r(date(2020, 1, 1), date(2020, 2, 1)), today, Some(60));
2075        assert_eq!(clamped, r(date(2026, 9, 19), date(2026, 9, 19)));
2076    }
2077
2078    /// A decoupled method asks for a typed TAN when the bank sends 0030
2079    /// without 3955 (PIN/TAN TAN-Prozess 4): only 3955 makes the challenge
2080    /// decoupled.
2081    #[test]
2082    fn only_3955_makes_a_challenge_decoupled() {
2083        use crate::types::{TanMethod, TanProcess};
2084        let mut params = BankParams::new();
2085        params.tan_methods = vec![TanMethod {
2086            security_function: SecurityFunction::new("901"),
2087            tan_process: TanProcess::TwoStep,
2088            name: "App".into(),
2089            needs_tan_medium: false,
2090            decoupled_max_polls: -1,
2091            wait_before_first_poll: 0,
2092            wait_before_next_poll: 0,
2093            is_decoupled: true,
2094            hktan_version: 7,
2095            zka_name: None,
2096            decoupled_auto_polling: None,
2097            challenge_structured: false,
2098        }];
2099        params.selected_security_function = SecurityFunction::new("901");
2100        let bank = |decoupled| protocol::TanChallenge {
2101            challenge: ChallengeText::new("TAN eingeben"),
2102            challenge_hhduc: None,
2103            task_reference: TaskReference::new("TASK-1"),
2104            decoupled,
2105            challenge_markup: false,
2106            valid_until: None,
2107        };
2108        let now = Timestamp::now();
2109        let typed = TanChallenge::from_bank(&bank(false), &params, now);
2110        assert!(matches!(typed.kind, TanKind::Typed { .. }), "{typed:?}");
2111        let app = TanChallenge::from_bank(&bank(true), &params, now);
2112        assert!(matches!(app.kind, TanKind::Decoupled { .. }), "{app:?}");
2113    }
2114
2115    /// One booked camt entry with the entry reference `reference`.
2116    fn camt_entry(reference: &str) -> Vec<u8> {
2117        format!(
2118            "<Document><BkToCstmrAcctRpt><Rpt><Ntry><Amt Ccy=\"EUR\">1.00</Amt>\
2119             <CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>\
2120             <BookgDt><Dt>2026-03-02</Dt></BookgDt>\
2121             <AcctSvcrRef>{reference}</AcctSvcrRef></Ntry></Rpt></BkToCstmrAcctRpt></Document>"
2122        )
2123        .into_bytes()
2124    }
2125
2126    fn ids(txs: &[Transaction]) -> Vec<Option<&str>> {
2127        txs.iter().map(|t| t.booking_id.as_deref()).collect()
2128    }
2129
2130    /// The profile rule reaches the booked camt part; the pending part gets
2131    /// no ID (its `Sts` says BOOK, the HICAZ field says pending), and a
2132    /// reference on two pages is dropped from both.
2133    #[test]
2134    fn statement_booking_ids_follow_the_rule_on_booked_camt_only() {
2135        let rule = BookingIdSource::CamtEntryAcctSvcrRef;
2136        let booked = [camt_entry("TESTREF-1"), camt_entry("TESTREF-2")];
2137        let pending = [camt_entry("TESTREF-3")];
2138        let s = parse_statement(StatementFormat::Camt, &booked, &pending, true, rule).unwrap();
2139        assert_eq!(ids(&s.booked), [Some("TESTREF-1"), Some("TESTREF-2")]);
2140        let Pending::Reported(p) = &s.pending else {
2141            panic!("{:?}", s.pending)
2142        };
2143        assert_eq!(ids(p), [None]);
2144
2145        let generic = BookingIdSource::None;
2146        let s = parse_statement(StatementFormat::Camt, &booked, &[], false, generic).unwrap();
2147        assert_eq!(ids(&s.booked), [None, None]);
2148
2149        let repeated = [camt_entry("TESTREF-1"), camt_entry("TESTREF-1")];
2150        let s = parse_statement(StatementFormat::Camt, &repeated, &[], false, rule).unwrap();
2151        assert_eq!(ids(&s.booked), [None, None]);
2152    }
2153
2154    /// MT940 never gives a booking ID, also with a `:61:` bank reference
2155    /// and the camt rule of a profile.
2156    #[test]
2157    fn mt940_bookings_never_get_a_booking_id() {
2158        let mt940 = b":20:STARTUMS\r\n:25:12030000/0000000201\r\n:28C:1\r\n\
2159            :60F:C260301EUR100,00\r\n\
2160            :61:2603020302D1,00NTRFNONREF//TESTBANKREF1\r\n:86:177?20SVWZ+Test\r\n\
2161            :62F:C260302EUR99,00\r\n-"
2162            .to_vec();
2163        let rule = BookingIdSource::CamtEntryAcctSvcrRef;
2164        let s = parse_statement(StatementFormat::Mt940, &[mt940], &[], false, rule).unwrap();
2165        assert_eq!(s.booked.len(), 1);
2166        assert_eq!(s.booked[0].bank_reference.as_deref(), Some("TESTBANKREF1"));
2167        assert_eq!(s.booked[0].booking_id, None);
2168    }
2169
2170    /// The paused job is plain data: it survives JSON unchanged.
2171    #[test]
2172    fn pending_job_round_trips_through_json() {
2173        let pending = PendingJob {
2174            ticket: Ticket::Task(TaskReference::new("TASK0001")),
2175            wait: Wait::Tan(TanChallenge {
2176                challenge: ChallengeText::new("Bitte in der App freigeben"),
2177                challenge_markup: false,
2178                kind: TanKind::Decoupled {
2179                    first_wait: Some(Duration::from_secs(5)),
2180                    next_wait: Some(Duration::from_secs(2)),
2181                    max_polls: Some(10),
2182                    polls_done: 3,
2183                    auto_polling_allowed: Some(false),
2184                },
2185                valid_until: None,
2186                not_before: Some(Timestamp::constant(1_740_830_405, 0)),
2187                payee_check: None,
2188                rejected: None,
2189            }),
2190            job: JobInput::Balance {
2191                account: Account::new("DE02120300000000202051", "BYLADEM1001").unwrap(),
2192            },
2193            notices: Vec::new(),
2194        };
2195        let json = serde_json::to_string(&pending).unwrap();
2196        let back: PendingJob = serde_json::from_str(&json).unwrap();
2197        assert_eq!(back.challenge(), pending.challenge());
2198        assert_eq!(back.ticket, pending.ticket);
2199        assert_eq!(back.job.job(), Job::Balance);
2200        assert_eq!(serde_json::to_string(&back).unwrap(), json);
2201    }
2202}