1use 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#[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 pub fn with_now(mut self, now: DateTime) -> Self {
101 self.now = Some(now);
102 self
103 }
104
105 pub fn now(&self) -> DateTime {
109 self.now
110 .unwrap_or_else(|| jiff::ZonedDateTime::now().datetime())
111 }
112
113 pub fn today(&self) -> Date {
115 self.now().date()
116 }
117
118 pub fn with_transport(mut self, transport: SharedTransport) -> Self {
120 self.transport = Some(transport);
121 self
122 }
123
124 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 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#[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#[must_use]
213#[derive(Debug)]
214pub enum Step<T> {
215 Done(Completed<T>),
216 NeedTan(TanChallenge, Resume<T>),
219 NeedVopConfirmation(VopConfirmation, Resume<T>),
223 VopPending(VopWait, Resume<T>),
226}
227
228#[derive(Debug, Clone)]
231pub struct Completed<T> {
232 pub value: T,
233 pub notices: Vec<Notice>,
234}
235
236#[derive(Debug)]
239pub struct Resume<T> {
240 ticket: Ticket,
241 _value: PhantomData<fn() -> T>,
242}
243
244#[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#[derive(Debug, Clone, Serialize, Deserialize)]
260enum Wait {
261 Tan(TanChallenge),
262 VopConfirmation(VopConfirmation),
263 VopPoll(VopWait),
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct TanChallenge {
269 pub challenge: ChallengeText,
271 pub challenge_markup: bool,
276 pub kind: TanKind,
277 pub valid_until: Option<DateTime>,
281 pub not_before: Option<Timestamp>,
288 pub payee_check: Option<VopResult>,
292 pub rejected: Option<Box<TanRejected>>,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300pub struct TanRejected {
301 pub code: ReturnCode,
303 pub attempts_left: Option<u32>,
306 pub count: u32,
308}
309
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312pub enum TanKind {
313 Typed { media: Option<TanMedia> },
316 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 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
370pub(crate) fn extend_notices(notices: &mut Vec<Notice>, new: Vec<Notice>) {
375 for notice in new {
376 if !notices.contains(¬ice) {
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#[derive(Debug, Clone)]
393pub struct Opened {
394 pub accounts: Vec<AccountInfo>,
396 pub tan_methods: Vec<TanMethod>,
398 pub allowed_security_functions: Vec<SecurityFunction>,
400 pub selected_tan_method: Option<TanMethod>,
405}
406
407pub 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 #[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 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
524pub enum Format {
525 #[default]
530 Auto,
531 Camt,
533 Mt940,
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
539pub enum StatementFormat {
540 Camt,
541 Mt940,
542}
543
544#[derive(Debug, Clone)]
549#[non_exhaustive]
550pub enum Pending {
551 Reported(Vec<Transaction>),
555 NotSent,
558 Unreadable { kind: Category, message: String },
565}
566
567impl Pending {
568 pub fn reported(&self) -> Option<&[Transaction]> {
570 match self {
571 Self::Reported(t) => Some(t),
572 _ => None,
573 }
574 }
575}
576
577#[derive(Debug, Clone)]
579pub struct Statement {
580 pub booked: Vec<Transaction>,
582 pub pending: Pending,
584 pub pending_created_at: Option<BankTime>,
591 pub format: StatementFormat,
593}
594
595#[derive(Debug, Clone, Serialize, Deserialize)]
599enum JobInput {
600 Open,
602 Balance { account: Account },
604 Transactions {
606 account: Account,
607 range: Range,
608 format: StatementFormat,
609 touchdown: Option<TouchdownPoint>,
610 booked: Vec<Vec<u8>>,
613 pending: Vec<Vec<u8>>,
614 pending_sent: bool,
616 find_payment: Option<String>,
620 },
621 Holdings {
623 account: Account,
624 currency: Option<Currency>,
625 touchdown: Option<TouchdownPoint>,
626 found: Vec<SecurityHolding>,
627 },
628 DepotTransactions {
630 account: Account,
631 range: Option<Range>,
632 touchdown: Option<TouchdownPoint>,
633 found: Vec<DepotTransaction>,
634 },
635 Transfer(Box<PaymentJob>),
637 InstantStatus {
639 account: Account,
640 descriptors: Vec<String>,
641 order_id: String,
642 min_wait: Option<u32>,
643 },
644}
645
646fn 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 fn payment_ids(&self) -> Option<PaymentIds> {
658 match self {
659 Self::Transfer(p) => Some(p.ids()),
660 _ => None,
661 }
662 }
663
664 fn in_flight(&self) -> InFlight {
666 match self.payment_ids() {
667 Some(ids) => InFlight::Payment(ids),
668 None => InFlight::Message,
669 }
670 }
671
672 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 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 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 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
900fn 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct PendingJob {
972 ticket: Ticket,
973 wait: Wait,
974 job: JobInput,
975 notices: Vec<Notice>,
977}
978
979impl PendingJob {
980 pub fn challenge(&self) -> Option<&TanChallenge> {
983 match &self.wait {
984 Wait::Tan(c) => Some(c),
985 _ => None,
986 }
987 }
988
989 pub fn vop(&self) -> Option<&VopConfirmation> {
991 match &self.wait {
992 Wait::VopConfirmation(c) => Some(c),
993 _ => None,
994 }
995 }
996
997 pub fn vop_wait(&self) -> Option<&VopWait> {
999 match &self.wait {
1000 Wait::VopPoll(w) => Some(w),
1001 _ => None,
1002 }
1003 }
1004
1005 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#[derive(Debug, Clone)]
1018pub enum Phase {
1019 Open,
1021 Paused(Box<PendingJob>),
1023 Ended,
1025}
1026
1027enum 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
1054pub struct Dialog {
1072 inner: protocol::Dialog<Open>,
1073 bic: Bic,
1075 booking_id: BookingIdSource,
1077 phase: Phase,
1078 last_message_at: Timestamp,
1080 in_flight: Option<InFlight>,
1084}
1085
1086#[derive(Debug, Clone)]
1088enum InFlight {
1089 Message,
1091 Payment(PaymentIds),
1094}
1095
1096#[must_use]
1098#[derive(Debug, Clone, PartialEq, Eq)]
1099pub enum Cancelled {
1100 NothingSent,
1105 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
1130pub 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 if let Some(s) = state {
1179 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(¶ms)
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
1215async 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
1249fn 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
1266pub 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 ¬ices {
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, ¶ms),
1322 notices,
1323 })
1324}
1325
1326async 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
1369pub 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
1383pub 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
1450fn 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
1463fn 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
1472fn 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
1497fn find_upd_account<'a>(params: &'a BankParams, account: &Account) -> Option<&'a UpdAccount> {
1500 params.upd()?.find(account)
1501}
1502
1503fn 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
1512pub 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
1530pub 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 pub fn phase(&self) -> &Phase {
1551 &self.phase
1552 }
1553
1554 pub fn pending(&self) -> Option<&PendingJob> {
1556 match &self.phase {
1557 Phase::Paused(p) => Some(p.as_ref()),
1558 _ => None,
1559 }
1560 }
1561
1562 pub fn last_message_at(&self) -> Timestamp {
1564 self.last_message_at
1565 }
1566
1567 pub fn capabilities(&self, accounts: &[Account]) -> Capabilities {
1571 Capabilities::build(self.bank_params(), self.inner.tan_overrides(), accounts)
1572 }
1573
1574 #[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 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 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 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 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 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 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 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 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 fn end_locally(&mut self) {
1844 self.phase = Phase::Ended;
1845 self.inner.forget_dialog();
1846 }
1847
1848 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 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 fn job_failed(&mut self, job: &JobInput) {
1880 if job.job() == Job::Open {
1881 self.phase = Phase::Ended;
1882 }
1883 }
1884
1885 fn settle(&mut self, job: &JobInput, sent: Result<Response>) -> Result<Response> {
1889 self.settle_message(job.job() == Job::Open, sent)
1890 }
1891
1892 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 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 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 async fn start(&mut self, job: JobInput) -> Result<Outcome> {
1958 self.start_with(job, Vec::new()).await
1959 }
1960
1961 async fn start_with(&mut self, job: JobInput, notices: Vec<Notice>) -> Result<Outcome> {
1964 self.ready()?;
1965 self.inner.take_notices();
1967 self.send_order(job, notices).await
1968 }
1969
1970 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 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 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 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 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 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 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 #[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), ¶ms, now);
2110 assert!(matches!(typed.kind, TanKind::Typed { .. }), "{typed:?}");
2111 let app = TanChallenge::from_bank(&bank(true), ¶ms, now);
2112 assert!(matches!(app.kind, TanKind::Decoupled { .. }), "{app:?}");
2113 }
2114
2115 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 #[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 #[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 #[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}