Skip to main content

fints_client/jobs/
instant_status.rs

1//! The instant payment status job (docs/payments-design.md 3.7): HKIPS asks
2//! how an HKIPZ ended up, HIIPS answers with "Status SEPA-Auftrag". A bank
3//! that offers HKIPZ without HKIPS gets the statement read instead, and the
4//! payment is looked up by its end-to-end ID.
5
6use super::transfer::descriptor_for;
7use super::*;
8use crate::codec::decode_segment;
9use crate::codec::defs::HiIps1;
10
11/// "Status SEPA-Auftrag" (Messages 2022, data dictionary, version 2; codes
12/// 1 to 5 are the version 1 list).
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[non_exhaustive]
15pub enum SepaOrderStatus {
16    /// `1`: in Terminierung.
17    Scheduled,
18    /// `2`: abgelehnt von erster Inkassostelle.
19    RejectedByFirstCollector,
20    /// `3`: in Bearbeitung.
21    InProcess,
22    /// `4`: creditor side processed, booking initiated.
23    Processed,
24    /// `5`: a return (R-Transaktion) was initiated.
25    ReturnInitiated,
26    /// `6`: Auftrag fehlgeschlagen.
27    Failed,
28    /// `7`: executed; the money is available to the payee.
29    Executed,
30    /// `8`: rejected by the payer's payment service provider.
31    RejectedByPayerPsp,
32    /// `9`: rejected by the payee's payment service provider.
33    RejectedByPayeePsp,
34    /// A code outside the list.
35    Other(String),
36}
37
38impl SepaOrderStatus {
39    fn from_code(code: &str) -> Self {
40        match code {
41            "1" => Self::Scheduled,
42            "2" => Self::RejectedByFirstCollector,
43            "3" => Self::InProcess,
44            "4" => Self::Processed,
45            "5" => Self::ReturnInitiated,
46            "6" => Self::Failed,
47            "7" => Self::Executed,
48            "8" => Self::RejectedByPayerPsp,
49            "9" => Self::RejectedByPayeePsp,
50            other => Self::Other(other.to_string()),
51        }
52    }
53}
54
55/// The value of [`instant_status`].
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct InstantStatus {
58    /// The bank's status; `None` when the bank answered 3045 (ask again),
59    /// sent no status, or the statement does not show the payment yet.
60    pub status: Option<SepaOrderStatus>,
61    /// With 3045: ask again not before this (arrival plus HIIPSS
62    /// "Mindestwartezeit"); `None` without 3045 or without HIIPSS.
63    pub again_after: Option<Timestamp>,
64    /// Where `status` comes from.
65    pub source: StatusSource,
66}
67
68/// Where an [`InstantStatus`] comes from.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum StatusSource {
72    /// HIIPS, the bank's answer to HKIPS.
73    StatusRequest,
74    /// The account's statement from [`TransferReceipt::sent_on`] to today
75    /// (HKCAZ or HKKAZ), searched for a debit with the payment's
76    /// end-to-end ID: used when the bank offers no HKIPS, or the receipt
77    /// has no order ID to ask with. A booked debit is
78    /// [`SepaOrderStatus::Executed`], a pending one
79    /// [`SepaOrderStatus::InProcess`], none found is `None`: check again
80    /// later or look at the account. The client's reading, not the bank's
81    /// word.
82    Statement,
83}
84
85/// The status of the instant payment of `receipt` sent from `from`.
86///
87/// With HKIPS in the BPD and an order ID on the receipt (HIIPZ
88/// "Auftragsidentifikation"), the bank is asked (HKIPS). Still open: 3045,
89/// the value has `status: None` and `again_after`.
90///
91/// Without HKIPS, or without an order ID, the account's statement from
92/// `receipt.sent_on` to today is read and searched for the payment's
93/// end-to-end ID ([`StatusSource::Statement`]).
94///
95/// Either order follows the usual TAN rule, so the step can be `NeedTan`.
96/// Fails with [`FinTSError::NoBpd`] or [`FinTSError::VersionMismatch`] before
97/// anything is sent.
98pub async fn instant_status(
99    dialog: &mut Dialog,
100    from: &Account,
101    receipt: &TransferReceipt,
102) -> Result<Step<InstantStatus>> {
103    dialog.ready()?;
104    let params = dialog.bank_params();
105    let order_id = match (
106        params.order_version(Order::InstantStatus),
107        &receipt.order_id,
108    ) {
109        (Err(e @ FinTSError::NoBpd { .. }), _) => return Err(e),
110        (Ok(_), Some(id)) => id.clone(),
111        _ => return from_account(dialog, from, receipt).await,
112    };
113    let descriptor = descriptor_for(params, Order::InstantStatus)?;
114    let min_wait = params
115        .bpd()
116        .and_then(|b| b.instant())
117        .and_then(|i| i.status)
118        .map(|s| s.min_wait);
119    dialog
120        .start(JobInput::InstantStatus {
121            account: from.clone(),
122            descriptors: vec![descriptor.announced],
123            order_id,
124            min_wait,
125        })
126        .await?
127        .into_step()
128}
129
130/// The job's value from the bank's answer.
131pub(super) fn read(response: &Response, min_wait: Option<u32>) -> Result<InstantStatus> {
132    let status = response
133        .find_segment("HIIPS")
134        .map(|raw| {
135            decode_segment::<HiIps1>(raw)
136                .map(|(_, v)| v)
137                .map_err(FinTSError::SegmentUnreadable)
138        })
139        .transpose()?
140        .and_then(|s| s.status)
141        .map(|c| SepaOrderStatus::from_code(c.as_str()));
142    if !response.has(Kind::InstantStatusQuery) {
143        return Ok(InstantStatus {
144            status,
145            again_after: None,
146            source: StatusSource::StatusRequest,
147        });
148    }
149    let wait = min_wait.map(|s| Duration::from_secs(u64::from(s)));
150    Ok(InstantStatus {
151        status: None,
152        again_after: not_before_after(Timestamp::now(), wait),
153        source: StatusSource::StatusRequest,
154    })
155}
156
157/// The statement job that looks for the payment of `receipt`.
158async fn from_account(
159    dialog: &mut Dialog,
160    from: &Account,
161    receipt: &TransferReceipt,
162) -> Result<Step<InstantStatus>> {
163    info!("[FinTS] No HKIPS for this payment: reading the statement instead");
164    let format = choose_format(dialog.bank_params(), from, Format::Auto)?;
165    let today = dialog.inner.now().date();
166    dialog
167        .start(JobInput::Transactions {
168            account: from.clone(),
169            range: Range::new(receipt.sent_on.min(today), today),
170            format,
171            touchdown: None,
172            booked: Vec::new(),
173            pending: Vec::new(),
174            pending_sent: false,
175            find_payment: Some(receipt.end_to_end_id.clone()),
176        })
177        .await?
178        .into_step()
179}
180
181/// The status of the payment with end-to-end ID `id` as `statement` shows
182/// it: a booked debit is executed, a pending one in process.
183pub(super) fn from_statement(statement: &Statement, id: &str) -> InstantStatus {
184    let ours =
185        |t: &Transaction| t.amount.is_sign_negative() && t.end_to_end_id.as_deref() == Some(id);
186    let pending = match &statement.pending {
187        Pending::Reported(p) => p.as_slice(),
188        _ => &[],
189    };
190    let status = if statement.booked.iter().any(ours) {
191        Some(SepaOrderStatus::Executed)
192    } else if pending.iter().any(ours) {
193        Some(SepaOrderStatus::InProcess)
194    } else {
195        None
196    };
197    InstantStatus {
198        status,
199        again_after: None,
200        source: StatusSource::Statement,
201    }
202}