1use std::collections::BTreeMap;
20use std::fmt;
21
22use rust_decimal::Decimal;
23use serde::{Deserialize, Serialize, Serializer};
24use tracing::warn;
25
26use super::Account;
27use crate::codec::defs::{AccountLimit2, AllowedOrder2, HiBpa3, HiUpa4, PinTanParameters1};
28use crate::codec::{Code, CodecError, ErrorKind, Num, RawSegment, TypedSegment};
29use crate::segments::Order;
30use crate::segments::read::{self, ParamsHeader};
31use crate::types::{
32 AccountClass, AccountKey, Bic, Blz, Currency, Iban, SegmentType, SepaAccount, TanMethod,
33};
34
35pub(crate) fn is_bpd_segment(code: &str) -> bool {
41 matches!(code, "HIBPA" | "HIKOM" | "HISHV" | "HIKPV") || is_job_parameter_segment(code)
42}
43
44fn is_job_parameter_segment(code: &str) -> bool {
46 (code.starts_with("HI") || code.starts_with("DI")) && code.len() == 6 && code.ends_with('S')
47}
48
49fn order_code(parameter_code: &str) -> SegmentType {
52 let mut code = String::with_capacity(5);
53 code.push_str(¶meter_code[..1]);
54 code.push('K');
55 code.push_str(¶meter_code[2..5]);
56 SegmentType::new(code)
57}
58
59pub(crate) fn bpd_after(
67 current: &[RawSegment],
68 response: &[RawSegment],
69) -> Option<Vec<RawSegment>> {
70 let incoming: Vec<RawSegment> = response
71 .iter()
72 .filter(|s| is_bpd_segment(s.segment_type()))
73 .cloned()
74 .collect();
75 if response.iter().any(|s| s.segment_type() == "HIBPA") {
76 return Some(incoming);
77 }
78 if incoming.is_empty() {
79 return None;
80 }
81 let names: Vec<String> = incoming
82 .iter()
83 .map(|s| format!("{}:{}", s.segment_type(), s.segment_version()))
84 .collect();
85 warn!(
86 "[FinTS] parameter segments without HIBPA, merged into the BPD: {}",
87 names.join(", ")
88 );
89 let mut merged = current.to_vec();
90 for seg in incoming {
91 let same = |s: &&mut RawSegment| {
92 s.segment_type() == seg.segment_type() && s.segment_version() == seg.segment_version()
93 };
94 match merged.iter_mut().find(same) {
95 Some(slot) => *slot = seg,
96 None => merged.push(seg),
97 }
98 }
99 Some(merged)
100}
101
102pub(crate) fn upd_after(response: &[RawSegment]) -> Option<Vec<RawSegment>> {
107 response
108 .iter()
109 .any(|s| s.segment_type() == "HIUPA")
110 .then(|| {
111 response
112 .iter()
113 .filter(|s| matches!(s.segment_type(), "HIUPA" | "HIUPD"))
114 .cloned()
115 .collect()
116 })
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
124#[non_exhaustive]
125pub enum ParamsError {
126 #[error("no {0} segment")]
128 Missing(&'static str),
129 #[error("{0} not readable: {1}")]
132 Unreadable(&'static str, Box<CodecError>),
133}
134
135#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
137#[non_exhaustive]
138pub struct VersionMismatch {
139 pub code: SegmentType,
141 pub offered: Vec<u16>,
144 pub implemented: Vec<u16>,
146 pub formats: Option<Box<FormatLists>>,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
153#[non_exhaustive]
154pub struct FormatLists {
155 pub offered: Vec<String>,
157 pub implemented: Vec<String>,
159}
160
161impl fmt::Display for VersionMismatch {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 let list = |v: &[u16]| {
164 if v.is_empty() {
165 "none".to_string()
166 } else {
167 v.iter().map(u16::to_string).collect::<Vec<_>>().join(", ")
168 }
169 };
170 if let Some(formats) = &self.formats {
171 let offered = if formats.offered.is_empty() {
172 "none".to_string()
173 } else {
174 formats.offered.join(", ")
175 };
176 return write!(
177 f,
178 "{}: no common format (bank offers {offered}, client builds {})",
179 self.code,
180 formats.implemented.join(", ")
181 );
182 }
183 if self.offered.is_empty() {
184 return write!(
185 f,
186 "{}: bank does not offer this order (client implements {})",
187 self.code,
188 list(&self.implemented)
189 );
190 }
191 write!(
192 f,
193 "{}: no common version (bank offers {}, client implements {})",
194 self.code,
195 list(&self.offered),
196 list(&self.implemented)
197 )
198 }
199}
200
201impl std::error::Error for VersionMismatch {}
202
203#[derive(Debug, Clone, Serialize)]
205#[non_exhaustive]
206pub struct UnparsedParam {
207 pub segment: RawSegment,
208 #[serde(serialize_with = "display")]
209 pub error: CodecError,
210}
211
212fn display<T: fmt::Display, S: Serializer>(value: &T, s: S) -> Result<S::Ok, S::Error> {
213 s.collect_str(value)
214}
215
216#[derive(Debug, Clone, Serialize)]
220#[non_exhaustive]
221pub struct Bpd {
222 pub version: u16,
224 pub country: String,
226 pub bank_code: Option<Blz>,
228 pub bank_name: String,
229 pub max_order_kinds: u16,
231 pub languages: Vec<u16>,
233 pub hbci_versions: Vec<u16>,
235 pub max_message_size: Option<u32>,
237 pub min_timeout: Option<u32>,
238 pub max_timeout: Option<u32>,
239 pub pin_tan: Option<PinTanParams>,
242 pub tan: TanParams,
244 jobs: BTreeMap<SegmentType, JobParams>,
245 unparsed: Vec<UnparsedParam>,
246}
247
248#[derive(Debug, Clone, Serialize)]
250#[non_exhaustive]
251pub struct JobParams {
252 pub code: SegmentType,
254 pub versions: BTreeMap<u16, JobVersion>,
256}
257
258#[derive(Debug, Clone, Serialize)]
260#[non_exhaustive]
261pub struct JobVersion {
262 pub max_orders: u16,
264 pub min_signatures: u8,
266 pub security_class: Option<u8>,
270 pub detail: JobDetail,
271}
272
273#[derive(Debug, Clone, Serialize)]
275#[non_exhaustive]
276pub enum JobDetail {
277 None,
280 Sepa(SepaParams),
282 Statement(StatementParams),
284 Camt(CamtParams),
286 Balance(BalanceParams),
288 Holdings(HoldingsParams),
290 Instant(InstantParams),
292 InstantStatus(InstantStatusParams),
294 Vop(VopParams),
296 Raw(RawSegment),
299}
300
301#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
303#[non_exhaustive]
304pub struct SepaParams {
305 pub single_account_allowed: bool,
306 pub national_account_allowed: bool,
309 pub structured_purpose_allowed: bool,
310 pub max_entries_allowed: Option<bool>,
312 pub reserved_purpose_places: Option<u16>,
314 pub formats: Vec<String>,
316}
317
318#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
320#[non_exhaustive]
321pub struct StatementParams {
322 pub days_stored: u32,
324 pub max_entries_allowed: bool,
325 pub all_accounts_allowed: bool,
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
330#[non_exhaustive]
331pub struct CamtParams {
332 pub days_stored: u32,
333 pub max_entries_allowed: bool,
334 pub all_accounts_allowed: bool,
335 pub formats: Vec<String>,
337}
338
339#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
341#[non_exhaustive]
342pub struct BalanceParams {
343 pub max_entries_allowed: bool,
344}
345
346#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
348#[non_exhaustive]
349pub struct HoldingsParams {
350 pub max_entries_allowed: bool,
351 pub currency_selectable: bool,
352 pub quality_selectable: bool,
353}
354
355#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
357#[non_exhaustive]
358pub struct InstantParams {
359 pub conversion_allowed: bool,
363 pub purpose_codes: Vec<String>,
365 pub formats: Vec<String>,
368}
369
370#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
372#[non_exhaustive]
373pub struct InstantStatusParams {
374 pub min_wait: u32,
376 pub formats: Vec<String>,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
383#[non_exhaustive]
384pub enum VopDelivery {
385 Stepwise,
387 Complete,
389 Other(String),
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
397#[non_exhaustive]
398pub struct VopParams {
399 pub max_transactions: u32,
401 pub explanation_structured: bool,
403 pub delivery: VopDelivery,
404 pub bulk_with_one_order_allowed: bool,
405 pub max_entries_input_allowed: bool,
406 pub report_formats: Vec<String>,
409 pub required_for: Vec<SegmentType>,
412}
413
414impl VopParams {
415 pub fn requires(&self, order: &str) -> bool {
418 self.required_for.iter().any(|c| c.as_str() == order)
419 }
420}
421
422#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
425#[non_exhaustive]
426pub struct InstantSupport {
427 pub versions: Vec<u16>,
429 pub payment: InstantParams,
431 pub status: Option<InstantStatusParams>,
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
437#[non_exhaustive]
438pub struct PinTanParams {
439 pub min_pin_length: Option<u8>,
440 pub max_pin_length: Option<u8>,
441 pub max_tan_length: Option<u8>,
442 pub user_id_text: Option<String>,
443 pub customer_id_text: Option<String>,
444 pub tan_required: BTreeMap<SegmentType, bool>,
447}
448
449#[derive(Debug, Clone, Default, Serialize)]
451#[non_exhaustive]
452pub struct TanParams {
453 pub versions: BTreeMap<u16, TanVersion>,
454}
455
456#[derive(Debug, Clone, Serialize)]
458#[non_exhaustive]
459pub struct TanVersion {
460 pub one_step_allowed: Option<bool>,
463 pub methods: Vec<TanMethod>,
464}
465
466impl TanParams {
467 pub fn hktan_versions(&self) -> impl Iterator<Item = u16> + '_ {
469 self.versions.keys().copied()
470 }
471
472 pub fn methods(&self) -> impl Iterator<Item = &TanMethod> {
474 self.versions.values().flat_map(|v| &v.methods)
475 }
476}
477
478impl JobParams {
479 pub fn offered(&self) -> impl Iterator<Item = u16> + '_ {
481 self.versions.keys().copied()
482 }
483
484 pub fn highest(&self) -> Option<(u16, &JobVersion)> {
486 self.versions.iter().next_back().map(|(v, j)| (*v, j))
487 }
488}
489
490impl Bpd {
491 pub fn from_segments(segments: &[RawSegment]) -> Result<Bpd, ParamsError> {
494 let hibpa = segments
495 .iter()
496 .find(|s| s.segment_type() == "HIBPA")
497 .ok_or(ParamsError::Missing("HIBPA"))?;
498 let header: HiBpa3 = match read::typed(hibpa) {
499 Ok((_, TypedSegment::HiBpa3(h))) => h,
500 Ok(_) => unreachable!("HIBPA reads as HIBPA"),
501 Err(e) => return Err(ParamsError::Unreadable("HIBPA", Box::new(e))),
502 };
503 let num32 = |n: Option<Num>| n.and_then(|n| u32::try_from(n.value()).ok());
504 let mut bpd = Bpd {
505 version: u16_of(header.bpd_version),
506 country: header.bank.country.as_str().to_string(),
507 bank_code: header.bank.bank_code.as_ref().map(|c| Blz::new(c.as_str())),
508 bank_name: header.bank_name.as_str().to_string(),
509 max_order_kinds: u16_of(header.max_order_kinds),
510 languages: header
511 .languages
512 .languages
513 .iter()
514 .filter_map(|c| c.as_str().parse().ok())
515 .collect(),
516 hbci_versions: header
517 .hbci_versions
518 .versions
519 .iter()
520 .map(|n| u16_of(*n))
521 .collect(),
522 max_message_size: num32(header.max_message_size),
523 min_timeout: num32(header.min_timeout),
524 max_timeout: num32(header.max_timeout),
525 pin_tan: None,
526 tan: TanParams::default(),
527 jobs: BTreeMap::new(),
528 unparsed: Vec::new(),
529 };
530 for seg in segments
531 .iter()
532 .filter(|s| is_job_parameter_segment(s.segment_type()))
533 {
534 bpd.add_job_segment(seg);
535 }
536 Ok(bpd)
537 }
538
539 fn add_job_segment(&mut self, seg: &RawSegment) {
540 let version = seg.segment_version();
541 let job = match read::typed(seg) {
542 Ok((_, typed)) => match self.typed_job(seg, typed) {
543 Some(job) => job,
544 None => header_only(seg),
545 },
546 Err(error) => {
547 let undefined = error.kind == ErrorKind::UnknownSegment;
548 if undefined && seg.segment_type() == "HITANS" {
549 self.tan.versions.insert(
551 version,
552 TanVersion {
553 one_step_allowed: None,
554 methods: read::tan_methods(seg),
555 },
556 );
557 }
558 if !undefined {
559 read::report(&error);
560 }
561 let job =
562 read::params_header(seg).map(|h| job_version(h, JobDetail::Raw(seg.clone())));
563 if !undefined || job.is_none() {
564 self.unparsed.push(UnparsedParam {
565 segment: seg.clone(),
566 error,
567 });
568 }
569 match job {
570 Some(job) => job,
571 None => return,
572 }
573 }
574 };
575 let code = order_code(seg.segment_type());
576 self.jobs
577 .entry(code.clone())
578 .or_insert_with(|| JobParams {
579 code,
580 versions: BTreeMap::new(),
581 })
582 .versions
583 .insert(version, job);
584 }
585
586 fn typed_job(&mut self, seg: &RawSegment, typed: TypedSegment) -> Option<JobVersion> {
589 use JobDetail as D;
590 use TypedSegment as T;
591 macro_rules! head {
592 ($s:expr) => {
593 ParamsHeader {
594 max_orders: u16_of($s.max_orders),
595 min_signatures: u8_of($s.min_signatures),
596 security_class: class(&$s.security_class),
597 }
598 };
599 }
600 macro_rules! head_pre_fints {
601 ($s:expr) => {
602 ParamsHeader {
603 max_orders: u16_of($s.max_orders),
604 min_signatures: u8_of($s.min_signatures),
605 security_class: None,
606 }
607 };
608 }
609 macro_rules! tans {
610 ($s:expr) => {{
611 self.tan.versions.insert(
612 seg.segment_version(),
613 TanVersion {
614 one_step_allowed: Some($s.parameters.one_step_allowed.value()),
615 methods: read::tan_methods(seg),
616 },
617 );
618 job_version(head!($s), D::None)
619 }};
620 }
621 let statement = |p: &crate::codec::defs::TurnoverParameters2| {
622 D::Statement(StatementParams {
623 days_stored: u32_of(p.storage_period),
624 max_entries_allowed: p.max_entries_allowed.value(),
625 all_accounts_allowed: p.all_accounts_allowed.value(),
626 })
627 };
628 let holdings = |p: &crate::codec::defs::DepotListParameters2| {
629 D::Holdings(HoldingsParams {
630 max_entries_allowed: p.max_entries_allowed.value(),
631 currency_selectable: p.currency_selectable.value(),
632 quality_selectable: p.quality_selectable.value(),
633 })
634 };
635 let texts = |v: &[crate::codec::An]| v.iter().map(|f| f.as_str().to_string()).collect();
636 let list = |a: Option<&crate::codec::An>, sep: char| -> Vec<String> {
638 a.map(|a| {
639 a.as_str()
640 .split(sep)
641 .map(str::trim)
642 .filter(|p| !p.is_empty())
643 .map(str::to_string)
644 .collect()
645 })
646 .unwrap_or_default()
647 };
648 Some(match typed {
649 T::HiPins1(s) => {
650 self.pin_tan = Some(pin_tan(&s.parameters));
651 job_version(head!(s), D::None)
652 }
653 T::HiTans1(s) => tans!(s),
654 T::HiTans2(s) => tans!(s),
655 T::HiTans3(s) => tans!(s),
656 T::HiTans4(s) => tans!(s),
657 T::HiTans5(s) => tans!(s),
658 T::HiTans6(s) => tans!(s),
659 T::HiTans7(s) => tans!(s),
660 T::HiSpas1(s) => {
661 let p = &s.parameters;
662 let detail = D::Sepa(SepaParams {
663 single_account_allowed: p.single_account_allowed.value(),
664 national_account_allowed: p.national_account_allowed.value(),
665 structured_purpose_allowed: p.structured_purpose_allowed.value(),
666 max_entries_allowed: None,
667 reserved_purpose_places: None,
668 formats: texts(&p.formats),
669 });
670 job_version(head!(s), detail)
671 }
672 T::HiSpas2(s) => {
673 let p = &s.parameters;
674 let detail = D::Sepa(SepaParams {
675 single_account_allowed: p.single_account_allowed.value(),
676 national_account_allowed: p.national_account_allowed.value(),
677 structured_purpose_allowed: p.structured_purpose_allowed.value(),
678 max_entries_allowed: Some(p.max_entries_allowed.value()),
679 reserved_purpose_places: None,
680 formats: texts(&p.formats),
681 });
682 job_version(head!(s), detail)
683 }
684 T::HiSpas3(s) => {
685 let p = &s.parameters;
686 let detail = D::Sepa(SepaParams {
687 single_account_allowed: p.single_account_allowed.value(),
688 national_account_allowed: p.national_account_allowed.value(),
689 structured_purpose_allowed: p.structured_purpose_allowed.value(),
690 max_entries_allowed: Some(p.max_entries_allowed.value()),
691 reserved_purpose_places: Some(u16_of(p.reserved_purpose_places)),
692 formats: texts(&p.formats),
693 });
694 job_version(head!(s), detail)
695 }
696 T::HiSals5(s) => job_version(head_pre_fints!(s), D::None),
697 T::HiSals6(s) => job_version(head!(s), D::None),
698 T::HiSals7(s) => job_version(head!(s), D::None),
699 T::HiSals8(s) => {
700 let detail = D::Balance(BalanceParams {
701 max_entries_allowed: s.parameters.max_entries_allowed.value(),
702 });
703 job_version(head!(s), detail)
704 }
705 T::HiKazs5(s) => job_version(head_pre_fints!(s), statement(&s.parameters)),
706 T::HiKazs6(s) => job_version(head!(s), statement(&s.parameters)),
707 T::HiKazs7(s) => job_version(head!(s), statement(&s.parameters)),
708 T::HiCazs1(s) => {
709 let p = &s.parameters;
710 let detail = D::Camt(CamtParams {
711 days_stored: u32_of(p.storage_period),
712 max_entries_allowed: p.entry_count_allowed.value(),
713 all_accounts_allowed: p.all_accounts_allowed.value(),
714 formats: texts(&p.formats),
715 });
716 job_version(head!(s), detail)
717 }
718 T::HiCcss1(s) => job_version(head!(s), D::None),
719 T::HiVpas1(s) => job_version(head!(s), D::None),
720 T::HiIpzs1(s) => {
721 let p = &s.parameters;
722 let detail = D::Instant(InstantParams {
723 conversion_allowed: false,
724 purpose_codes: list(p.purpose_codes.as_ref(), ','),
725 formats: texts(&p.formats),
726 });
727 job_version(head!(s), detail)
728 }
729 T::HiIpzs2(s) => {
730 let p = &s.parameters;
731 let detail = D::Instant(InstantParams {
732 conversion_allowed: p.conversion_allowed.value(),
733 purpose_codes: list(p.purpose_codes.as_ref(), ','),
734 formats: texts(&p.formats),
735 });
736 job_version(head!(s), detail)
737 }
738 T::HiIpss1(s) => {
739 let p = &s.parameters;
740 let detail = D::InstantStatus(InstantStatusParams {
741 min_wait: u32_of(p.min_wait),
742 formats: texts(&p.formats),
743 });
744 job_version(head!(s), detail)
745 }
746 T::HiVpps1(s) => {
747 let p = &s.parameters;
748 let delivery = match p.delivery.as_str() {
749 "S" => VopDelivery::Stepwise,
750 "V" => VopDelivery::Complete,
751 other => {
752 warn!("[FinTS] HIVPPS: unknown delivery {other:?}, read as complete");
753 VopDelivery::Other(other.to_string())
754 }
755 };
756 let detail = D::Vop(VopParams {
757 max_transactions: u32_of(p.max_transactions),
758 explanation_structured: p.explanation_structured.value(),
759 delivery,
760 bulk_with_one_order_allowed: p.bulk_with_one_order_allowed.value(),
761 max_entries_input_allowed: p.max_entries_input_allowed.value(),
762 report_formats: list(Some(&p.report_formats), ';'),
763 required_for: p
764 .required_for
765 .iter()
766 .map(|c| SegmentType::new(c.as_str()))
767 .collect(),
768 });
769 job_version(head!(s), detail)
770 }
771 T::HiWpds5(s) => job_version(head_pre_fints!(s), holdings(&s.parameters)),
772 T::HiWpds6(s) => job_version(head!(s), holdings(&s.parameters)),
773 _ => return None,
774 })
775 }
776
777 pub fn job(&self, code: &str) -> Option<&JobParams> {
779 self.jobs.get(&SegmentType::new(code))
780 }
781
782 pub fn jobs(&self) -> impl Iterator<Item = &JobParams> {
784 self.jobs.values()
785 }
786
787 pub fn unparsed(&self) -> &[UnparsedParam] {
789 &self.unparsed
790 }
791
792 pub fn highest_common(&self, code: &str, implemented: &[u16]) -> Result<u16, VersionMismatch> {
795 let offered: Vec<u16> = self
796 .job(code)
797 .map(|j| j.offered().collect())
798 .unwrap_or_default();
799 offered
800 .iter()
801 .rev()
802 .copied()
803 .find(|v| implemented.contains(v))
804 .ok_or_else(|| VersionMismatch {
805 code: SegmentType::new(code),
806 offered,
807 implemented: implemented.to_vec(),
808 formats: None,
809 })
810 }
811
812 pub fn tan_required(&self, code: &str) -> Option<bool> {
815 self.pin_tan
816 .as_ref()?
817 .tan_required
818 .get(&SegmentType::new(code))
819 .copied()
820 }
821
822 pub fn tan_methods(&self) -> impl Iterator<Item = &TanMethod> {
824 self.tan.methods()
825 }
826
827 pub fn sepa(&self) -> Option<&SepaParams> {
829 self.job("HKSPA")?
830 .versions
831 .values()
832 .rev()
833 .find_map(|j| match &j.detail {
834 JobDetail::Sepa(s) => Some(s),
835 _ => None,
836 })
837 }
838
839 pub fn vop(&self) -> Option<&VopParams> {
843 self.job("HKVPP")?
844 .versions
845 .values()
846 .rev()
847 .find_map(|j| match &j.detail {
848 JobDetail::Vop(p) => Some(p),
849 _ => None,
850 })
851 }
852
853 pub fn sepa_formats(&self, order: Order) -> &[String] {
860 let own: &[String] = match order {
861 Order::InstantTransfer => self.instant_params().map_or(&[], |p| &p.formats),
862 Order::InstantStatus => self
863 .instant_status_params()
864 .map_or(&[], |p| p.formats.as_slice()),
865 Order::Transfer => &[],
866 _ => return &[],
867 };
868 if own.is_empty() {
869 self.sepa().map_or(&[], |s| s.formats.as_slice())
870 } else {
871 own
872 }
873 }
874
875 pub fn instant(&self) -> Option<InstantSupport> {
878 let job = self.job("HKIPZ")?;
879 let payment = self.instant_params()?.clone();
880 Some(InstantSupport {
881 versions: job.offered().collect(),
882 payment,
883 status: self.instant_status_params().cloned(),
884 })
885 }
886
887 fn instant_params(&self) -> Option<&InstantParams> {
888 self.job("HKIPZ")?
889 .versions
890 .values()
891 .rev()
892 .find_map(|j| match &j.detail {
893 JobDetail::Instant(p) => Some(p),
894 _ => None,
895 })
896 }
897
898 fn instant_status_params(&self) -> Option<&InstantStatusParams> {
899 self.job("HKIPS")?
900 .versions
901 .values()
902 .rev()
903 .find_map(|j| match &j.detail {
904 JobDetail::InstantStatus(p) => Some(p),
905 _ => None,
906 })
907 }
908
909 pub fn camt_formats(&self) -> &[String] {
911 self.job("HKCAZ")
912 .and_then(|j| {
913 j.versions.values().rev().find_map(|j| match &j.detail {
914 JobDetail::Camt(c) => Some(c.formats.as_slice()),
915 _ => None,
916 })
917 })
918 .unwrap_or_default()
919 }
920}
921
922fn job_version(h: ParamsHeader, detail: JobDetail) -> JobVersion {
923 JobVersion {
924 max_orders: h.max_orders,
925 min_signatures: h.min_signatures,
926 security_class: h.security_class,
927 detail,
928 }
929}
930
931fn header_only(seg: &RawSegment) -> JobVersion {
933 match read::params_header(seg) {
934 Some(h) => job_version(h, JobDetail::Raw(seg.clone())),
935 None => JobVersion {
936 max_orders: 0,
937 min_signatures: 0,
938 security_class: None,
939 detail: JobDetail::Raw(seg.clone()),
940 },
941 }
942}
943
944fn pin_tan(p: &PinTanParameters1) -> PinTanParams {
945 let len = |n: Option<Num>| n.map(u8_of);
946 let text =
947 |a: Option<&crate::codec::An>| a.map(|a| a.as_str().to_string()).filter(|s| !s.is_empty());
948 PinTanParams {
949 min_pin_length: len(p.min_pin_length),
950 max_pin_length: len(p.max_pin_length),
951 max_tan_length: len(p.max_tan_length),
952 user_id_text: text(p.user_id_text.as_ref()),
953 customer_id_text: text(p.customer_id_text.as_ref()),
954 tan_required: p
955 .orders
956 .iter()
957 .map(|o| {
958 (
959 SegmentType::new(o.segment_code.as_str()),
960 o.tan_required.value(),
961 )
962 })
963 .collect(),
964 }
965}
966
967fn u8_of(n: Num) -> u8 {
968 u8::try_from(n.value()).unwrap_or(u8::MAX)
969}
970
971fn u16_of(n: Num) -> u16 {
972 u16::try_from(n.value()).unwrap_or(u16::MAX)
973}
974
975fn u32_of(n: Num) -> u32 {
976 u32::try_from(n.value()).unwrap_or(u32::MAX)
977}
978
979fn class(c: &Code) -> Option<u8> {
980 c.as_str().parse().ok()
981}
982
983#[derive(Debug, Clone, Serialize)]
987#[non_exhaustive]
988pub struct Upd {
989 pub version: u16,
993 pub usage: UpdUsage,
995 pub accounts: Vec<UpdAccount>,
996 unparsed: Vec<UnparsedParam>,
997}
998
999#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1001#[non_exhaustive]
1002pub enum UpdUsage {
1003 Closed,
1005 Open,
1008}
1009
1010#[derive(Debug, Clone, Serialize)]
1013#[non_exhaustive]
1014pub struct UpdAccount {
1015 pub account_number: Option<String>,
1016 pub sub_account: Option<String>,
1017 pub blz: Option<Blz>,
1018 pub iban: Option<Iban>,
1019 pub customer_id: String,
1021 pub account_type: Option<u8>,
1023 pub currency: Option<Currency>,
1024 pub owner: Vec<String>,
1026 pub product_name: Option<String>,
1027 pub limit: Option<AccountLimit>,
1028 pub allowed: BTreeMap<SegmentType, AllowedJob>,
1030 pub bic: Option<Bic>,
1033}
1034
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1037#[non_exhaustive]
1038pub struct AllowedJob {
1039 pub min_signatures: u8,
1041 pub limit: Option<AccountLimit>,
1042}
1043
1044#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1046#[non_exhaustive]
1047pub struct AccountLimit {
1048 pub kind: LimitKind,
1049 pub amount: Option<Decimal>,
1050 pub currency: Option<Currency>,
1051 pub days: Option<u16>,
1053}
1054
1055#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1057#[non_exhaustive]
1058pub enum LimitKind {
1059 SingleOrder,
1061 Day,
1063 Week,
1065 Month,
1067 Period,
1069 Other(String),
1071}
1072
1073#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1075#[non_exhaustive]
1076pub enum Allowance {
1077 Yes,
1079 No,
1081 Unknown,
1083}
1084
1085impl Upd {
1086 pub fn from_segments(segments: &[RawSegment]) -> Result<Upd, ParamsError> {
1089 let hiupa = segments
1090 .iter()
1091 .find(|s| s.segment_type() == "HIUPA")
1092 .ok_or(ParamsError::Missing("HIUPA"))?;
1093 let header: HiUpa4 = match read::typed(hiupa) {
1094 Ok((_, TypedSegment::HiUpa4(h))) => h,
1095 Ok(_) => unreachable!("HIUPA reads as HIUPA"),
1096 Err(e) => return Err(ParamsError::Unreadable("HIUPA", Box::new(e))),
1097 };
1098 let usage = match header.upd_usage.as_str() {
1099 "0" => UpdUsage::Closed,
1100 "1" => UpdUsage::Open,
1101 other => {
1102 warn!("[FinTS] unknown UPD usage {other:?}, taken as open");
1103 UpdUsage::Open
1104 }
1105 };
1106 let mut upd = Upd {
1107 version: u16_of(header.upd_version),
1108 usage,
1109 accounts: Vec::new(),
1110 unparsed: Vec::new(),
1111 };
1112 for seg in segments.iter().filter(|s| s.segment_type() == "HIUPD") {
1113 match read::typed(seg) {
1114 Ok((_, TypedSegment::HiUpd4(s))) => upd.accounts.push(UpdAccount {
1115 account_number: some(s.account.account_number.as_str()),
1116 sub_account: s.account.subaccount.as_ref().and_then(|a| some(a.as_str())),
1117 blz: s
1118 .account
1119 .bank
1120 .bank_code
1121 .as_ref()
1122 .and_then(|b| some(b.as_str()))
1123 .map(Blz::new),
1124 iban: None,
1125 customer_id: s.customer_id.as_str().to_string(),
1126 account_type: None,
1127 currency: s.currency.as_ref().map(|c| Currency::new(c.as_str())),
1128 owner: owners(&s.holder_name_1, s.holder_name_2.as_ref()),
1129 product_name: s.product_name.as_ref().and_then(|p| some(p.as_str())),
1130 limit: s.limit.as_ref().map(account_limit),
1131 allowed: allowed(&s.allowed_orders),
1132 bic: None,
1133 }),
1134 Ok((_, TypedSegment::HiUpd6(s))) => {
1135 let k = s.account.as_ref();
1136 upd.accounts.push(UpdAccount {
1137 account_number: k.and_then(|k| some(k.account_number.as_str())),
1138 sub_account: k
1139 .and_then(|k| k.subaccount.as_ref())
1140 .and_then(|a| some(a.as_str())),
1141 blz: k
1142 .and_then(|k| k.bank.bank_code.as_ref())
1143 .and_then(|b| some(b.as_str()))
1144 .map(Blz::new),
1145 iban: s
1146 .iban
1147 .as_ref()
1148 .and_then(|i| some(i.as_str()))
1149 .map(Iban::new),
1150 customer_id: s.customer_id.as_str().to_string(),
1151 account_type: s.account_type.and_then(|t| u8::try_from(t.value()).ok()),
1152 currency: s.currency.as_ref().map(|c| Currency::new(c.as_str())),
1153 owner: owners(&s.holder_name_1, s.holder_name_2.as_ref()),
1154 product_name: s.product_name.as_ref().and_then(|p| some(p.as_str())),
1155 limit: s.limit.as_ref().map(account_limit),
1156 allowed: allowed(&s.allowed_orders),
1157 bic: None,
1158 });
1159 }
1160 Ok(_) => {}
1161 Err(e) if e.kind == ErrorKind::UnknownSegment => {
1162 match crate::segments::response::parse_hiupd(seg) {
1164 Some(sepa) => upd.accounts.push(UpdAccount::from_remainder(sepa)),
1165 None => upd.unparsed.push(UnparsedParam {
1166 segment: seg.clone(),
1167 error: e,
1168 }),
1169 }
1170 }
1171 Err(e) => {
1172 read::report(&e);
1173 upd.unparsed.push(UnparsedParam {
1174 segment: seg.clone(),
1175 error: e,
1176 });
1177 }
1178 }
1179 }
1180 Ok(upd)
1181 }
1182
1183 pub fn is_dialog_only(&self) -> bool {
1186 self.version == 0
1187 }
1188
1189 pub fn accounts(&self) -> &[UpdAccount] {
1191 &self.accounts
1192 }
1193
1194 pub fn unparsed(&self) -> &[UnparsedParam] {
1196 &self.unparsed
1197 }
1198
1199 pub fn allows(&self, account: &UpdAccount, code: &str) -> Allowance {
1202 if account.allowed.contains_key(&SegmentType::new(code)) {
1203 Allowance::Yes
1204 } else if self.usage == UpdUsage::Closed {
1205 Allowance::No
1206 } else {
1207 Allowance::Unknown
1208 }
1209 }
1210}
1211
1212impl UpdAccount {
1213 fn from_remainder(sepa: SepaAccount) -> UpdAccount {
1214 UpdAccount {
1215 account_number: some(&sepa.account_number),
1216 sub_account: some(&sepa.sub_account),
1217 blz: some(sepa.blz.as_str()).map(Blz::new),
1218 iban: some(sepa.iban.as_str()).map(Iban::new),
1219 customer_id: String::new(),
1220 account_type: sepa.account_type,
1221 currency: sepa.currency,
1222 owner: sepa.owner.into_iter().collect(),
1223 product_name: sepa.product_name,
1224 limit: None,
1225 allowed: BTreeMap::new(),
1226 bic: some(sepa.bic.as_str()).map(Bic::new),
1227 }
1228 }
1229
1230 pub fn class(&self) -> Option<AccountClass> {
1232 AccountClass::from_account_type(self.account_type?)
1233 }
1234
1235 pub fn key(&self) -> Option<AccountKey> {
1239 let sub = self.sub_account.as_deref();
1240 match (&self.blz, &self.account_number) {
1241 (Some(blz), Some(number)) => AccountKey::national(blz.as_str(), number, sub),
1242 _ => None,
1243 }
1244 .or_else(|| AccountKey::iban(self.iban.as_ref()?.as_str(), sub))
1245 }
1246
1247 fn is(&self, account: &Account) -> bool {
1251 match self.key() {
1252 Some(AccountKey::National {
1253 blz,
1254 number,
1255 subaccount,
1256 }) => {
1257 let same_blz = account.blz().is_none_or(|b| b == blz.as_str());
1258 let mine = account
1259 .account_number()
1260 .and_then(|n| AccountKey::national(blz.as_str(), n, account.subaccount()));
1261 same_blz
1262 && mine
1263 == Some(AccountKey::National {
1264 blz,
1265 number,
1266 subaccount,
1267 })
1268 }
1269 Some(key @ AccountKey::Iban { .. }) => {
1270 AccountKey::iban(account.iban(), account.subaccount()) == Some(key)
1271 }
1272 None => false,
1273 }
1274 }
1275
1276 fn resembles(&self, account: &Account) -> bool {
1279 let number = |n: &str| n.trim_start_matches('0').to_string();
1280 let by_iban = !account.iban().is_empty()
1281 && self
1282 .iban
1283 .as_ref()
1284 .is_some_and(|i| i.as_str() == account.iban());
1285 let by_number = account.account_number().is_some_and(|n| {
1286 self.account_number
1287 .as_deref()
1288 .is_some_and(|m| number(m) == number(n))
1289 });
1290 by_iban || by_number
1291 }
1292}
1293
1294impl Upd {
1295 pub fn find(&self, account: &Account) -> Option<&UpdAccount> {
1301 if let Some(exact) = self.accounts.iter().find(|a| a.is(account)) {
1302 return Some(exact);
1303 }
1304 let mut alike = self.accounts.iter().filter(|a| a.resembles(account));
1305 match (alike.next(), alike.next()) {
1306 (Some(only), None) => Some(only),
1307 _ => None,
1308 }
1309 }
1310}
1311
1312fn some(s: &str) -> Option<String> {
1313 (!s.is_empty()).then(|| s.to_string())
1314}
1315
1316fn owners(first: &crate::codec::An, second: Option<&crate::codec::An>) -> Vec<String> {
1317 std::iter::once(first)
1318 .chain(second)
1319 .filter_map(|n| some(n.as_str()))
1320 .collect()
1321}
1322
1323fn limit_kind(code: &str) -> LimitKind {
1324 match code {
1325 "E" => LimitKind::SingleOrder,
1326 "T" => LimitKind::Day,
1327 "W" => LimitKind::Week,
1328 "M" => LimitKind::Month,
1329 "Z" => LimitKind::Period,
1330 other => LimitKind::Other(other.to_string()),
1331 }
1332}
1333
1334fn account_limit(l: &AccountLimit2) -> AccountLimit {
1335 AccountLimit {
1336 kind: limit_kind(l.kind.as_str()),
1337 amount: l.amount.as_ref().map(|b| b.value.value()),
1338 currency: l
1339 .amount
1340 .as_ref()
1341 .map(|b| Currency::new(b.currency.as_str())),
1342 days: l.days.map(u16_of),
1343 }
1344}
1345
1346fn allowed(orders: &[AllowedOrder2]) -> BTreeMap<SegmentType, AllowedJob> {
1347 orders
1348 .iter()
1349 .map(|o| {
1350 let limit = o.limit_kind.as_ref().map(|k| AccountLimit {
1351 kind: limit_kind(k.as_str()),
1352 amount: o.limit_amount.as_ref().map(|b| b.value.value()),
1353 currency: o
1354 .limit_amount
1355 .as_ref()
1356 .map(|b| Currency::new(b.currency.as_str())),
1357 days: o.limit_days.map(u16_of),
1358 });
1359 (
1360 SegmentType::new(o.segment_code.as_str()),
1361 AllowedJob {
1362 min_signatures: u8_of(o.signatures_required),
1363 limit,
1364 },
1365 )
1366 })
1367 .collect()
1368}
1369
1370#[cfg(test)]
1371mod tests {
1372 use super::*;
1373
1374 fn segs(wire: &[&str]) -> Vec<RawSegment> {
1375 wire.iter()
1376 .map(|s| {
1377 crate::codec::wire::tokenize(s.as_bytes())
1378 .unwrap()
1379 .remove(0)
1380 })
1381 .collect()
1382 }
1383
1384 const HIBPA: &str = "HIBPA:5:3:4+12+280:12345678+Testbank+3+1:2+300+100+10+120'";
1385
1386 fn bpd(rest: &[&str]) -> Bpd {
1387 let mut all = vec![HIBPA];
1388 all.extend_from_slice(rest);
1389 Bpd::from_segments(&segs(&all)).unwrap()
1390 }
1391
1392 #[test]
1393 fn hibpa_fields() {
1394 let b = bpd(&[]);
1395 assert_eq!(b.version, 12);
1396 assert_eq!(b.country, "280");
1397 assert_eq!(b.bank_code, Some(Blz::new("12345678")));
1398 assert_eq!(b.bank_name, "Testbank");
1399 assert_eq!(b.max_order_kinds, 3);
1400 assert_eq!(b.languages, [1, 2]);
1401 assert_eq!(b.hbci_versions, [300]);
1402 assert_eq!(
1403 (b.max_message_size, b.min_timeout, b.max_timeout),
1404 (Some(100), Some(10), Some(120))
1405 );
1406 assert!(b.pin_tan.is_none() && b.jobs().next().is_none());
1407 }
1408
1409 #[test]
1410 fn missing_or_unreadable_header_is_an_error() {
1411 assert_eq!(
1412 Bpd::from_segments(&segs(&["HISALS:6:6:4+1+1+0'"])).unwrap_err(),
1413 ParamsError::Missing("HIBPA")
1414 );
1415 assert!(matches!(
1416 Bpd::from_segments(&segs(&["HIBPA:5:3:4+x+280:1+T+3+1+300'"])).unwrap_err(),
1417 ParamsError::Unreadable("HIBPA", _)
1418 ));
1419 assert_eq!(
1420 Upd::from_segments(&segs(&[])).unwrap_err(),
1421 ParamsError::Missing("HIUPA")
1422 );
1423 assert!(matches!(
1424 Upd::from_segments(&segs(&["HIUPA:5:4:4+USER+7+0x'"])).unwrap_err(),
1425 ParamsError::Unreadable("HIUPA", _)
1426 ));
1427 }
1428
1429 #[test]
1430 fn several_versions_of_one_job() {
1431 let b = bpd(&[
1432 "HISALS:6:5:4+1+1'",
1433 "HISALS:7:6:4+1+2+3'",
1434 "HISALS:8:8:4+5+1+1+J'",
1435 ]);
1436 let sal = b.job("HKSAL").unwrap();
1437 assert_eq!(sal.offered().collect::<Vec<_>>(), [5, 6, 8]);
1438 let v5 = &sal.versions[&5];
1439 assert_eq!(
1440 (v5.max_orders, v5.min_signatures, v5.security_class),
1441 (1, 1, None)
1442 );
1443 assert!(matches!(v5.detail, JobDetail::None));
1444 let v6 = &sal.versions[&6];
1445 assert_eq!((v6.min_signatures, v6.security_class), (2, Some(3)));
1446 let (v, v8) = sal.highest().unwrap();
1447 assert_eq!((v, v8.max_orders), (8, 5));
1448 assert!(matches!(
1449 v8.detail,
1450 JobDetail::Balance(BalanceParams {
1451 max_entries_allowed: true
1452 })
1453 ));
1454 assert!(b.unparsed().is_empty());
1455 }
1456
1457 #[test]
1458 fn typed_details() {
1459 let b = bpd(&[
1460 "HIKAZS:6:6:4+1+1+0+90:J:N'",
1461 "HIKAZS:7:5:4+1+1+60:N:J'",
1462 "HICAZS:8:1:4+1+1+0+450:N:N:urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.02'",
1463 "HIWPDS:9:6:4+1+1+0+J:N:J'",
1464 ]);
1465 let kaz = b.job("HKKAZ").unwrap();
1466 let JobDetail::Statement(s) = &kaz.versions[&6].detail else {
1467 panic!()
1468 };
1469 assert_eq!(
1470 (s.days_stored, s.max_entries_allowed, s.all_accounts_allowed),
1471 (90, true, false)
1472 );
1473 assert_eq!(kaz.versions[&5].security_class, None);
1474 let JobDetail::Statement(s) = &kaz.versions[&5].detail else {
1475 panic!()
1476 };
1477 assert_eq!((s.days_stored, s.all_accounts_allowed), (60, true));
1478 assert_eq!(
1479 b.camt_formats(),
1480 ["urn:iso:std:iso:20022:tech:xsd:camt.052.001.02"]
1481 );
1482 let JobDetail::Holdings(h) = &b.job("HKWPD").unwrap().versions[&6].detail else {
1483 panic!()
1484 };
1485 assert_eq!(
1486 (
1487 h.max_entries_allowed,
1488 h.currency_selectable,
1489 h.quality_selectable
1490 ),
1491 (true, false, true)
1492 );
1493 }
1494
1495 #[test]
1496 fn job_without_definition_is_header_only() {
1497 let b = bpd(&["HICCMS:6:1:4+1+1+0+J:N'", "HIPROS:7:3:4+999+2'"]);
1498 let ccs = &b.job("HKCCM").unwrap().versions[&1];
1499 assert_eq!(
1500 (ccs.max_orders, ccs.min_signatures, ccs.security_class),
1501 (1, 1, Some(0))
1502 );
1503 assert!(matches!(&ccs.detail, JobDetail::Raw(s) if s.segment_type() == "HICCMS"));
1504 let pro = &b.job("HKPRO").unwrap().versions[&3];
1505 assert_eq!(
1506 (pro.max_orders, pro.min_signatures, pro.security_class),
1507 (999, 2, None)
1508 );
1509 assert!(b.unparsed().is_empty());
1510 let b = bpd(&["DIKKUS:6:2:4+1+1+0'"]);
1512 assert!(b.job("DKKKU").is_some());
1513 }
1514
1515 #[test]
1516 fn rejected_segment_is_header_only_and_unparsed() {
1517 let b = bpd(&["HIKAZS:6:6:4+1+1+0+90:X:N'"]);
1519 let v6 = &b.job("HKKAZ").unwrap().versions[&6];
1520 assert!(matches!(v6.detail, JobDetail::Raw(_)));
1521 assert_eq!(v6.security_class, Some(0));
1522 assert_eq!(b.unparsed().len(), 1);
1523 assert_eq!(b.unparsed()[0].segment.segment_type(), "HIKAZS");
1524 assert!(b.unparsed()[0].error.field.contains("max_entries_allowed"));
1525 }
1526
1527 #[test]
1528 fn segment_without_header_is_unparsed_and_not_offered() {
1529 let b = bpd(&["HIXYZS:6:1:4+*+*'"]);
1530 assert!(b.job("HKXYZ").is_none());
1531 assert_eq!(b.unparsed().len(), 1);
1532 assert_eq!(b.unparsed()[0].error.kind, ErrorKind::UnknownSegment);
1533 }
1534
1535 #[test]
1536 fn general_parameter_segments_are_not_jobs() {
1537 let b = bpd(&[
1538 "HIKOM:6:4:4+280:12345678+1+3:https?://x'",
1539 "HISHV:7:3:4+N+PIN:1'",
1540 ]);
1541 assert!(b.jobs().next().is_none());
1542 assert!(b.unparsed().is_empty());
1543 }
1544
1545 #[test]
1546 fn pin_tan_and_tan_required() {
1547 let b = bpd(&[
1548 "HIPINS:6:1:4+1+1+0+5:20:6:Kundennummer:Kunden-ID:HKSAL:N:HKCCS:J'",
1549 "HISALS:7:6:4+1+1+0'",
1550 ]);
1551 let p = b.pin_tan.as_ref().unwrap();
1552 assert_eq!(
1553 (p.min_pin_length, p.max_pin_length, p.max_tan_length),
1554 (Some(5), Some(20), Some(6))
1555 );
1556 assert_eq!(p.user_id_text.as_deref(), Some("Kundennummer"));
1557 assert_eq!(b.tan_required("HKSAL"), Some(false));
1558 assert_eq!(b.tan_required("HKCCS"), Some(true));
1560 assert!(b.job("HKCCS").is_none());
1561 assert_eq!(b.tan_required("HKKAZ"), None);
1562 assert!(b.job("HKPIN").is_some());
1563 assert_eq!(bpd(&[]).tan_required("HKSAL"), None);
1564 }
1565
1566 #[test]
1567 fn tan_methods_per_version() {
1568 let hitans7 = "HITANS:6:7:4+1+1+0+N:N:1:900:2:MS1.0.0:photoTAN::Generator:9:1:TAN:999:J:1:N:0:0:N:J:00:0:J:1::::::901:2:MS2.0.0:Decoupled::App:::TAN:999:J:1:N:0:0:N:J:00:0:J:1:60:5:5:N:J'";
1569 let b = bpd(&[hitans7]);
1570 assert_eq!(b.tan.hktan_versions().collect::<Vec<_>>(), [7]);
1571 assert_eq!(b.tan.versions[&7].one_step_allowed, Some(false));
1572 let sf: Vec<&str> = b
1573 .tan_methods()
1574 .map(|m| m.security_function.as_str())
1575 .collect();
1576 assert_eq!(sf, ["900", "901"]);
1577 assert!(b.tan_methods().nth(1).unwrap().is_decoupled);
1578 assert!(b.job("HKTAN").is_some());
1579 }
1580
1581 #[test]
1582 fn sepa_is_the_highest_hispas() {
1583 let b = bpd(&[
1584 "HISPAS:6:1:4+1+1+0+J:J:J:urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.03'",
1585 "HISPAS:7:3:4+1+1+0+J:N:J:J:27'",
1586 ]);
1587 let s = b.sepa().unwrap();
1588 assert!(!s.national_account_allowed);
1589 assert_eq!(s.max_entries_allowed, Some(true));
1590 assert_eq!(s.reserved_purpose_places, Some(27));
1591 assert!(s.formats.is_empty());
1592 assert!(
1593 bpd(&["HISPAS:6:1:4+1+1+0+J:J:N'"])
1594 .sepa()
1595 .unwrap()
1596 .national_account_allowed
1597 );
1598 assert!(bpd(&[]).sepa().is_none());
1599 }
1600
1601 #[test]
1602 fn highest_common_version() {
1603 let b = bpd(&[
1604 "HISALS:6:5:4+1+1'",
1605 "HISALS:7:6:4+1+1+0'",
1606 "HISALS:8:7:4+1+1+0'",
1607 ]);
1608 assert_eq!(b.highest_common("HKSAL", &[5, 6, 8]), Ok(6));
1609 assert_eq!(b.highest_common("HKSAL", &[8, 7]), Ok(7));
1610 let e = b.highest_common("HKSAL", &[8]).unwrap_err();
1611 assert_eq!(
1612 (e.offered.as_slice(), e.implemented.as_slice()),
1613 (&[5, 6, 7][..], &[8][..])
1614 );
1615 assert_eq!(
1616 e.to_string(),
1617 "HKSAL: no common version (bank offers 5, 6, 7, client implements 8)"
1618 );
1619 let e = b.highest_common("HKKAZ", &[6, 7]).unwrap_err();
1620 assert_eq!(
1621 e.to_string(),
1622 "HKKAZ: bank does not offer this order (client implements 6, 7)"
1623 );
1624 }
1625
1626 #[test]
1627 fn bpd_replaced_with_hibpa_merged_without() {
1628 let current = segs(&[HIBPA, "HISALS:6:5:4+1+1'", "HISALS:7:6:4+1+1+0'"]);
1629 let response = segs(&[
1631 "HIRMG:2:2+0010::ok'",
1632 "HIBPA:3:3:4+13+280:12345678+Testbank+3+1+300'",
1633 "HIKAZS:4:6:4+1+1+0+90:J:N'",
1634 ]);
1635 let next = bpd_after(¤t, &response).unwrap();
1636 let codes: Vec<_> = next.iter().map(|s| s.segment_type()).collect();
1637 assert_eq!(codes, ["HIBPA", "HIKAZS"]);
1638 assert_eq!(Bpd::from_segments(&next).unwrap().version, 13);
1639 let response = segs(&["HISALS:3:6:4+9+1+0'", "HISALS:4:7:4+1+1+0'"]);
1641 let next = bpd_after(¤t, &response).unwrap();
1642 let b = Bpd::from_segments(&next).unwrap();
1643 assert_eq!(b.version, 12);
1644 let sal = b.job("HKSAL").unwrap();
1645 assert_eq!(sal.offered().collect::<Vec<_>>(), [5, 6, 7]);
1646 assert_eq!(sal.versions[&6].max_orders, 9);
1647 assert_eq!(next.len(), 4);
1648 assert!(bpd_after(¤t, &segs(&["HIRMG:2:2+0010::ok'"])).is_none());
1650 }
1651
1652 const HIUPD6: &str = "HIUPD:6:6:4+1234567890::280:12345678+DE00123456781234567890+CUST0001+1+EUR+Erika Beispiel+Max Beispiel+Girokonto+T:2500,:EUR+HKSAL:1+HKKAZ:1+HKCCS:1:E:1000,:EUR'";
1653 const HIUPD4: &str =
1654 "HIUPD:7:4:4+7654321::280:12345678+CUST0001+EUR+Erika Beispiel++Sparkonto++HKSAL:2'";
1655
1656 #[test]
1657 fn upd_accounts_and_usage() {
1658 let u = Upd::from_segments(&segs(&["HIUPA:5:4:4+USER0001+7+0'", HIUPD6, HIUPD4])).unwrap();
1659 assert_eq!((u.version, u.usage), (7, UpdUsage::Closed));
1660 assert!(!u.is_dialog_only());
1661 assert_eq!(u.accounts().len(), 2);
1662 let a = &u.accounts()[0];
1663 assert_eq!(a.account_number.as_deref(), Some("1234567890"));
1664 assert_eq!(a.iban, Some(Iban::new("DE00123456781234567890")));
1665 assert_eq!(a.customer_id, "CUST0001");
1666 assert_eq!(a.class(), Some(AccountClass::Checking));
1667 assert_eq!(a.owner, ["Erika Beispiel", "Max Beispiel"]);
1668 assert_eq!(a.limit.as_ref().unwrap().kind, LimitKind::Day);
1669 assert_eq!(a.limit.as_ref().unwrap().amount, Some(Decimal::from(2500)));
1670 let ccs = &a.allowed[&SegmentType::new("HKCCS")];
1671 assert_eq!(ccs.limit.as_ref().unwrap().kind, LimitKind::SingleOrder);
1672 assert_eq!(u.allows(a, "HKSAL"), Allowance::Yes);
1673 assert_eq!(u.allows(a, "HKWPD"), Allowance::No);
1674 assert_eq!(a.key().unwrap().to_string(), "12345678/1234567890");
1675 let b = &u.accounts()[1];
1677 assert_eq!((b.iban.as_ref(), b.account_type), (None, None));
1678 assert_eq!(b.allowed[&SegmentType::new("HKSAL")].min_signatures, 2);
1679 assert_eq!(b.product_name.as_deref(), Some("Sparkonto"));
1680
1681 let u = Upd::from_segments(&segs(&["HIUPA:5:4:4+USER0001+7+1'", HIUPD4])).unwrap();
1682 assert_eq!(u.usage, UpdUsage::Open);
1683 assert_eq!(u.allows(&u.accounts()[0], "HKWPD"), Allowance::Unknown);
1684 }
1685
1686 #[test]
1687 fn upd_version_0_is_dialog_only() {
1688 let u = Upd::from_segments(&segs(&["HIUPA:5:4:4+USER0001+0+0'"])).unwrap();
1689 assert!(u.is_dialog_only());
1690 assert!(u.accounts().is_empty());
1691 }
1692
1693 #[test]
1694 fn unreadable_hiupd_is_unparsed() {
1695 let u = Upd::from_segments(&segs(&[
1696 "HIUPA:5:4:4+USER0001+7+0'",
1697 "HIUPD:6:6:4+1::280:12345678++C+abc+EUR+Name'",
1698 HIUPD4,
1699 ]))
1700 .unwrap();
1701 assert_eq!(u.accounts().len(), 1);
1702 assert_eq!(u.unparsed().len(), 1);
1703 assert_eq!(u.unparsed()[0].error.field, "account_type");
1704 }
1705
1706 #[test]
1707 fn upd_replaced_only_with_hiupa() {
1708 assert!(upd_after(&segs(&["HIRMG:2:2+0010::ok'", HIUPD6])).is_none());
1709 let next = upd_after(&segs(&[
1710 "HIRMG:2:2+0010::ok'",
1711 "HIUPA:5:4:4+U+8+0'",
1712 HIUPD6,
1713 ]))
1714 .unwrap();
1715 let codes: Vec<_> = next.iter().map(|s| s.segment_type()).collect();
1716 assert_eq!(codes, ["HIUPA", "HIUPD"]);
1717 }
1718
1719 #[test]
1720 fn model_serialises_for_inspection() {
1721 let b = bpd(&["HIKAZS:6:6:4+1+1+0+90:X:N'"]);
1722 let json = serde_json::to_value(&b).unwrap();
1723 assert_eq!(json["jobs"]["HKKAZ"]["versions"]["6"]["max_orders"], 1);
1724 assert!(
1725 json["unparsed"][0]["error"]
1726 .as_str()
1727 .unwrap()
1728 .contains("max_entries_allowed")
1729 );
1730 }
1731
1732 #[test]
1734 #[cfg(repo_checkout)]
1735 fn consorsbank_trace() {
1736 let path = concat!(
1737 env!("CARGO_MANIFEST_DIR"),
1738 "/testbank/fixtures/replay/consorsbank-76030080.trace.json"
1739 );
1740 let json: serde_json::Value =
1741 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
1742 let answer = |marker: &str| -> Vec<RawSegment> {
1743 let exchange = json["exchanges"]
1744 .as_array()
1745 .unwrap()
1746 .iter()
1747 .find(|e| {
1748 e["response"]
1749 .as_array()
1750 .unwrap()
1751 .iter()
1752 .any(|s| s.as_str().unwrap().starts_with(marker))
1753 })
1754 .unwrap();
1755 let wire: Vec<&str> = exchange["response"]
1756 .as_array()
1757 .unwrap()
1758 .iter()
1759 .map(|s| s.as_str().unwrap())
1760 .filter(|s| s.starts_with("HI") || s.starts_with("DI"))
1761 .collect();
1762 segs(&wire)
1763 };
1764
1765 let b = Bpd::from_segments(&answer("HIBPA:")).unwrap();
1766 let p = b.pin_tan.as_ref().unwrap();
1767 let flags: Vec<(&str, bool)> = p
1768 .tan_required
1769 .iter()
1770 .map(|(k, v)| (k.as_str(), *v))
1771 .collect();
1772 assert_eq!(
1773 flags,
1774 [
1775 ("HKCCS", true),
1776 ("HKIPZ", true),
1777 ("HKKAZ", false),
1778 ("HKPRO", false),
1779 ("HKSAL", false),
1780 ("HKSPA", false),
1781 ("HKTAN", false),
1782 ("HKWPD", false),
1783 ("XKADA", false),
1784 ("XKADS", false),
1785 ]
1786 );
1787 let offered = |code| b.job(code).unwrap().offered().collect::<Vec<_>>();
1788 assert_eq!(offered("HKSAL"), [3, 4, 5, 6]);
1789 assert_eq!(offered("HKKAZ"), [3, 4, 5, 6, 7]);
1790 assert_eq!(offered("HKWPD"), [2, 3, 4, 5, 6]);
1791 assert_eq!(offered("HKPRO"), [3, 4]);
1792 assert_eq!(b.tan.hktan_versions().collect::<Vec<_>>(), [7]);
1793 let sf: Vec<&str> = b
1794 .tan_methods()
1795 .map(|m| m.security_function.as_str())
1796 .collect();
1797 assert_eq!(sf, ["900", "901"]);
1798 let s = b.sepa().unwrap();
1799 assert!(
1800 s.single_account_allowed && s.national_account_allowed && s.structured_purpose_allowed
1801 );
1802 assert!(matches!(
1804 b.job("HKKAZ").unwrap().versions[&7].detail,
1805 JobDetail::Statement(_)
1806 ));
1807 assert!(matches!(
1808 b.job("HKKAZ").unwrap().versions[&4].detail,
1809 JobDetail::Raw(_)
1810 ));
1811 assert!(matches!(
1812 b.job("HKWPD").unwrap().versions[&6].detail,
1813 JobDetail::Holdings(_)
1814 ));
1815 assert!(matches!(
1816 b.job("HKCCS").unwrap().versions[&1].detail,
1817 JobDetail::None
1818 ));
1819 assert!(matches!(
1820 b.job("HKIPZ").unwrap().versions[&1].detail,
1821 JobDetail::Instant(_)
1822 ));
1823 assert!(b.unparsed().is_empty());
1826 assert!(b.job("DKPIN").is_some());
1827
1828 let u = Upd::from_segments(&answer("HIUPA:")).unwrap();
1829 assert!(u.is_dialog_only());
1830 assert_eq!(u.usage, UpdUsage::Closed);
1831 assert!(u.unparsed().is_empty());
1832 assert_eq!(u.accounts().len(), 7);
1833 fn jobs(a: &UpdAccount) -> Vec<&str> {
1834 a.allowed.keys().map(|k| k.as_str()).collect()
1835 }
1836 let giro = ["HKCCS", "HKIPZ", "HKKAZ", "HKPRO", "HKSAL", "HKSPA"];
1837 assert_eq!(u.accounts().iter().filter(|a| a.iban.is_none()).count(), 1);
1839 for a in u.accounts() {
1840 if a.iban.is_none() {
1841 assert_eq!(jobs(a), ["HKPRO", "HKWPD"]);
1842 assert_eq!(u.allows(a, "HKSAL"), Allowance::No);
1843 } else {
1844 assert_eq!(jobs(a), giro);
1845 assert_eq!(u.allows(a, "HKWPD"), Allowance::No);
1846 }
1847 assert_eq!(a.currency, Some(Currency::new("EUR")));
1848 }
1849 }
1850
1851 const URN_09: &str = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09";
1852 const URN_03: &str = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03";
1853 const URN_09_WIRE: &str = "urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.09";
1854 const URN_03_WIRE: &str = "urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.03";
1855 const HISPAS: &str =
1856 "HISPAS:8:1:4+1+1+0+J:J:J:urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.03'";
1857
1858 #[test]
1859 fn vop_reads_the_parameters_of_the_highest_hivpps() {
1860 let b = bpd(&[
1861 "HIVPPS:9:1:4+1+1+0+1000:N:V:N:N:urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.002.001.10;sepade.pain.002.001.10.xsd:HKCCS:HKIPZ'",
1862 ]);
1863 assert!(b.unparsed().is_empty(), "{:?}", b.unparsed());
1864 let v = b.vop().expect("vop");
1865 assert_eq!(v.max_transactions, 1000);
1866 assert!(!v.explanation_structured);
1867 assert_eq!(v.delivery, VopDelivery::Complete);
1868 assert!(!v.bulk_with_one_order_allowed && !v.max_entries_input_allowed);
1869 assert_eq!(
1870 v.report_formats,
1871 [
1872 "urn:iso:std:iso:20022:tech:xsd:pain.002.001.10",
1873 "sepade.pain.002.001.10.xsd"
1874 ]
1875 );
1876 assert!(v.requires("HKCCS") && v.requires("HKIPZ") && !v.requires("HKKAZ"));
1877 let c = bpd(&["HIVPPS:9:1:4+1+1+0+20:J:S:N:N:x.xsd:HKIPZ'"]);
1878 let v = c.vop().unwrap();
1879 assert_eq!(v.delivery, VopDelivery::Stepwise);
1880 assert!(v.explanation_structured);
1881 assert!(!v.requires("HKCCS"));
1882 }
1883
1884 #[test]
1885 fn vop_is_none_without_hivpps_and_kept_with_an_unknown_delivery() {
1886 assert!(bpd(&[HISPAS]).vop().is_none());
1887 let b = bpd(&["HIVPPS:9:1:4+1+1+0+20:J:X:N:N:x.xsd:HKIPZ'"]);
1888 let v = b.vop().expect("an unknown delivery keeps the parameters");
1889 assert_eq!(v.delivery, VopDelivery::Other("X".into()));
1890 assert!(v.requires("HKIPZ"));
1891 }
1892
1893 #[test]
1894 fn instant_summarises_hiipzs_and_hiipss() {
1895 let ipz1 = format!("HIIPZS:3:1:4+1+1+0+BENE, SALA,:{URN_09_WIRE}'");
1896 let ipz2 = format!("HIIPZS:4:2:4+1+1+0+J::{URN_09_WIRE}:{URN_03_WIRE}'");
1897 let ips = "HIIPSS:5:1:4+1+1+0+5'";
1898 let b = bpd(&[&ipz1, &ipz2, ips]);
1899 assert!(b.unparsed().is_empty(), "{:?}", b.unparsed());
1900 let i = b.instant().expect("instant");
1901 assert_eq!(i.versions, [1, 2]);
1902 assert!(i.payment.conversion_allowed);
1903 assert!(i.payment.purpose_codes.is_empty());
1904 assert_eq!(i.payment.formats, [URN_09, URN_03]);
1905 let s = i.status.expect("status");
1906 assert_eq!((s.min_wait, s.formats.len()), (5, 0));
1907
1908 let b = bpd(&[&ipz1]);
1909 let i = b.instant().unwrap();
1910 assert!(!i.payment.conversion_allowed);
1911 assert_eq!(i.payment.purpose_codes, ["BENE", "SALA"]);
1912 assert!(i.status.is_none());
1913 assert!(bpd(&[HISPAS]).instant().is_none());
1914 }
1915
1916 #[test]
1917 fn sepa_formats_per_order() {
1918 let ipz = format!("HIIPZS:3:1:4+1+1+0+:{URN_09_WIRE}'");
1919 let b = bpd(&[HISPAS, &ipz, "HICCSS:4:1:4+1+1+0'"]);
1920 assert_eq!(b.sepa_formats(Order::Transfer), [URN_03]);
1921 assert_eq!(b.sepa_formats(Order::InstantTransfer), [URN_09]);
1922 let b = bpd(&[HISPAS, &ipz, "HIIPSS:5:1:4+1+1+0+5'"]);
1924 assert_eq!(b.sepa_formats(Order::InstantStatus), [URN_03]);
1925 let ips = format!("HIIPSS:5:1:4+1+1+0+5:{URN_09_WIRE}'");
1926 let b = bpd(&[HISPAS, &ips]);
1927 assert_eq!(b.sepa_formats(Order::InstantStatus), [URN_09]);
1928 let b = bpd(&[HISPAS, "HIIPZS:3:1:4+1+1+0+'"]);
1930 assert_eq!(b.sepa_formats(Order::InstantTransfer), [URN_03]);
1931 assert!(bpd(&[]).sepa_formats(Order::Transfer).is_empty());
1932 assert!(b.sepa_formats(Order::Balance).is_empty());
1934 assert!(b.sepa_formats(Order::VopCheck).is_empty());
1935 }
1936
1937 #[test]
1938 fn payment_parameter_segments_without_own_parameters_read_typed() {
1939 let b = bpd(&["HICCSS:3:1:4+999+1+0'", "HIVPAS:4:1:4+1+1+0'"]);
1940 assert!(b.unparsed().is_empty());
1941 for code in ["HKCCS", "HKVPA"] {
1942 let v = &b.job(code).unwrap().versions[&1];
1943 assert!(matches!(v.detail, JobDetail::None), "{code}");
1944 }
1945 assert_eq!(b.job("HKCCS").unwrap().versions[&1].max_orders, 999);
1946 }
1947}