1use std::fmt;
11
12use serde::{Deserialize, Serialize};
13
14use crate::types::{SecurityFunction, SegmentType, TouchdownPoint};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
18#[serde(try_from = "String", into = "String")]
19pub struct Code([u8; 4]);
20
21impl Code {
22 pub fn new(s: &str) -> Option<Self> {
24 let bytes: [u8; 4] = s.as_bytes().try_into().ok()?;
25 bytes.iter().all(u8::is_ascii_digit).then_some(Self(bytes))
26 }
27
28 pub fn as_str(&self) -> &str {
30 std::str::from_utf8(&self.0).unwrap_or("????")
32 }
33
34 pub fn class(self) -> Class {
36 match self.0[0] {
37 b'0' => Class::Success,
38 b'1' => Class::Note,
39 b'3' => Class::Warning,
40 b'9' => Class::Error,
41 _ => Class::Undefined,
42 }
43 }
44}
45
46impl fmt::Display for Code {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.write_str(self.as_str())
49 }
50}
51
52impl TryFrom<String> for Code {
53 type Error = String;
54 fn try_from(s: String) -> Result<Self, String> {
55 Self::new(&s).ok_or_else(|| format!("not a four-digit return code: {s:?}"))
56 }
57}
58
59impl From<Code> for String {
60 fn from(c: Code) -> String {
61 c.as_str().to_string()
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum Class {
68 Success,
70 Note,
72 Warning,
74 Error,
76 Undefined,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
82pub enum Scope {
83 Message,
85 Segment {
87 number: u16,
90 order: Option<SegmentType>,
93 },
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum Kind {
102 MessageReceived,
104 OrderExecuted,
106 TanRequired,
108 DialogEnded,
110 TanValid,
112 NoNameDeviation,
114 BicOutdated { new_bic: Option<String> },
116 InstantStatusQuery,
118 CheckTransactions,
120 ProcessingReference { reference: Option<String> },
123 NotAvailable,
127 Touchdown(TouchdownPoint),
129 PartialWarnings,
131 UserDataChanged {
134 user_id: Option<String>,
135 customer_id: Option<String>,
136 },
137 ScaExemption,
139 VopCheckResult,
141 VopNotRequired,
143 VopRequiredFrom { date: Option<String> },
145 VopInProgress,
147 VopComplete,
149 VopNoResult,
151 ConvertedToStandard,
154 AllowedSecurityFunctions(Vec<SecurityFunction>),
156 VopApprovalNotPossible,
158 DecoupledInitiated,
161 DecoupledPending,
163 DecoupledAwaitPush,
167 DecoupledMethodUnsupported,
169 OutcomeUnknown { query: Option<SegmentType> },
173 GeneralError,
175 AuthenticationFailed,
179 PartialErrors,
181 ScaRequired,
183 VopRequired,
186 ProductNotRegistered,
188 UnknownStructure,
190 ElementNotAllowed,
193 InsufficientFunds,
195 DuplicateSubmission,
197 NotExpected,
199 DataElementMissing,
201 NoLongerAccepted,
203 ProtocolVersionUnsupported,
205 VopUnavailable,
208 InstantLimitExceeded { link: Option<String> },
211 PinTanUnavailable,
213 SecurityProcedureNotAllowed,
215 SignatureInsufficient,
217 NotAuthorised,
220 SignatureInvalid,
225 PinWrong,
229 SystemIdInvalid,
231 DialogAborted,
233 AccountLocked,
235 LockAfterAttempts { attempts_left: Option<u32> },
239 TanInvalid,
241 TanUsed,
243 TanExpired,
245 SmsNotSent,
247 Other,
249}
250
251impl Kind {
252 pub fn of(code: Code, parameters: &[String]) -> Self {
255 let params: Vec<&String> = parameters.iter().filter(|p| !p.is_empty()).collect();
256 match code.as_str() {
257 "0010" => Self::MessageReceived,
258 "0020" => Self::OrderExecuted,
259 "0030" => Self::TanRequired,
260 "0100" => Self::DialogEnded,
261 "0900" => Self::TanValid,
262 "0025" => Self::NoNameDeviation,
263 "3020" => Self::BicOutdated {
264 new_bic: params.first().map(|s| s.to_string()),
265 },
266 "3045" => Self::InstantStatusQuery,
267 "3046" => Self::CheckTransactions,
268 "3070" => Self::ProcessingReference {
269 reference: params.first().map(|s| s.to_string()),
270 },
271 "3090" => Self::VopCheckResult,
272 "3092" => Self::VopRequiredFrom {
273 date: params.first().map(|s| s.to_string()),
274 },
275 "3093" => Self::VopInProgress,
276 "3094" => Self::VopComplete,
277 "3095" => Self::VopNoResult,
278 "3270" => Self::ConvertedToStandard,
279 "9150" => Self::ElementNotAllowed,
280 "9230" => Self::InsufficientFunds,
281 "9390" => Self::DuplicateSubmission,
282 "3010" => Self::NotAvailable,
283 "3040" => Self::Touchdown(TouchdownPoint::new(
284 params.first().map(|s| s.as_str()).unwrap_or(""),
285 )),
286 "3060" => Self::PartialWarnings,
287 "3072" => Self::UserDataChanged {
288 user_id: params.first().map(|s| s.to_string()),
289 customer_id: params.get(1).or(params.first()).map(|s| s.to_string()),
290 },
291 "3076" => Self::ScaExemption,
292 "3091" => Self::VopNotRequired,
293 "3920" => Self::AllowedSecurityFunctions(
294 params.into_iter().map(SecurityFunction::new).collect(),
295 ),
296 "3945" => Self::VopApprovalNotPossible,
297 "3955" => Self::DecoupledInitiated,
298 "3956" => Self::DecoupledPending,
299 "3957" => Self::DecoupledAwaitPush,
300 "3958" => Self::DecoupledMethodUnsupported,
301 "9000" => Self::OutcomeUnknown {
302 query: params.first().map(|s| SegmentType::new(s.as_str())),
303 },
304 "9010" => Self::GeneralError,
305 "9040" => Self::AuthenticationFailed,
306 "9050" => Self::PartialErrors,
307 "9075" => Self::ScaRequired,
308 "9076" => Self::VopRequired,
309 "9078" => Self::ProductNotRegistered,
310 "9110" => Self::UnknownStructure,
311 "9120" => Self::NotExpected,
312 "9160" => Self::DataElementMissing,
313 "9180" => Self::NoLongerAccepted,
314 "9185" => Self::ProtocolVersionUnsupported,
315 "9250" => Self::VopUnavailable,
316 "9255" => Self::InstantLimitExceeded {
317 link: params.first().map(|s| s.to_string()),
318 },
319 "9311" => Self::PinTanUnavailable,
320 "9360" => Self::LockAfterAttempts {
321 attempts_left: params.first().and_then(|p| p.trim().parse().ok()),
322 },
323 "9361" => Self::SecurityProcedureNotAllowed,
324 "9370" => Self::SignatureInsufficient,
325 "9380" => Self::NotAuthorised,
326 "9340" => Self::SignatureInvalid,
327 "9910" | "9942" => Self::PinWrong,
328 "9391" => Self::SystemIdInvalid,
329 "9800" => Self::DialogAborted,
330 "9930" | "9931" => Self::AccountLocked,
331 "9941" => Self::TanInvalid,
332 "9943" => Self::TanUsed,
333 "9951" => Self::TanExpired,
334 "9959" => Self::SmsNotSent,
335 _ => Self::Other,
336 }
337 }
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
346#[serde(rename_all = "snake_case")]
347#[non_exhaustive]
348pub enum Category {
349 Credentials(Credentials),
353 SystemId,
356 ScaRequired,
359 Tan,
362 DialogEnded,
364 Unsupported,
367 AuthenticationRefused,
373 NotPermitted,
375 OutcomeUnknown,
379 Temporary,
382 ClientFault,
386 InvalidInput,
390 Rejected,
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
396#[serde(rename_all = "snake_case")]
397pub enum Credentials {
398 PinWrong,
400 SignatureInvalid,
403 Locked,
405 Unclear,
408}
409
410impl Category {
411 pub fn of(code: Code, kind: &Kind) -> Option<Self> {
413 if code.class() != Class::Error {
414 return None;
415 }
416 Some(match kind {
417 Kind::PinWrong if code.as_str() == "9910" => Self::Credentials(Credentials::Unclear),
418 Kind::PinWrong => Self::Credentials(Credentials::PinWrong),
419 Kind::SignatureInvalid => Self::Credentials(Credentials::SignatureInvalid),
420 Kind::AccountLocked
421 | Kind::LockAfterAttempts {
422 attempts_left: None,
423 } => Self::Credentials(Credentials::Locked),
424 Kind::LockAfterAttempts { .. } => Self::Tan,
425 Kind::SystemIdInvalid => Self::SystemId,
426 Kind::ScaRequired => Self::ScaRequired,
427 Kind::TanInvalid | Kind::TanUsed | Kind::TanExpired => Self::Tan,
428 Kind::DialogAborted => Self::DialogEnded,
429 Kind::VopRequired
430 | Kind::ProductNotRegistered
431 | Kind::NoLongerAccepted
432 | Kind::ProtocolVersionUnsupported
433 | Kind::SecurityProcedureNotAllowed => Self::Unsupported,
434 Kind::AuthenticationFailed => Self::AuthenticationRefused,
435 Kind::SignatureInsufficient | Kind::NotAuthorised => Self::NotPermitted,
436 Kind::OutcomeUnknown { .. } => Self::OutcomeUnknown,
437 Kind::VopUnavailable | Kind::PinTanUnavailable | Kind::SmsNotSent => Self::Temporary,
438 Kind::UnknownStructure | Kind::NotExpected => Self::ClientFault,
439 _ if ("9130".."9171").contains(&code.as_str()) => Self::ClientFault,
441 _ => Self::Rejected,
442 })
443 }
444}
445
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
449pub struct ReturnCode {
450 pub code: Code,
452 pub text: String,
454 pub scope: Scope,
456 pub reference_element: Option<String>,
459 pub parameters: Vec<String>,
462}
463
464impl ReturnCode {
465 pub fn new(code: Code, text: impl Into<String>, scope: Scope) -> Self {
467 Self {
468 code,
469 text: text.into(),
470 scope,
471 reference_element: None,
472 parameters: Vec::new(),
473 }
474 }
475
476 pub fn with_parameters(mut self, parameters: Vec<String>) -> Self {
478 self.parameters = parameters;
479 self
480 }
481
482 pub fn with_reference_element(mut self, element: impl Into<String>) -> Self {
484 self.reference_element = Some(element.into());
485 self
486 }
487
488 pub fn class(&self) -> Class {
490 self.code.class()
491 }
492
493 pub fn kind(&self) -> Kind {
495 Kind::of(self.code, &self.parameters)
496 }
497
498 pub fn category(&self) -> Option<Category> {
500 Category::of(self.code, &self.kind())
501 }
502
503 pub fn is_error(&self) -> bool {
505 self.class() == Class::Error
506 }
507}
508
509impl fmt::Display for ReturnCode {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 write!(f, "{}: {}", self.code, self.text)
513 }
514}
515
516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[non_exhaustive]
523pub enum Notice {
524 Bank {
526 dialog: NoticeDialog,
532 code: ReturnCode,
536 },
537 Client {
539 dialog: NoticeDialog,
541 warning: ClientWarning,
543 },
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
549#[non_exhaustive]
550#[serde(rename_all = "snake_case")]
551pub enum ClientWarning {
552 Utf8TextInLatin1,
557 RangeClamped {
562 requested: jiff::civil::Date,
563 used: jiff::civil::Date,
564 },
565}
566
567#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
569#[serde(rename_all = "snake_case")]
570pub enum NoticeDialog {
571 Sync,
573 Job,
575}
576
577impl Notice {
578 pub fn new(dialog: NoticeDialog, code: ReturnCode) -> Self {
580 Self::Bank { dialog, code }
581 }
582
583 pub fn client(dialog: NoticeDialog, warning: ClientWarning) -> Self {
585 Self::Client { dialog, warning }
586 }
587
588 pub fn dialog(&self) -> NoticeDialog {
590 match self {
591 Self::Bank { dialog, .. } | Self::Client { dialog, .. } => *dialog,
592 }
593 }
594
595 pub fn code(&self) -> Option<&ReturnCode> {
597 match self {
598 Self::Bank { code, .. } => Some(code),
599 Self::Client { .. } => None,
600 }
601 }
602
603 pub fn kind(&self) -> Option<Kind> {
605 self.code().map(ReturnCode::kind)
606 }
607
608 pub fn client_warning(&self) -> Option<ClientWarning> {
610 match self {
611 Self::Client { warning, .. } => Some(*warning),
612 Self::Bank { .. } => None,
613 }
614 }
615
616 pub(crate) fn is_consumed(code: &ReturnCode) -> bool {
620 let payee_check = matches!(
621 &code.scope,
622 Scope::Segment { order: Some(o), .. } if matches!(o.as_str(), "HKVPP" | "HKVPA")
623 );
624 match code.kind() {
625 Kind::TanRequired
626 | Kind::Touchdown(_)
627 | Kind::ScaExemption
628 | Kind::AllowedSecurityFunctions(_)
629 | Kind::DecoupledInitiated
630 | Kind::DecoupledPending
631 | Kind::VopNotRequired
632 | Kind::VopApprovalNotPossible
633 | Kind::InstantStatusQuery => true,
634 Kind::VopCheckResult | Kind::VopInProgress | Kind::VopComplete => payee_check,
635 _ => false,
636 }
637 }
638}
639
640impl fmt::Display for NoticeDialog {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642 f.write_str(match self {
643 Self::Sync => "sync",
644 Self::Job => "job",
645 })
646 }
647}
648
649impl fmt::Display for ClientWarning {
650 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
651 match self {
652 Self::Utf8TextInLatin1 => f.write_str(
653 "bank text looks like UTF-8 in an ISO 8859-1 answer (umlauts garbled); shown as decoded",
654 ),
655 Self::RangeClamped { requested, used } => write!(
656 f,
657 "statement range starts {requested}, before the bank's storage period; requested from {used}"
658 ),
659 }
660 }
661}
662
663impl fmt::Display for Notice {
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668 let (dialog, code) = match self {
669 Self::Bank { dialog, code } => (dialog, code),
670 Self::Client { dialog, warning } => {
671 return write!(f, "client [{dialog}]: {warning}");
672 }
673 };
674 write!(f, "{} [{}, ", code.code, dialog)?;
675 match &code.scope {
676 Scope::Message => f.write_str("HIRMG")?,
677 Scope::Segment {
678 order: Some(order), ..
679 } => write!(f, "{order}")?,
680 Scope::Segment { number, .. } => write!(f, "HIRMS #{number}")?,
681 }
682 write!(f, "]: {}", code.text)
683 }
684}
685
686pub(crate) fn looks_like_utf8_as_latin1(text: &str) -> bool {
692 let bytes: Vec<u8> = match text.chars().map(u8::try_from).collect() {
693 Ok(b) => b,
694 Err(_) => return false,
695 };
696 let mut i = 0;
697 while i < bytes.len() {
698 let len = match bytes[i] {
699 0xC2..=0xDF => 2,
700 0xE0..=0xEF => 3,
701 0xF0..=0xF4 => 4,
702 _ => 1,
703 };
704 if len > 1
705 && bytes
706 .get(i..i + len)
707 .is_some_and(|s| std::str::from_utf8(s).is_ok())
708 {
709 return true;
710 }
711 i += 1;
712 }
713 false
714}
715
716#[cfg(test)]
717mod mojibake_tests {
718 use super::looks_like_utf8_as_latin1 as detect;
719
720 fn latin1(utf8: &str) -> String {
721 utf8.bytes().map(char::from).collect()
722 }
723
724 #[test]
725 fn utf8_read_as_latin1_is_found() {
726 for s in ["Zahlung für Müller", "Straße", "Betrag in €", "schön"] {
727 assert!(detect(&latin1(s)), "{s}");
728 }
729 }
730
731 #[test]
732 fn real_latin1_umlauts_are_not_found() {
733 for s in [
734 "Zahlung für Müller, Größe, Äpfel, schön, Straße",
735 "ÄÖÜ äöü ß ÂÃ ÄÅ",
736 "Überweisung ausgeführt",
737 "plain ascii",
738 "",
739 ] {
740 assert!(!detect(s), "{s}");
741 }
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748
749 fn kind(code: &str, params: &[&str]) -> (Class, Kind) {
750 let params: Vec<String> = params.iter().map(|s| s.to_string()).collect();
751 let c = ReturnCode::new(Code::new(code).unwrap(), "t", Scope::Message)
752 .with_parameters(params.clone());
753 assert_eq!(c.parameters, params, "{code}: parameters kept verbatim");
754 (c.class(), c.kind())
755 }
756
757 #[test]
760 fn inventory() {
761 use Class::*;
762 let sf = |s: &str| SecurityFunction::new(s);
763 let cases: Vec<(&str, &[&str], Class, Kind)> = vec![
764 ("0010", &[], Success, Kind::MessageReceived),
765 ("0020", &[], Success, Kind::OrderExecuted),
766 ("0030", &[], Success, Kind::TanRequired),
767 ("0100", &[], Success, Kind::DialogEnded),
768 ("0900", &[], Success, Kind::TanValid),
769 ("0999", &[], Success, Kind::Other),
770 ("0025", &[], Success, Kind::NoNameDeviation),
771 (
772 "3020",
773 &["NEWBDEFFXXX"],
774 Warning,
775 Kind::BicOutdated {
776 new_bic: Some("NEWBDEFFXXX".into()),
777 },
778 ),
779 ("3045", &[], Warning, Kind::InstantStatusQuery),
780 ("3046", &[], Warning, Kind::CheckTransactions),
781 (
782 "3070",
783 &["REF-1"],
784 Warning,
785 Kind::ProcessingReference {
786 reference: Some("REF-1".into()),
787 },
788 ),
789 ("3090", &[], Warning, Kind::VopCheckResult),
790 (
791 "3092",
792 &["2026-10-09"],
793 Warning,
794 Kind::VopRequiredFrom {
795 date: Some("2026-10-09".into()),
796 },
797 ),
798 ("3093", &[], Warning, Kind::VopInProgress),
799 ("3094", &[], Warning, Kind::VopComplete),
800 ("3095", &[], Warning, Kind::VopNoResult),
801 ("3270", &[], Warning, Kind::ConvertedToStandard),
802 ("9150", &[], Error, Kind::ElementNotAllowed),
803 ("9230", &[], Error, Kind::InsufficientFunds),
804 ("9390", &[], Error, Kind::DuplicateSubmission),
805 ("3010", &[], Warning, Kind::NotAvailable),
806 (
807 "3040",
808 &["TD1"],
809 Warning,
810 Kind::Touchdown(TouchdownPoint::new("TD1")),
811 ),
812 ("3060", &[], Warning, Kind::PartialWarnings),
813 (
814 "3072",
815 &["new-user", "new-customer"],
816 Warning,
817 Kind::UserDataChanged {
818 user_id: Some("new-user".into()),
819 customer_id: Some("new-customer".into()),
820 },
821 ),
822 (
823 "3072",
824 &["new-user"],
825 Warning,
826 Kind::UserDataChanged {
827 user_id: Some("new-user".into()),
828 customer_id: Some("new-user".into()),
829 },
830 ),
831 (
832 "3072",
833 &[],
834 Warning,
835 Kind::UserDataChanged {
836 user_id: None,
837 customer_id: None,
838 },
839 ),
840 ("3076", &[], Warning, Kind::ScaExemption),
841 ("3091", &[], Warning, Kind::VopNotRequired),
842 (
843 "3920",
844 &["912", "913", "940"],
845 Warning,
846 Kind::AllowedSecurityFunctions(vec![sf("912"), sf("913"), sf("940")]),
847 ),
848 ("3945", &[], Warning, Kind::VopApprovalNotPossible),
849 ("3955", &[], Warning, Kind::DecoupledInitiated),
850 ("3956", &[], Warning, Kind::DecoupledPending),
851 ("3957", &[], Warning, Kind::DecoupledAwaitPush),
852 ("3958", &[], Warning, Kind::DecoupledMethodUnsupported),
853 ("3999", &["P"], Warning, Kind::Other),
854 (
855 "9000",
856 &["HKCAZ"],
857 Error,
858 Kind::OutcomeUnknown {
859 query: Some(SegmentType::new("HKCAZ")),
860 },
861 ),
862 ("9000", &[], Error, Kind::OutcomeUnknown { query: None }),
863 ("9010", &[], Error, Kind::GeneralError),
864 ("9040", &[], Error, Kind::AuthenticationFailed),
865 ("9050", &[], Error, Kind::PartialErrors),
866 ("9075", &[], Error, Kind::ScaRequired),
867 ("9076", &[], Error, Kind::VopRequired),
868 ("9078", &[], Error, Kind::ProductNotRegistered),
869 ("9110", &[], Error, Kind::UnknownStructure),
870 ("9120", &[], Error, Kind::NotExpected),
871 ("9160", &[], Error, Kind::DataElementMissing),
872 ("9180", &[], Error, Kind::NoLongerAccepted),
873 ("9185", &[], Error, Kind::ProtocolVersionUnsupported),
874 ("9250", &[], Error, Kind::VopUnavailable),
875 (
876 "9255",
877 &["https://bank.example/limit"],
878 Error,
879 Kind::InstantLimitExceeded {
880 link: Some("https://bank.example/limit".into()),
881 },
882 ),
883 (
884 "9255",
885 &[],
886 Error,
887 Kind::InstantLimitExceeded { link: None },
888 ),
889 ("9311", &[], Error, Kind::PinTanUnavailable),
890 (
891 "9360",
892 &["2"],
893 Error,
894 Kind::LockAfterAttempts {
895 attempts_left: Some(2),
896 },
897 ),
898 (
899 "9360",
900 &[],
901 Error,
902 Kind::LockAfterAttempts {
903 attempts_left: None,
904 },
905 ),
906 ("9361", &[], Error, Kind::SecurityProcedureNotAllowed),
907 ("9370", &[], Error, Kind::SignatureInsufficient),
908 ("9380", &[], Error, Kind::NotAuthorised),
909 ("9340", &[], Error, Kind::SignatureInvalid),
910 ("9910", &[], Error, Kind::PinWrong),
911 ("9942", &[], Error, Kind::PinWrong),
912 ("9391", &[], Error, Kind::SystemIdInvalid),
913 ("9800", &[], Error, Kind::DialogAborted),
914 ("9930", &[], Error, Kind::AccountLocked),
915 ("9931", &[], Error, Kind::AccountLocked),
916 ("9941", &[], Error, Kind::TanInvalid),
917 ("9943", &[], Error, Kind::TanUsed),
918 ("9951", &[], Error, Kind::TanExpired),
919 ("9959", &[], Error, Kind::SmsNotSent),
920 ("9210", &[], Error, Kind::Other),
922 ("9999", &["A", "B"], Error, Kind::Other),
923 ("1234", &[], Note, Kind::Other),
925 ("5000", &[], Undefined, Kind::Other),
926 ];
927 for (code, params, class, want) in cases {
928 assert_eq!(kind(code, params), (class, want), "{code} {params:?}");
929 }
930 }
931
932 #[test]
934 fn categories() {
935 use Category::*;
936 let cases: &[(&str, Option<Category>)] = &[
937 ("0020", None),
938 ("3040", None),
939 ("3999", None),
940 ("1234", None),
941 ("5000", None),
942 (
943 "9340",
944 Some(Credentials(super::Credentials::SignatureInvalid)),
945 ),
946 ("9942", Some(Credentials(super::Credentials::PinWrong))),
947 ("9930", Some(Credentials(super::Credentials::Locked))),
948 ("9931", Some(Credentials(super::Credentials::Locked))),
949 ("9910", Some(Credentials(super::Credentials::Unclear))),
950 ("9391", Some(SystemId)),
951 ("9075", Some(ScaRequired)),
952 ("9941", Some(Tan)),
953 ("9943", Some(Tan)),
954 ("9951", Some(Tan)),
955 ("9800", Some(DialogEnded)),
956 ("9076", Some(Unsupported)),
957 ("9078", Some(Unsupported)),
958 ("9180", Some(Unsupported)),
959 ("9185", Some(Unsupported)),
960 ("9360", Some(Credentials(super::Credentials::Locked))),
961 ("9361", Some(Unsupported)),
962 ("9370", Some(NotPermitted)),
963 ("9380", Some(NotPermitted)),
964 ("9000", Some(OutcomeUnknown)),
965 ("9250", Some(Temporary)),
966 ("9311", Some(Temporary)),
967 ("9959", Some(Temporary)),
968 ("9110", Some(ClientFault)),
969 ("9120", Some(ClientFault)),
970 ("9130", Some(ClientFault)),
971 ("9140", Some(ClientFault)),
972 ("9145", Some(ClientFault)),
973 ("9150", Some(ClientFault)),
974 ("9160", Some(ClientFault)),
975 ("9170", Some(ClientFault)),
976 ("9010", Some(Rejected)),
977 ("9040", Some(AuthenticationRefused)),
978 ("9050", Some(Rejected)),
979 ("9171", Some(Rejected)),
980 ("9210", Some(Rejected)),
981 ("9230", Some(Rejected)),
982 ("9390", Some(Rejected)),
983 ("9255", Some(Rejected)),
984 ("9999", Some(Rejected)),
985 ];
986 for (code, want) in cases {
987 let c = ReturnCode::new(Code::new(code).unwrap(), "t", Scope::Message);
988 assert_eq!(c.category(), *want, "{code}");
989 }
990 let c = ReturnCode::new(Code::new("9360").unwrap(), "t", Scope::Message)
993 .with_parameters(vec!["2".into()]);
994 assert_eq!(c.category(), Some(Tan));
995 }
996
997 #[test]
998 fn empty_parameters_are_kept_but_skipped_for_the_kind() {
999 let c = ReturnCode::new(Code::new("3072").unwrap(), "t", Scope::Message)
1000 .with_parameters(vec!["".into(), "cust".into()]);
1001 assert_eq!(c.parameters, ["", "cust"]);
1002 assert_eq!(
1003 c.kind(),
1004 Kind::UserDataChanged {
1005 user_id: Some("cust".into()),
1006 customer_id: Some("cust".into()),
1007 }
1008 );
1009 }
1010
1011 #[test]
1013 fn payee_check_codes_are_consumed_only_for_hkvpp_and_hkvpa() {
1014 let on = |code: &str, order: &str| {
1015 ReturnCode::new(
1016 Code::new(code).unwrap(),
1017 "t",
1018 Scope::Segment {
1019 number: 3,
1020 order: Some(SegmentType::new(order)),
1021 },
1022 )
1023 };
1024 for code in ["3090", "3093", "3094"] {
1025 assert!(Notice::is_consumed(&on(code, "HKVPP")), "{code}");
1026 assert!(Notice::is_consumed(&on(code, "HKVPA")), "{code}");
1027 assert!(!Notice::is_consumed(&on(code, "HKCCS")), "{code}");
1028 }
1029 assert!(Notice::is_consumed(&on("3045", "HKTAN")));
1030 for code in ["3070", "3092", "3270", "3046", "3020"] {
1031 assert!(!Notice::is_consumed(&on(code, "HKCCS")), "{code}");
1032 }
1033 }
1034
1035 #[test]
1036 fn code_is_four_digits() {
1037 for bad in ["", "123", "12345", "XXXX", "12a4", "١٢٣٤"] {
1038 assert_eq!(Code::new(bad), None, "{bad}");
1039 }
1040 assert_eq!(Code::new("0010").unwrap().to_string(), "0010");
1041 }
1042
1043 #[test]
1044 fn serde_round_trip() {
1045 let c = ReturnCode::new(
1046 Code::new("9210").unwrap(),
1047 "Konto unbekannt",
1048 Scope::Segment {
1049 number: 4,
1050 order: Some(SegmentType::new("HKSAL")),
1051 },
1052 )
1053 .with_reference_element("3")
1054 .with_parameters(vec!["A1".into()]);
1055 let json = serde_json::to_string(&c).unwrap();
1056 assert!(json.contains("\"code\":\"9210\""), "{json}");
1057 assert_eq!(serde_json::from_str::<ReturnCode>(&json).unwrap(), c);
1058 assert!(serde_json::from_str::<Code>("\"92\"").is_err());
1059 assert_eq!(c.to_string(), "9210: Konto unbekannt");
1060 }
1061}