Skip to main content

fints_client/jobs/
transfer.rs

1//! The transfer job (docs/payments-design.md sections 2 and 3): HKCCS or
2//! HKIPZ with the payee check (HKVPP, HKVPA) and the TAN.
3//!
4//! Message 1 is `HKVPP + order + HKTAN:4` (or `order + HKTAN:4` when the
5//! BPD asks for no payee check), and its answer is classified by the
6//! table of design section 3.2: a rejection fails the job, an unfinished
7//! check pauses on [`Step::VopPending`], a check that is not a clean match
8//! pauses on [`Step::NeedVopConfirmation`], a clean match goes on to the
9//! TAN (or, after 3945, to the execution order `HKVPA + order + HKTAN:4`).
10//! The pain.001 bytes are built once and sent unchanged in every message
11//! that carries the order. The library never sends a payment twice.
12
13use jiff::civil::Time;
14
15use super::*;
16use crate::codec::defs::{HiIpz1, HiIpz2, HiVpp1};
17use crate::codec::{RawSegment, decode_segment};
18use crate::formats::pain001::{self, Pain001Descriptor, Pain001Version, PainIds};
19use crate::protocol::{FormatLists, VersionMismatch, VopDelivery};
20
21mod input;
22mod vop;
23pub use input::{
24    CheckedTransfer, Instant, InvalidReason, InvalidTransfer, Transfer, TransferField,
25};
26pub use vop::{PayeeOutcome, PayeeResult, VopResult};
27
28// ═══════════════════════════════════════════════════════════════════════════
29// Public values
30// ═══════════════════════════════════════════════════════════════════════════
31
32/// The value of [`transfer`]: how the bank took the payment.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct TransferReceipt {
35    pub sent_as: SentAs,
36    pub status: TransferStatus,
37    /// The day the order went out (the client's local date, or the one
38    /// pinned with [`BankClient::with_now`]). [`instant_status`] reads
39    /// the statement from this day when the bank offers no HKIPS.
40    pub sent_on: Date,
41    /// pain.001 `MsgId`, generated.
42    pub message_id: String,
43    /// `EndToEndId` as sent (the generated one when the transfer gave none).
44    pub end_to_end_id: String,
45    /// HIIPZ "Auftragsidentifikation" (instant payments).
46    pub order_id: Option<String>,
47    /// 3070 P1: the bank's reference for the order.
48    pub bank_reference: Option<String>,
49    /// What the bank reported for the payee; `None` when no HKVPP was sent.
50    pub payee_check: Option<VopResult>,
51}
52
53/// The order the payment went out as.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55pub enum SentAs {
56    /// HKCCS.
57    Standard,
58    /// HKIPZ.
59    Instant,
60    /// HKIPZ that the bank runs as a standard transfer (3270, allowed by
61    /// the conversion flag of HKIPZ 2).
62    InstantConverted,
63}
64
65/// Where the payment stands after the bank's last answer.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub enum TransferStatus {
68    /// Taken for processing (0010 or 3076 without 0020).
69    Accepted,
70    /// Executed (0020).
71    Executed,
72    /// Instant payment whose outcome the bank does not know yet (3045):
73    /// ask with [`instant_status`], not before `not_before` (HIIPSS
74    /// "Mindestwartezeit"; `None` when the bank gives none, also when it
75    /// offers no HKIPS and the status comes from the statement).
76    /// `order_id` is HIIPZ "Auftragsidentifikation", `None` when the bank
77    /// sent no HIIPZ.
78    InstantPending {
79        order_id: Option<String>,
80        not_before: Option<Timestamp>,
81    },
82}
83
84/// The payee check asks the user (anything but a clean match). Answer with
85/// [`Dialog::confirm_vop`] or [`Dialog::cancel`].
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct VopConfirmation {
88    /// The result; no payees when the bank reported none (3095).
89    pub result: VopResult,
90    /// HIVPP "Aufklärungstext": the bank requires it to be shown.
91    pub explanation: Option<String>,
92    /// HIVPPS "Aufklärungstext strukturiert": the text may hold `<br> <p>
93    /// <b> <i> <u> <ul> <ol> <li> <a href>`.
94    pub explanation_markup: bool,
95    /// HIVPP "VOP-ID gültig bis", bank local time.
96    pub valid_until: Option<DateTime>,
97}
98
99/// The payee check is not finished. Call [`Dialog::poll`] at or after
100/// `not_before` (`None`: the bank gave no wait; use your own).
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct VopWait {
103    pub not_before: Option<Timestamp>,
104    /// HKVPP polls sent so far (message 1 not counted).
105    pub polls_done: u32,
106}
107
108// ═══════════════════════════════════════════════════════════════════════════
109// The job as data
110// ═══════════════════════════════════════════════════════════════════════════
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113enum PaymentKind {
114    /// HKCCS.
115    Ccs,
116    /// HKIPZ at `version`; `convert` is HKIPZ 2's conversion flag.
117    Ipz { version: u16, convert: Option<bool> },
118}
119
120/// A transfer in flight: the pain.001 bytes as built, and the payee check
121/// so far. Part of a paused dialog (payments design 3.8).
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub(super) struct PaymentJob {
124    from: Account,
125    kind: PaymentKind,
126    /// The pain.001 descriptor as the bank announced it.
127    descriptor: String,
128    /// The pain.001 message, verbatim: every order segment carries these
129    /// bytes (VoP C.10.7.1.2).
130    #[serde(with = "utf8_bytes")]
131    pain: Vec<u8>,
132    message_id: String,
133    end_to_end_id: String,
134    payee_iban: Iban,
135    payee_name: String,
136    vop: Option<VopState>,
137    /// The next TAN message carries HKVPA (a TAN without 3945 and 3091).
138    hkvpa_with_tan: bool,
139}
140
141/// The payee check of a [`PaymentJob`].
142#[derive(Debug, Clone, Default, Serialize, Deserialize)]
143struct VopState {
144    /// The pain.002 descriptors HKVPP asks for.
145    descriptors: Vec<String>,
146    /// HIVPPS "Art der Lieferung" `S`: pain.002 parts are merged.
147    stepwise: bool,
148    explanation_markup: bool,
149    vop_id: Option<Vec<u8>>,
150    valid_until: Option<DateTime>,
151    polling_id: Option<Vec<u8>>,
152    touchdown: Option<String>,
153    polls_done: u32,
154    /// pain.002 documents received, in order.
155    parts: Vec<Vec<u8>>,
156    result: Option<VopResult>,
157    explanation: Option<String>,
158    /// 3090 in the final answer.
159    deviation: bool,
160    /// 3091 in the final answer.
161    not_required: bool,
162    /// The challenge of message 1 while the user decides on the result:
163    /// [`Dialog::confirm_vop`] returns it without sending when every payee
164    /// matched (the user was asked for 3090 or an explanation text).
165    live_tan: Option<(TaskReference, TanChallenge)>,
166}
167
168/// pain.001 is UTF-8 (the builder writes it): stored as a string.
169mod utf8_bytes {
170    use serde::{Deserialize, Deserializer, Serializer};
171
172    pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
173        let text = std::str::from_utf8(bytes).map_err(serde::ser::Error::custom)?;
174        s.serialize_str(text)
175    }
176
177    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
178        Ok(String::deserialize(d)?.into_bytes())
179    }
180}
181
182/// Which message the answer belongs to.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184enum Stage {
185    /// Message 1: `[HKVPP +] order + HKTAN:4`.
186    First,
187    /// HKVPP alone.
188    Poll,
189    /// `HKVPA + order + HKTAN:4`.
190    Execution,
191}
192
193/// The IDs of a payment whose order went out.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub(super) struct PaymentIds {
196    end_to_end_id: String,
197    message_id: String,
198}
199
200impl PaymentIds {
201    /// [`FinTSError::PaymentOutcomeUnknown`] for this payment.
202    pub(super) fn unknown(&self) -> FinTSError {
203        FinTSError::PaymentOutcomeUnknown {
204            end_to_end_id: self.end_to_end_id.clone(),
205            message_id: self.message_id.clone(),
206        }
207    }
208
209    /// An error after a message that carried the order or its TAN (design
210    /// D2): a class 9 rejection by the bank is definite, every other error
211    /// (transport, unreadable answer, unexpected answer) leaves the bank's
212    /// decision unknown.
213    pub(super) fn after_order(&self, e: FinTSError) -> FinTSError {
214        match e {
215            FinTSError::Bank(_) | FinTSError::PaymentOutcomeUnknown { .. } => e,
216            e => {
217                warn!("[FinTS] Payment outcome unknown: {e}");
218                self.unknown()
219            }
220        }
221    }
222}
223
224/// What follows an answer.
225enum Next {
226    Outcome(Outcome),
227    /// Send the execution order (design 3.3).
228    Execute(Box<PaymentJob>, Vec<Notice>),
229}
230
231impl PaymentJob {
232    /// Check the transfer, choose the order and the pain.001 version,
233    /// build the pain.001 with `ids` and `created` (`CreDtTm`). Sends
234    /// nothing.
235    fn prepare(
236        params: &BankParams,
237        t: &Transfer,
238        ids: &PainIds,
239        created: DateTime,
240    ) -> Result<Self> {
241        let holder = find_upd_account(params, &t.from)
242            .and_then(|a| a.owner.iter().find(|o| !o.trim().is_empty()))
243            .map(String::as_str);
244        let checked = t.check(holder)?;
245        let (kind, descriptor) = choose_order(params, t.instant)?;
246        let code = kind.code();
247        let vop = match params.bpd().and_then(|b| b.vop()) {
248            Some(v) if v.requires(code) => {
249                params.order_version(Order::VopCheck)?;
250                Some(VopState {
251                    descriptors: vop::choose_report_formats(v),
252                    // An unknown delivery code reads like complete delivery.
253                    stepwise: v.delivery == VopDelivery::Stepwise,
254                    explanation_markup: v.explanation_structured,
255                    ..VopState::default()
256                })
257            }
258            _ => None,
259        };
260        let instant = matches!(kind, PaymentKind::Ipz { .. });
261        let pain = pain001::build(&checked.pain_input(instant), &descriptor, ids, created);
262        info!(
263            "[FinTS] Transfer as {code} ({}), payee check: {}",
264            pain.descriptor,
265            if vop.is_some() { "yes" } else { "no" }
266        );
267        Ok(Self {
268            from: t.from.clone(),
269            kind,
270            descriptor: pain.descriptor,
271            pain: pain.xml,
272            message_id: pain.message_id,
273            end_to_end_id: checked.end_to_end_id().to_string(),
274            payee_iban: checked.payee_iban().clone(),
275            payee_name: checked.payee_name().to_string(),
276            vop,
277            hkvpa_with_tan: false,
278        })
279    }
280
281    fn code(&self) -> &'static str {
282        self.kind.code()
283    }
284
285    fn order_segment(&self) -> Segment {
286        match self.kind {
287            PaymentKind::Ccs => Segment::CreditTransfer {
288                account: self.from.clone(),
289                descriptor: self.descriptor.clone(),
290                pain: self.pain.clone(),
291            },
292            PaymentKind::Ipz { version, convert } => Segment::InstantTransfer {
293                account: self.from.clone(),
294                version,
295                descriptor: self.descriptor.clone(),
296                pain: self.pain.clone(),
297                convert,
298            },
299        }
300    }
301
302    /// HKVPA for the next TAN message, when the bank expects it.
303    pub(super) fn tan_extra(&self) -> Vec<Segment> {
304        match self.vop.as_ref().and_then(|v| v.vop_id.clone()) {
305            Some(vop_id) if self.hkvpa_with_tan => vec![Segment::VopExecute { vop_id }],
306            _ => Vec::new(),
307        }
308    }
309
310    /// HKVPA went out with a TAN message; later polls go without it.
311    pub(super) fn tan_extra_sent(&mut self) {
312        self.hkvpa_with_tan = false;
313    }
314
315    /// The IDs the order carries, for [`FinTSError::PaymentOutcomeUnknown`]
316    /// and [`Cancelled::OrderSubmitted`].
317    pub(super) fn ids(&self) -> PaymentIds {
318        PaymentIds {
319            end_to_end_id: self.end_to_end_id.clone(),
320            message_id: self.message_id.clone(),
321        }
322    }
323
324    /// What a cancel on `wait` leaves behind (design D1). At a TAN the
325    /// order is at the bank: a late approval in the app may execute it.
326    /// At the payee check nothing is released: the bank executes only
327    /// after the client's execution order (HKVPA, VoP C.10.7: "zeigt der
328    /// Kunde mit der Einreichung des Ausführungsauftrags (HKVPA) an, dass
329    /// er der Ausführung … zustimmt"), and an unfinished check has no
330    /// VOP-ID to release and no challenge yet. The exception is a live
331    /// decoupled challenge of message 1 that the bank releases without
332    /// HKVPA (3091): an approval in the app may execute it.
333    pub(super) fn cancelled(&self, wait: &Wait) -> Cancelled {
334        let at_tan = match wait {
335            Wait::Tan(_) => true,
336            Wait::VopConfirmation(_) => {
337                !self.hkvpa_with_tan
338                    && self.vop.as_ref().is_some_and(|v| {
339                        v.live_tan
340                            .as_ref()
341                            .is_some_and(|(_, c)| matches!(c.kind, TanKind::Decoupled { .. }))
342                    })
343            }
344            Wait::VopPoll(_) => false,
345        };
346        if !at_tan {
347            return Cancelled::NothingSent;
348        }
349        warn!("[FinTS] Transfer cancelled after its order went out: the bank may still execute it");
350        let PaymentIds {
351            end_to_end_id,
352            message_id,
353        } = self.ids();
354        Cancelled::OrderSubmitted {
355            end_to_end_id,
356            message_id,
357        }
358    }
359
360    fn payee_check(&self) -> Option<VopResult> {
361        self.vop.as_ref().and_then(|v| v.result.clone())
362    }
363
364    /// Every payee matched, the bank sent no 3090 and no explanation
365    /// (design 3.2). An empty result (3095, or a final HIVPP without one)
366    /// and a transfer without a payee check count as clean.
367    fn clean_match(&self) -> bool {
368        let Some(v) = &self.vop else { return true };
369        !v.deviation && v.explanation.is_none() && self.all_match()
370    }
371
372    /// No payee is reported other than `Match` (an empty result included).
373    fn all_match(&self) -> bool {
374        self.vop
375            .as_ref()
376            .and_then(|v| v.result.as_ref())
377            .is_none_or(VopResult::all_match)
378    }
379
380    fn confirmation(&self) -> VopConfirmation {
381        let v = self.vop.clone().unwrap_or_default();
382        VopConfirmation {
383            result: v.result.unwrap_or_else(VopResult::empty),
384            explanation: v.explanation,
385            explanation_markup: v.explanation_markup,
386            valid_until: v.valid_until,
387        }
388    }
389
390    /// The result of the final HIVPP ([`vop::read_result`]).
391    fn read_result(&self, hivpp: &HiVpp1) -> Result<Option<VopResult>> {
392        let Some(v) = &self.vop else { return Ok(None) };
393        let sent = vop::Sent {
394            message_id: &self.message_id,
395            end_to_end_id: &self.end_to_end_id,
396            iban: &self.payee_iban,
397            name: &self.payee_name,
398        };
399        vop::read_result(hivpp, &v.parts, v.stepwise, &sent)
400    }
401
402    /// The receipt from the answer that ended the job.
403    pub(super) fn receipt(
404        &self,
405        response: &Response,
406        params: &BankParams,
407        sent_on: Date,
408    ) -> TransferReceipt {
409        let order_id = read_hiipz(response);
410        let sent_as = match self.kind {
411            PaymentKind::Ccs => SentAs::Standard,
412            PaymentKind::Ipz { .. } if response.has(Kind::ConvertedToStandard) => {
413                SentAs::InstantConverted
414            }
415            PaymentKind::Ipz { .. } => SentAs::Instant,
416        };
417        let status = if response.has(Kind::InstantStatusQuery) {
418            let min_wait = params
419                .bpd()
420                .and_then(|b| b.instant())
421                .and_then(|i| i.status)
422                .map(|s| Duration::from_secs(u64::from(s.min_wait)));
423            TransferStatus::InstantPending {
424                order_id: order_id.clone(),
425                not_before: not_before_after(Timestamp::now(), min_wait),
426            }
427        } else if response
428            .segment_codes
429            .iter()
430            .any(|c| c.kind() == Kind::OrderExecuted)
431        {
432            TransferStatus::Executed
433        } else {
434            TransferStatus::Accepted
435        };
436        let bank_reference = response.all_codes().find_map(|c| match c.kind() {
437            Kind::ProcessingReference { reference } => reference,
438            _ => None,
439        });
440        TransferReceipt {
441            sent_as,
442            status,
443            sent_on,
444            message_id: self.message_id.clone(),
445            end_to_end_id: self.end_to_end_id.clone(),
446            order_id,
447            bank_reference,
448            payee_check: self.payee_check(),
449        }
450    }
451}
452
453impl PaymentKind {
454    fn code(self) -> &'static str {
455        match self {
456            Self::Ccs => "HKCCS",
457            Self::Ipz { .. } => "HKIPZ",
458        }
459    }
460}
461
462/// HKCCS or HKIPZ and the pain.001 version, before anything is sent
463/// (design section 2, "Instant choice").
464fn choose_order(params: &BankParams, instant: Instant) -> Result<(PaymentKind, Pain001Descriptor)> {
465    let standard = || -> Result<(PaymentKind, Pain001Descriptor)> {
466        params.order_version(Order::Transfer)?;
467        Ok((PaymentKind::Ccs, descriptor_for(params, Order::Transfer)?))
468    };
469    let instant_order = || -> Result<(PaymentKind, Pain001Descriptor)> {
470        let version = params.order_version(Order::InstantTransfer)?;
471        let descriptor = descriptor_for(params, Order::InstantTransfer)?;
472        let allowed = params
473            .bpd()
474            .and_then(|b| b.instant())
475            .is_some_and(|i| i.payment.conversion_allowed);
476        let convert = (version >= 2 && allowed).then_some(true);
477        Ok((PaymentKind::Ipz { version, convert }, descriptor))
478    };
479    match instant {
480        Instant::No => standard(),
481        Instant::Require => instant_order(),
482        Instant::Prefer => match instant_order() {
483            Err(FinTSError::VersionMismatch(why)) => {
484                info!("[FinTS] No instant payment ({why}); sending HKCCS");
485                standard()
486            }
487            other => other,
488        },
489    }
490}
491
492/// The pain.001 version for `order`, or a [`VersionMismatch`] on code
493/// `pain.001` with both lists. HKIPZ needs pain.001.001.09 (`INST`).
494pub(super) fn descriptor_for(params: &BankParams, order: Order) -> Result<Pain001Descriptor> {
495    let offered = params.bpd().map_or(&[][..], |b| b.sepa_formats(order));
496    let instant = matches!(order, Order::InstantTransfer | Order::InstantStatus);
497    pain001::choose_descriptor(offered, instant).ok_or_else(|| {
498        FinTSError::VersionMismatch(VersionMismatch {
499            code: SegmentType::new("pain.001"),
500            offered: Vec::new(),
501            implemented: Vec::new(),
502            formats: Some(Box::new(FormatLists {
503                offered: offered.to_vec(),
504                implemented: Pain001Version::ALL
505                    .iter()
506                    .filter(|v| !instant || **v != Pain001Version::V001_003_03)
507                    .map(|v| v.name().to_string())
508                    .collect(),
509            })),
510        })
511    })
512}
513
514fn read_hivpp(response: &Response) -> Result<Option<HiVpp1>> {
515    response
516        .find_segment("HIVPP")
517        .map(|raw| {
518            decode_segment::<HiVpp1>(raw)
519                .map(|(_, v)| v)
520                .map_err(FinTSError::SegmentUnreadable)
521        })
522        .transpose()
523}
524
525/// HIIPZ "Auftragsidentifikation"; an unreadable HIIPZ is logged, never
526/// an error (the payment is through).
527fn read_hiipz(response: &Response) -> Option<String> {
528    let raw: &RawSegment = response.find_segment("HIIPZ")?;
529    let id = decode_segment::<HiIpz2>(raw)
530        .map(|(_, v)| v.order_id)
531        .or_else(|_| decode_segment::<HiIpz1>(raw).map(|(_, v)| v.order_id));
532    match id {
533        Ok(id) => Some(id.as_str().to_string()),
534        Err(e) => {
535            warn!("[FinTS] HIIPZ unreadable: {e}");
536            None
537        }
538    }
539}
540
541fn local_time(t: &crate::codec::defs::Tsp1) -> DateTime {
542    t.date
543        .date()
544        .to_datetime(t.time.map_or(Time::MIN, |t| t.time()))
545}
546
547// ═══════════════════════════════════════════════════════════════════════════
548// The job
549// ═══════════════════════════════════════════════════════════════════════════
550
551/// Send `transfer` (payments design sections 2 and 3).
552///
553/// Checks first ([`Transfer::check`]; the debtor name falls back to the
554/// UPD holder) and chooses the order before anything is sent:
555/// [`Instant::No`] sends HKCCS, [`Instant::Require`] HKIPZ or
556/// [`FinTSError::VersionMismatch`], [`Instant::Prefer`] HKIPZ when the bank
557/// offers it with pain.001.001.09 (instant needs `INST`), else HKCCS. No
558/// pain.001 version in common is a `VersionMismatch` on code `pain.001`. When the BPD
559/// (HIVPPS) asks for a payee check on the order, HKVPP goes with it.
560///
561/// The step is [`Step::NeedTan`] (the payee matched or no check was
562/// needed; the challenge carries the result), [`Step::NeedVopConfirmation`]
563/// (show the result and ask the user), [`Step::VopPending`] (the bank is
564/// still checking; poll later) or `Done` when the bank waived the TAN.
565/// A transfer ends in one of three ways: a receipt, a definite rejection
566/// (a class 9 return code from the bank, or an error before anything was
567/// sent), or [`FinTSError::PaymentOutcomeUnknown`]. Once a message carried
568/// the order or its TAN, every other error (transport, unreadable HITAN,
569/// HIVPP or pain.002, an answer that fits no case) is an unknown outcome,
570/// and so are a [`Dialog::poll`] past `max_polls` and a dropped future;
571/// [`Dialog::cancel`] at the TAN says [`Cancelled::OrderSubmitted`]. Check
572/// the account by `end_to_end_id` and `message_id` before trying again;
573/// the library never resends a payment. A rejection leaves the dialog open.
574///
575/// Not cancel-safe (see [`Dialog`]): a dropped future loses the IDs of
576/// the order in flight until the next call reports them.
577pub async fn transfer(dialog: &mut Dialog, transfer: &Transfer) -> Result<Step<TransferReceipt>> {
578    dialog.ready()?;
579    let ids = PainIds::generate(Timestamp::now(), &mut rand::rng());
580    // CreDtTm: the machine's local time (payments design 5.4).
581    let created = dialog.inner.now();
582    let job = PaymentJob::prepare(dialog.bank_params(), transfer, &ids, created)?;
583    dialog.inner.take_notices();
584    dialog
585        .run_payment(job, Vec::new(), Stage::First)
586        .await?
587        .into_step()
588}
589
590impl Dialog {
591    /// Confirm the payee check result of the paused transfer: sends the
592    /// execution order (`HKVPA + order + HKTAN:4`) and returns its step,
593    /// usually `NeedTan`. When every payee matched (the user was asked
594    /// because of 3090 or an explanation text) and the bank's TAN of
595    /// message 1 is still live, returns `NeedTan` for that challenge
596    /// without sending. A payee that did not match always goes through the
597    /// execution order (VoP E.8.1 point 4), even when message 1 had a
598    /// challenge. On a job that waits for something else:
599    /// [`FinTSError::Dialog`], and the job stays paused.
600    ///
601    /// Not cancel-safe (see [`Dialog`]).
602    pub async fn confirm_vop<T: JobValue>(&mut self, resume: Resume<T>) -> Result<Step<T>> {
603        let pending = self.pending_for(&resume)?;
604        if !matches!(pending.wait, Wait::VopConfirmation(_)) {
605            return Err(FinTSError::Dialog(
606                "the job does not wait for a payee check confirmation".into(),
607            ));
608        }
609        let PendingJob { job, notices, .. } = self.take_pending();
610        let JobInput::Transfer(mut payment) = job else {
611            return Err(FinTSError::Internal(
612                "payee check confirmation without a transfer".into(),
613            ));
614        };
615        let all_match = payment.all_match();
616        let live_tan = payment.vop.as_mut().and_then(|v| v.live_tan.take());
617        if let Some((task_reference, challenge)) = live_tan.filter(|_| all_match) {
618            info!("[FinTS] Payee check confirmed; the TAN of message 1 is live");
619            return self
620                .pause_on(
621                    JobInput::Transfer(payment),
622                    Wait::Tan(challenge),
623                    Ticket::Task(task_reference),
624                    notices,
625                )
626                .into_step();
627        }
628        info!("[FinTS] Payee check confirmed; sending the execution order");
629        self.run_payment(*payment, notices, Stage::Execution)
630            .await?
631            .into_step()
632    }
633
634    /// The next HKVPP poll of a paused transfer.
635    pub(super) async fn vop_poll(&mut self, pending: PendingJob) -> Result<Outcome> {
636        let PendingJob { job, notices, .. } = pending;
637        let JobInput::Transfer(mut payment) = job else {
638            return Err(FinTSError::Internal(
639                "payee check poll without a transfer".into(),
640            ));
641        };
642        if let Some(v) = payment.vop.as_mut() {
643            v.polls_done += 1;
644        }
645        self.run_payment(*payment, notices, Stage::Poll).await
646    }
647
648    /// Send the payment messages from `stage` on until the job pauses or
649    /// ends. After a message that carried the order, every error but a
650    /// class 9 rejection is [`FinTSError::PaymentOutcomeUnknown`].
651    async fn run_payment(
652        &mut self,
653        mut job: PaymentJob,
654        mut notices: Vec<Notice>,
655        mut stage: Stage,
656    ) -> Result<Outcome> {
657        loop {
658            let ids = (stage != Stage::Poll).then(|| job.ids());
659            let next = self
660                .payment_round(job, notices, stage)
661                .await
662                .map_err(|e| match &ids {
663                    Some(ids) => ids.after_order(e),
664                    None => e,
665                })?;
666            match next {
667                Next::Outcome(outcome) => return Ok(outcome),
668                Next::Execute(j, n) => {
669                    (job, notices, stage) = (*j, n, Stage::Execution);
670                }
671            }
672        }
673    }
674
675    /// Send one payment message of `stage` and classify its answer.
676    async fn payment_round(
677        &mut self,
678        job: PaymentJob,
679        notices: Vec<Notice>,
680        stage: Stage,
681    ) -> Result<Next> {
682        let response = match stage {
683            Stage::Poll => {
684                let v = job
685                    .vop
686                    .as_ref()
687                    .ok_or_else(|| FinTSError::Internal("poll without a payee check".into()))?;
688                // VoP C.10.7.1.1 HKVPP field 3: the polling ID only
689                // next to a touchdown point.
690                let poll = Segment::VopCheck {
691                    descriptors: v.descriptors.clone(),
692                    polling_id: v.touchdown.as_ref().and(v.polling_id.clone()),
693                    touchdown: v.touchdown.clone(),
694                };
695                self.in_flight = Some(InFlight::Message);
696                let sent = self.inner.send_vop_poll(poll).await;
697                // Nothing was ordered by an HKVPP alone: plain errors.
698                self.settle_message(false, sent)?
699            }
700            Stage::First | Stage::Execution => {
701                let extra = match (stage, &job.vop) {
702                    (Stage::First, Some(v)) => vec![Segment::VopCheck {
703                        descriptors: v.descriptors.clone(),
704                        polling_id: None,
705                        touchdown: None,
706                    }],
707                    (Stage::First, None) => Vec::new(),
708                    _ => {
709                        let vop_id =
710                            job.vop
711                                .as_ref()
712                                .and_then(|v| v.vop_id.clone())
713                                .ok_or_else(|| {
714                                    FinTSError::Internal("execution order without VOP-ID".into())
715                                })?;
716                        vec![Segment::VopExecute { vop_id }]
717                    }
718                };
719                self.in_flight = Some(InFlight::Payment(job.ids()));
720                let sent = self
721                    .inner
722                    .send_payment(&extra, job.order_segment(), job.code())
723                    .await;
724                self.settle_message(false, sent)?
725            }
726        };
727        self.payment_answer(job, &response, notices, stage)
728    }
729
730    /// Classify an answer by the table of design section 3.2.
731    fn payment_answer(
732        &mut self,
733        mut job: PaymentJob,
734        response: &Response,
735        mut notices: Vec<Notice>,
736        stage: Stage,
737    ) -> Result<Next> {
738        // Every submission of a payee-checked transfer (HKVPP, HKVPA, each
739        // status request) can carry the same 3060; one is enough.
740        super::extend_notices(&mut notices, self.inner.take_notices());
741        // After the order, `run_payment` turns every error but a class 9
742        // rejection into an unknown outcome.
743        response.check_errors()?;
744        let checked = stage != Stage::Execution && job.vop.is_some();
745        let challenge = response.order_tan_challenge()?;
746        if checked {
747            let hivpp = read_hivpp(response)?;
748            if let (Some(report), Some(v)) = (
749                hivpp.as_ref().and_then(|h| h.report.as_ref()),
750                job.vop.as_mut(),
751            ) {
752                v.parts.push(report.0.clone());
753            }
754            // Final only with a VOP-ID (VoP C.10.7.1.1: "bis eine
755            // abschließende Antwort (HIVPP mit VOP-ID) vorliegt"); an
756            // answer with a challenge is never a poll. Polling ID and
757            // touchdown point are both optional.
758            let pending = response.has(Kind::VopInProgress)
759                || (challenge.is_none() && hivpp.as_ref().is_some_and(|h| h.vop_id.is_none()));
760            if pending {
761                let wait = hivpp
762                    .as_ref()
763                    .and_then(|h| h.wait)
764                    .map(|w| Duration::from_secs(w.value()));
765                let v = job.vop.as_mut().expect("checked");
766                v.polling_id = hivpp
767                    .as_ref()
768                    .and_then(|h| h.polling_id.as_ref())
769                    .map(|p| p.0.clone());
770                v.touchdown = response.touchdown().map(|t| t.as_str().to_string());
771                let wait = VopWait {
772                    not_before: not_before_after(Timestamp::now(), wait),
773                    polls_done: v.polls_done,
774                };
775                info!("[FinTS] Payee check in progress");
776                return Ok(Next::Outcome(self.pause_on(
777                    JobInput::Transfer(Box::new(job)),
778                    Wait::VopPoll(wait),
779                    Ticket::local(),
780                    notices,
781                )));
782            }
783            let result = match &hivpp {
784                Some(h) => job.read_result(h)?,
785                None => None,
786            };
787            let v = job.vop.as_mut().expect("checked");
788            if let Some(h) = hivpp {
789                v.vop_id = h.vop_id.map(|b| b.0);
790                v.valid_until = h.vop_id_valid_until.as_ref().map(local_time);
791                v.explanation = h
792                    .explanation
793                    .map(|e| e.as_str().to_string())
794                    .filter(|e| !e.trim().is_empty());
795            }
796            // A final answer without a result: the bank had none to give
797            // (3095; VoP C.10.7.1.1 "HIVPP ohne befüllte
798            // VOP-Prüfergebnisse"), shown as an empty result.
799            v.result = Some(result.unwrap_or_else(VopResult::empty));
800            v.polling_id = None;
801            v.touchdown = None;
802            v.deviation = response.has(Kind::VopCheckResult);
803            v.not_required = response.has(Kind::VopNotRequired);
804        }
805        // After the final poll, or 3945: the execution order is next.
806        if checked
807            && (stage == Stage::Poll
808                || (challenge.is_none() && response.has(Kind::VopApprovalNotPossible)))
809        {
810            if job.clean_match() {
811                return Ok(Next::Execute(Box::new(job), notices));
812            }
813            return Ok(Next::Outcome(self.ask_vop(job, None, notices)));
814        }
815        if let Some(challenge) = challenge {
816            let mut tan =
817                TanChallenge::from_bank(&challenge, self.inner.bank_params(), Timestamp::now());
818            tan.payee_check = job.payee_check();
819            job.hkvpa_with_tan = checked
820                && job
821                    .vop
822                    .as_ref()
823                    .is_some_and(|v| !v.not_required && v.vop_id.is_some());
824            let task_reference = challenge.task_reference;
825            if checked && !job.clean_match() {
826                return Ok(Next::Outcome(self.ask_vop(
827                    job,
828                    Some((task_reference, tan)),
829                    notices,
830                )));
831            }
832            return Ok(Next::Outcome(self.pause_on(
833                JobInput::Transfer(Box::new(job)),
834                Wait::Tan(tan),
835                Ticket::Task(task_reference),
836                notices,
837            )));
838        }
839        // No challenge: the bank executed or took the order without SCA
840        // (3076), which needs its 0010/0020.
841        let taken = response.has_sca_exemption()
842            || response
843                .segment_codes
844                .iter()
845                .any(|c| matches!(c.kind(), Kind::OrderExecuted | Kind::MessageReceived));
846        if !taken {
847            return Err(FinTSError::InvalidResponse(
848                "payment answer without challenge or confirmation".into(),
849            ));
850        }
851        let receipt = job.receipt(response, self.inner.bank_params(), self.inner.now().date());
852        Ok(Next::Outcome(Outcome::Done(
853            Value::Transfer(receipt),
854            notices,
855        )))
856    }
857
858    /// Pause on the user's decision about the payee check result.
859    fn ask_vop(
860        &mut self,
861        mut job: PaymentJob,
862        live_tan: Option<(TaskReference, TanChallenge)>,
863        notices: Vec<Notice>,
864    ) -> Outcome {
865        info!("[FinTS] Payee check: asking the user");
866        let confirmation = job.confirmation();
867        if let Some(v) = job.vop.as_mut() {
868            v.live_tan = live_tan;
869        }
870        self.pause_on(
871            JobInput::Transfer(Box::new(job)),
872            Wait::VopConfirmation(confirmation),
873            Ticket::local(),
874            notices,
875        )
876    }
877}