1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct TransferReceipt {
35 pub sent_as: SentAs,
36 pub status: TransferStatus,
37 pub sent_on: Date,
41 pub message_id: String,
43 pub end_to_end_id: String,
45 pub order_id: Option<String>,
47 pub bank_reference: Option<String>,
49 pub payee_check: Option<VopResult>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55pub enum SentAs {
56 Standard,
58 Instant,
60 InstantConverted,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub enum TransferStatus {
68 Accepted,
70 Executed,
72 InstantPending {
79 order_id: Option<String>,
80 not_before: Option<Timestamp>,
81 },
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct VopConfirmation {
88 pub result: VopResult,
90 pub explanation: Option<String>,
92 pub explanation_markup: bool,
95 pub valid_until: Option<DateTime>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct VopWait {
103 pub not_before: Option<Timestamp>,
104 pub polls_done: u32,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113enum PaymentKind {
114 Ccs,
116 Ipz { version: u16, convert: Option<bool> },
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
123pub(super) struct PaymentJob {
124 from: Account,
125 kind: PaymentKind,
126 descriptor: String,
128 #[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 hkvpa_with_tan: bool,
139}
140
141#[derive(Debug, Clone, Default, Serialize, Deserialize)]
143struct VopState {
144 descriptors: Vec<String>,
146 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 parts: Vec<Vec<u8>>,
156 result: Option<VopResult>,
157 explanation: Option<String>,
158 deviation: bool,
160 not_required: bool,
162 live_tan: Option<(TaskReference, TanChallenge)>,
166}
167
168mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184enum Stage {
185 First,
187 Poll,
189 Execution,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
195pub(super) struct PaymentIds {
196 end_to_end_id: String,
197 message_id: String,
198}
199
200impl PaymentIds {
201 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 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
224enum Next {
226 Outcome(Outcome),
227 Execute(Box<PaymentJob>, Vec<Notice>),
229}
230
231impl PaymentJob {
232 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 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 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 pub(super) fn tan_extra_sent(&mut self) {
312 self.hkvpa_with_tan = false;
313 }
314
315 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 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 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 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 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 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
462fn 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
492pub(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
525fn 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
547pub 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 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 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 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 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 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 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 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 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 super::extend_notices(&mut notices, self.inner.take_notices());
741 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 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 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 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 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 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}