Skip to main content

fints_client/jobs/transfer/
vop.rs

1//! The payee check (Verification of Payee, VoP) result of a transfer: the
2//! types the caller sees, the pain.002 formats HKVPP asks for, and reading
3//! one result from an HIVPP (pain.002 parts or the single-transaction DEG;
4//! docs/payments-design.md sections 3 and 5.3).
5
6use serde::{Deserialize, Serialize};
7
8use crate::codec::An;
9use crate::codec::defs::HiVpp1;
10use crate::error::{FinTSError, Result};
11use crate::formats::pain002::{self, SentTx};
12use crate::protocol::VopParams;
13use crate::types::Iban;
14
15/// What the bank reported for the payees of one order.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct VopResult {
18    /// One entry per transaction; one for a single transfer. Empty when the
19    /// bank delivered no result (3095, VoP C.10.7.1.1: "HIVPP ohne
20    /// befüllte VOP-Prüfergebnisse").
21    pub payees: Vec<PayeeResult>,
22    /// Notes for the payer from the report (pain.002 group
23    /// `StsRsnInf/AddtlInf`, Anlage 3 2.2.6.4), each line starting with the
24    /// status it explains (`RVNM …`). Empty for the HIVPP DEG, whose
25    /// explanation text is a separate HIVPP field.
26    pub notes: Vec<String>,
27}
28
29impl VopResult {
30    /// No payees, no notes.
31    pub fn empty() -> Self {
32        Self {
33            payees: Vec::new(),
34            notes: Vec::new(),
35        }
36    }
37
38    /// Whether some payee still waits for the payee's bank (`PDNG`).
39    pub fn is_pending(&self) -> bool {
40        self.payees.iter().any(|p| p.outcome.is_pending())
41    }
42
43    /// Whether every payee matched (`RCVC`); true for an empty result.
44    pub fn all_match(&self) -> bool {
45        self.payees.iter().all(|p| p.outcome.is_match())
46    }
47}
48
49/// The check of one payee.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct PayeeResult {
52    /// Normalised (upper case, no spaces).
53    pub iban: String,
54    /// The name sent in the order.
55    pub requested_name: String,
56    pub outcome: PayeeOutcome,
57}
58
59/// Result of one payee check (Anlage 3 2.2.6.7; VoP D "VOP-Prüfergebnis").
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub enum PayeeOutcome {
62    /// `RCVC`: the name matches the account holder.
63    Match,
64    /// `RVMC`: the name matches partly; the registered name when the bank
65    /// gives it.
66    CloseMatch { registered_name: Option<String> },
67    /// `RVNM`: the name does not match.
68    NoMatch,
69    /// `RVNA`: no check possible (not a payment account, payee bank outside
70    /// VoP, timeout); the bank's reason when given.
71    NotApplicable { reason: Option<String> },
72    /// `PDNG`: the payee's bank has not answered yet (only in an unfinished
73    /// result).
74    Pending,
75    /// Another identifier than the name was checked (e.g. LEI): its name
76    /// and the outcome for it.
77    OtherId {
78        id_name: String,
79        outcome: Box<PayeeOutcome>,
80    },
81}
82
83impl PayeeOutcome {
84    pub fn is_pending(&self) -> bool {
85        match self {
86            Self::Pending => true,
87            Self::OtherId { outcome, .. } => outcome.is_pending(),
88            _ => false,
89        }
90    }
91
92    pub fn is_match(&self) -> bool {
93        match self {
94            Self::Match => true,
95            Self::OtherId { outcome, .. } => outcome.is_match(),
96            _ => false,
97        }
98    }
99
100    /// From a status code and its detail (RVMC: registered name, RVNA:
101    /// reason). `None` for codes that are not transaction results.
102    fn from_code(code: &str, detail: Option<String>) -> Option<Self> {
103        Some(match code {
104            "RCVC" => Self::Match,
105            "RVMC" => Self::CloseMatch {
106                registered_name: detail,
107            },
108            "RVNM" => Self::NoMatch,
109            "RVNA" => Self::NotApplicable { reason: detail },
110            "PDNG" => Self::Pending,
111            _ => return None,
112        })
113    }
114}
115
116/// The pain.002 descriptors HKVPP asks for: those of the HIVPPS list that
117/// name pain.002.001.10 (the version the reader knows), else the whole list
118/// (the bank may still answer with the DEG).
119pub(super) fn choose_report_formats(params: &VopParams) -> Vec<String> {
120    let readable: Vec<String> = params
121        .report_formats
122        .iter()
123        .filter(|f| f.contains("pain.002.001.10"))
124        .cloned()
125        .collect();
126    if readable.is_empty() {
127        params.report_formats.clone()
128    } else {
129        readable
130    }
131}
132
133/// The transfer a result answers.
134#[derive(Debug, Clone, Copy)]
135pub(super) struct Sent<'a> {
136    /// pain.001 `MsgId`.
137    pub message_id: &'a str,
138    pub end_to_end_id: &'a str,
139    pub iban: &'a Iban,
140    pub name: &'a str,
141}
142
143/// The result of a final HIVPP: the pain.002 `parts` received so far (the
144/// last one with complete delivery, all merged with `stepwise` delivery),
145/// else the HIVPP single-transaction DEG. `None` when the bank sent
146/// neither.
147pub(super) fn read_result(
148    hivpp: &HiVpp1,
149    parts: &[Vec<u8>],
150    stepwise: bool,
151    sent: &Sent<'_>,
152) -> Result<Option<VopResult>> {
153    if let Some(last) = parts.last() {
154        let parts: Vec<&[u8]> = if stepwise {
155            parts.iter().map(Vec::as_slice).collect()
156        } else {
157            vec![last.as_slice()]
158        };
159        let tx = [SentTx {
160            end_to_end_id: sent.end_to_end_id,
161            iban: sent.iban.as_str(),
162            name: sent.name,
163        }];
164        let report = pain002::read(&parts, sent.message_id, &tx)?;
165        let payees = report
166            .transactions
167            .into_iter()
168            .map(|t| PayeeResult {
169                outcome: PayeeOutcome::from_code(t.status, t.detail)
170                    .expect("pain002 returns known statuses"),
171                iban: t.iban,
172                requested_name: t.requested_name,
173            })
174            .collect();
175        return Ok(Some(VopResult {
176            payees,
177            notes: report.notes,
178        }));
179    }
180    let Some(deg) = &hivpp.result else {
181        return Ok(None);
182    };
183    let text = |a: &Option<An>| {
184        a.as_ref()
185            .map(|a| a.as_str().trim())
186            .filter(|s| !s.is_empty())
187            .map(str::to_string)
188    };
189    let code = deg.outcome.as_str().trim();
190    let detail = match code {
191        "RVMC" => text(&deg.registered_name),
192        "RVNA" => text(&deg.rvna_reason),
193        _ => None,
194    };
195    let outcome = PayeeOutcome::from_code(code, detail).ok_or_else(|| {
196        FinTSError::InvalidResponse(format!("HIVPP: unknown VOP result {code:?}"))
197    })?;
198    let outcome = match text(&deg.other_id) {
199        Some(id_name) => PayeeOutcome::OtherId {
200            id_name,
201            outcome: Box::new(outcome),
202        },
203        None => outcome,
204    };
205    let iban: String = deg
206        .iban
207        .as_str()
208        .chars()
209        .filter(|c| !c.is_whitespace())
210        .collect::<String>()
211        .to_ascii_uppercase();
212    if iban.is_empty() {
213        return Err(FinTSError::InvalidResponse(
214            "HIVPP: VOP result without IBAN".into(),
215        ));
216    }
217    Ok(Some(VopResult {
218        payees: vec![PayeeResult {
219            iban,
220            requested_name: sent.name.to_string(),
221            outcome,
222        }],
223        notes: Vec::new(),
224    }))
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::codec::defs::PayeeCheckResult1;
231    use crate::codec::{Bin, Code};
232
233    const MSG: &str = "FC20261117091530ABCDEFGH";
234
235    fn iban() -> Iban {
236        Iban::parse("DE89370400440532013000").unwrap()
237    }
238
239    fn hivpp(result: Option<PayeeCheckResult1>) -> HiVpp1 {
240        HiVpp1 {
241            vop_id: Some(Bin(b"VOPID".to_vec())),
242            vop_id_valid_until: None,
243            polling_id: None,
244            report_descriptor: None,
245            report: None,
246            result,
247            explanation: None,
248            wait: None,
249        }
250    }
251
252    fn deg(outcome: &str) -> PayeeCheckResult1 {
253        PayeeCheckResult1 {
254            iban: An::new("DE89370400440532013000").unwrap(),
255            iban_info: None,
256            registered_name: None,
257            other_id: None,
258            outcome: Code::new(outcome).unwrap(),
259            rvna_reason: None,
260        }
261    }
262
263    fn read(h: &HiVpp1, parts: &[Vec<u8>]) -> Result<Option<VopResult>> {
264        let iban = iban();
265        let sent = Sent {
266            message_id: MSG,
267            end_to_end_id: "NOTPROVIDED",
268            iban: &iban,
269            name: "Max Muster",
270        };
271        read_result(h, parts, false, &sent)
272    }
273
274    fn outcome(d: PayeeCheckResult1) -> Result<PayeeOutcome> {
275        read(&hivpp(Some(d)), &[]).map(|r| r.unwrap().payees[0].outcome.clone())
276    }
277
278    #[test]
279    fn deg_outcomes() {
280        assert_eq!(outcome(deg("RCVC")).unwrap(), PayeeOutcome::Match);
281        assert_eq!(outcome(deg("RVNM")).unwrap(), PayeeOutcome::NoMatch);
282        assert_eq!(outcome(deg("PDNG")).unwrap(), PayeeOutcome::Pending);
283        let mut d = deg("RVNA");
284        d.rvna_reason = Some(An::new("Zeitueberschreitung").unwrap());
285        assert_eq!(
286            outcome(d).unwrap(),
287            PayeeOutcome::NotApplicable {
288                reason: Some("Zeitueberschreitung".into())
289            }
290        );
291        assert_eq!(
292            outcome(deg("RVMC")).unwrap(),
293            PayeeOutcome::CloseMatch {
294                registered_name: None
295            }
296        );
297        let mut d = deg("RCVC");
298        d.other_id = Some(An::new("LEI").unwrap());
299        assert_eq!(
300            outcome(d).unwrap(),
301            PayeeOutcome::OtherId {
302                id_name: "LEI".into(),
303                outcome: Box::new(PayeeOutcome::Match)
304            }
305        );
306        assert!(matches!(
307            outcome(deg("XXXX")),
308            Err(FinTSError::InvalidResponse(_))
309        ));
310        let mut d = deg("RCVC");
311        d.iban = An::new("").unwrap();
312        assert!(matches!(outcome(d), Err(FinTSError::InvalidResponse(_))));
313        // Neither DEG nor report.
314        assert_eq!(read(&hivpp(None), &[]).unwrap(), None);
315    }
316
317    /// The DEG and the pain.002 give the same result for the same answer.
318    #[test]
319    fn deg_and_pain_agree() {
320        let mut d = deg("RVMC");
321        d.registered_name = Some(An::new("Maximilian Muster").unwrap());
322        let from_deg = read(&hivpp(Some(d)), &[]).unwrap();
323        let xml = format!(
324            r#"<?xml version="1.0" encoding="UTF-8"?>
325<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.002.001.10"><CstmrPmtStsRpt>
326<GrpHdr><MsgId>BANK-PSR-1</MsgId><CreDtTm>2026-11-17T10:15:31</CreDtTm></GrpHdr>
327<OrgnlGrpInfAndSts><OrgnlMsgId>{MSG}</OrgnlMsgId><OrgnlMsgNmId>pain.001.001.09</OrgnlMsgNmId>
328<GrpSts>RVCM</GrpSts></OrgnlGrpInfAndSts>
329<OrgnlPmtInfAndSts><OrgnlPmtInfId>P</OrgnlPmtInfId><TxInfAndSts>
330<OrgnlEndToEndId>NOTPROVIDED</OrgnlEndToEndId><TxSts>RVMC</TxSts>
331<StsRsnInf><AddtlInf>Maximilian Muster</AddtlInf></StsRsnInf>
332<OrgnlTxRef><Cdtr><Pty><Nm>Max Muster</Nm></Pty></Cdtr>
333<CdtrAcct><Id><IBAN>DE89370400440532013000</IBAN></Id></CdtrAcct></OrgnlTxRef>
334</TxInfAndSts></OrgnlPmtInfAndSts></CstmrPmtStsRpt></Document>"#
335        );
336        let from_pain = read(&hivpp(Some(deg("RCVC"))), &[xml.into_bytes()]).unwrap();
337        assert_eq!(from_pain, from_deg, "the report wins over the DEG");
338    }
339}