1use jiff::civil::Date;
7use rust_decimal::Decimal;
8use rust_decimal::prelude::ToPrimitive;
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12use crate::parser::RawSegment;
13
14macro_rules! text_type {
21 ($(#[$doc:meta])* $ty:ident) => {
22 $(#[$doc])*
23 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
24 pub struct $ty(String);
25
26 impl $ty {
27 pub fn new(text: impl Into<String>) -> Self {
29 Self(text.into())
30 }
31
32 pub fn as_str(&self) -> &str {
34 self.0.as_str()
35 }
36 }
37
38 impl fmt::Display for $ty {
39 fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
40 fmt::Display::fmt(self.0.as_str(), out)
41 }
42 }
43
44 impl AsRef<str> for $ty {
45 fn as_ref(&self) -> &str {
46 self.as_str()
47 }
48 }
49 };
50}
51
52text_type!(
53 Blz
55);
56text_type!(
57 UserId
59);
60text_type!(
61 SystemId
63);
64text_type!(
65 ProductId
67);
68text_type!(
69 DialogId
71);
72text_type!(
73 SecurityFunction
75);
76text_type!(
77 TaskReference
79);
80text_type!(
81 SegmentType
83);
84text_type!(
85 TanMediumName
87);
88text_type!(
89 TouchdownPoint
91);
92text_type!(
93 SegmentRef
95);
96text_type!(
97 Currency
99);
100
101impl Currency {
102 pub fn exponent(&self) -> u32 {
106 match self.0.to_ascii_uppercase().as_str() {
107 "BIF" | "CLP" | "DJF" | "GNF" | "ISK" | "JPY" | "KMF" | "KRW" | "PYG" | "RWF"
108 | "UGX" | "UYI" | "VND" | "VUV" | "XAF" | "XOF" | "XPF" => 0,
109 "BHD" | "IQD" | "JOD" | "KWD" | "LYD" | "OMR" | "TND" => 3,
110 _ => 2,
111 }
112 }
113
114 pub fn to_minor(&self, amount: Decimal) -> Option<i64> {
118 let amount = amount.normalize();
119 let exponent = self.exponent();
120 if amount.scale() > exponent {
121 return None;
122 }
123 let minor = amount.checked_mul(Decimal::from(10_i64.pow(exponent)))?;
124 minor.to_i64()
125 }
126}
127text_type!(
128 Iban
130);
131text_type!(
132 Bic
134);
135text_type!(
136 BankName
138);
139text_type!(
140 FinTSUrl
142);
143text_type!(
144 ChallengeText
146);
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct HhdUcData(pub Vec<u8>);
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155pub enum TanMedia {
156 Image { mime_type: String, data: Vec<u8> },
159 Flicker(String),
162}
163
164impl HhdUcData {
165 pub fn decode(&self) -> Option<TanMedia> {
172 let bytes = &self.0[..];
173 matrix_code(bytes).or_else(|| flicker_code(bytes))
174 }
175}
176
177fn length_prefixed(input: &[u8]) -> Option<(&[u8], &[u8])> {
179 let (len, rest) = input.split_first_chunk::<2>()?;
180 let len = usize::from(u16::from_be_bytes(*len));
181 (rest.len() >= len).then(|| rest.split_at(len))
182}
183
184fn matrix_code(bytes: &[u8]) -> Option<TanMedia> {
185 let (media_type, rest) = length_prefixed(bytes)?;
186 let plausible = matches!(media_type.len(), 3..=100)
187 && media_type.iter().all(u8::is_ascii_graphic)
188 && media_type.contains(&b'/');
189 if !plausible {
190 return None;
191 }
192 let (picture, _) = length_prefixed(rest)?;
193 Some(TanMedia::Image {
194 mime_type: String::from_utf8_lossy(media_type).into_owned(),
195 data: picture.to_vec(),
196 })
197}
198
199fn flicker_code(bytes: &[u8]) -> Option<TanMedia> {
200 if bytes.is_empty() || bytes.iter().any(|b| !(b' '..=b'~').contains(b)) {
201 return None;
202 }
203 let text = std::str::from_utf8(bytes).ok()?;
205 Some(TanMedia::Flicker(text.trim().to_owned()))
206}
207
208#[derive(Debug, Clone, Default)]
210pub struct Mt940Data(pub Vec<u8>);
211
212impl Mt940Data {
213 pub fn new() -> Self {
215 Self::default()
216 }
217
218 pub fn as_bytes(&self) -> &[u8] {
220 self.0.as_slice()
221 }
222
223 pub fn is_empty(&self) -> bool {
225 self.as_bytes().is_empty()
226 }
227
228 pub fn extend(&mut self, page: Vec<u8>) {
232 self.0.extend_from_slice(&page);
233 }
234}
235
236#[derive(Clone)]
238pub struct Pin(String);
239
240impl Pin {
241 pub fn new(pin: impl Into<String>) -> Self {
242 Self(pin.into())
243 }
244
245 pub fn as_str(&self) -> &str {
247 self.0.as_str()
248 }
249}
250
251const HIDDEN: &str = "****";
252
253impl fmt::Debug for Pin {
254 fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
255 write!(out, "Pin({HIDDEN})")
256 }
257}
258
259impl fmt::Display for Pin {
260 fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
261 out.write_str(HIDDEN)
262 }
263}
264
265const NOT_YET_ASSIGNED: &str = "0";
271
272fn assigned(id: &str) -> bool {
273 !matches!(id, "" | NOT_YET_ASSIGNED)
274}
275
276impl SystemId {
277 pub fn unassigned() -> Self {
279 Self::new(NOT_YET_ASSIGNED)
280 }
281
282 pub fn is_assigned(&self) -> bool {
284 assigned(&self.0)
285 }
286}
287
288impl DialogId {
289 pub fn unassigned() -> Self {
291 Self::new(NOT_YET_ASSIGNED)
292 }
293
294 pub fn is_assigned(&self) -> bool {
296 assigned(&self.0)
297 }
298}
299
300impl SecurityFunction {
301 pub fn pin_only() -> Self {
303 Self::new("999")
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
309pub enum TanProcess {
310 OneStep,
312 TwoStep,
315}
316
317impl TanProcess {
318 pub fn from_str_val(code: &str) -> Self {
320 if code == "1" {
321 Self::OneStep
322 } else {
323 Self::TwoStep
324 }
325 }
326}
327
328pub(crate) fn read_str(seg: &RawSegment, deg: usize, de: usize) -> String {
332 seg.deg(deg).get_str(de)
333}
334
335pub(crate) fn read_opt_str(seg: &RawSegment, deg: usize, de: usize) -> Option<String> {
337 Some(read_str(seg, deg, de)).filter(|text| !text.is_empty())
338}
339
340#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct TanMethod {
345 pub security_function: SecurityFunction,
347 pub tan_process: TanProcess,
349 pub name: String,
351 pub needs_tan_medium: bool,
353 pub decoupled_max_polls: i32,
357 pub wait_before_first_poll: i32,
360 pub wait_before_next_poll: i32,
363 pub is_decoupled: bool,
365 pub hktan_version: u16,
368 pub zka_name: Option<String>,
371 pub decoupled_auto_polling: Option<bool>,
374 pub challenge_structured: bool,
377}
378
379#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
395pub enum AccountKey {
396 National {
398 blz: Blz,
399 number: String,
400 subaccount: Option<String>,
401 },
402 Iban {
405 iban: Iban,
406 subaccount: Option<String>,
407 },
408}
409
410impl AccountKey {
411 pub fn national(blz: &str, number: &str, subaccount: Option<&str>) -> Option<Self> {
413 let (blz, number) = (blz.trim(), number.trim());
414 if blz.is_empty() || number.is_empty() {
415 return None;
416 }
417 let stripped = number.trim_start_matches('0');
418 Some(Self::National {
419 blz: Blz::new(blz),
420 number: if stripped.is_empty() { "0" } else { stripped }.to_string(),
421 subaccount: normal_subaccount(subaccount),
422 })
423 }
424
425 pub fn iban(iban: &str, subaccount: Option<&str>) -> Option<Self> {
427 let iban: String = iban
428 .chars()
429 .filter(|c| !c.is_whitespace())
430 .collect::<String>()
431 .to_ascii_uppercase();
432 (!iban.is_empty()).then(|| Self::Iban {
433 iban: Iban::new(iban),
434 subaccount: normal_subaccount(subaccount),
435 })
436 }
437
438 pub fn subaccount(&self) -> Option<&str> {
440 match self {
441 Self::National { subaccount, .. } | Self::Iban { subaccount, .. } => {
442 subaccount.as_deref()
443 }
444 }
445 }
446}
447
448fn normal_subaccount(subaccount: Option<&str>) -> Option<String> {
449 subaccount
450 .map(str::trim)
451 .filter(|s| !s.is_empty())
452 .map(str::to_string)
453}
454
455const KEY_IBAN_PREFIX: &str = "iban:";
456
457fn key_escape(s: &str) -> String {
458 s.replace('%', "%25").replace('/', "%2F")
459}
460
461fn key_unescape(s: &str) -> String {
462 s.replace("%2F", "/")
463 .replace("%2f", "/")
464 .replace("%25", "%")
465}
466
467impl fmt::Display for AccountKey {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469 let subaccount = match self {
470 Self::National { blz, number, .. } => {
471 write!(f, "{}/{}", key_escape(blz.as_str()), key_escape(number))?;
472 self.subaccount()
473 }
474 Self::Iban { iban, .. } => {
475 write!(f, "{KEY_IBAN_PREFIX}{}", key_escape(iban.as_str()))?;
476 self.subaccount()
477 }
478 };
479 match subaccount {
480 Some(s) => write!(f, "/{s}"),
481 None => Ok(()),
482 }
483 }
484}
485
486#[derive(Debug, Clone, PartialEq, Eq)]
488pub struct AccountKeyError(String);
489
490impl fmt::Display for AccountKeyError {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 write!(f, "not an account key: {:?}", self.0)
493 }
494}
495
496impl std::error::Error for AccountKeyError {}
497
498impl std::str::FromStr for AccountKey {
499 type Err = AccountKeyError;
500
501 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
504 let err = || AccountKeyError(s.to_string());
505 let key = if let Some(rest) = s.strip_prefix(KEY_IBAN_PREFIX) {
506 let (iban, sub) = match rest.split_once('/') {
507 Some((iban, sub)) => (iban, Some(sub)),
508 None => (rest, None),
509 };
510 AccountKey::iban(&key_unescape(iban), sub)
511 } else {
512 let mut parts = s.splitn(3, '/');
513 let blz = parts.next().ok_or_else(err)?;
514 let number = parts.next().ok_or_else(err)?;
515 AccountKey::national(&key_unescape(blz), &key_unescape(number), parts.next())
516 };
517 key.filter(|k| k.to_string() == s).ok_or_else(err)
519 }
520}
521
522impl Serialize for AccountKey {
523 fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
524 s.collect_str(self)
525 }
526}
527
528impl<'de> Deserialize<'de> for AccountKey {
529 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
530 let s = String::deserialize(d)?;
531 s.parse().map_err(serde::de::Error::custom)
532 }
533}
534
535pub(crate) fn classify(
538 account_type: Option<u8>,
539 allows: impl Fn(&str) -> bool,
540) -> Option<(AccountClass, ClassSource)> {
541 if let Some(class) = account_type.and_then(AccountClass::from_account_type) {
542 return Some((class, ClassSource::Kontoart));
543 }
544 if allows("HKWPD") && !allows("HKSAL") && !allows("HKKAZ") && !allows("HKCAZ") {
545 return Some((AccountClass::Depot, ClassSource::AllowedJobs));
546 }
547 None
548}
549
550#[derive(Debug, Clone)]
554pub(crate) struct SepaAccount {
555 pub iban: Iban,
556 pub bic: Bic,
557 pub account_number: String,
558 pub sub_account: String,
559 pub blz: Blz,
560 pub owner: Option<String>,
561 pub product_name: Option<String>,
562 pub currency: Option<Currency>,
563 pub account_type: Option<u8>,
565 #[cfg_attr(not(any(test, feature = "trace")), allow(dead_code))]
569 pub allowed_jobs: Vec<String>,
570}
571
572impl SepaAccount {
573 #[cfg(any(test, feature = "trace"))]
575 pub(crate) fn classify(&self) -> Option<(AccountClass, ClassSource)> {
576 classify(self.account_type, |job| {
577 self.allowed_jobs.iter().any(|j| j == job)
578 })
579 }
580}
581
582#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
584pub enum ClassSource {
585 Kontoart,
587 AllowedJobs,
589}
590
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
595pub enum AccountClass {
596 Checking,
598 Savings,
600 FixedDeposit,
602 Depot,
604 Loan,
606 CreditCard,
608 FundDepot,
610 HomeSavings,
612 Insurance,
614 Other,
616}
617
618impl AccountClass {
619 const BY_TENS: [Self; 10] = [
621 Self::Checking,
622 Self::Savings,
623 Self::FixedDeposit,
624 Self::Depot,
625 Self::Loan,
626 Self::CreditCard,
627 Self::FundDepot,
628 Self::HomeSavings,
629 Self::Insurance,
630 Self::Other,
631 ];
632
633 pub fn from_account_type(account_type: u8) -> Option<Self> {
635 if !(1..=99).contains(&account_type) {
636 return None;
637 }
638 Some(Self::BY_TENS[usize::from(account_type / 10)])
639 }
640}
641
642#[derive(Debug, Clone, Serialize, Deserialize)]
644pub struct AccountBalance {
645 pub amount: Decimal,
646 pub date: Option<Date>,
648 pub currency: Currency,
650 pub credit_line: Option<Decimal>,
651 pub available: Option<Decimal>,
652 pub pending_amount: Option<Decimal>,
654 pub pending_date: Option<Date>,
656}
657
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
664pub struct BankTime {
665 pub datetime: jiff::civil::DateTime,
667 pub offset: Option<jiff::tz::Offset>,
669}
670
671impl BankTime {
672 pub fn timestamp(&self) -> Option<jiff::Timestamp> {
676 self.offset.and_then(|o| o.to_timestamp(self.datetime).ok())
677 }
678}
679
680#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub enum TransactionStatus {
683 Booked,
684 Pending,
685}
686
687text_type!(
690 Isin
692);
693text_type!(
694 Wkn
696);
697
698#[derive(Debug, Clone, Serialize, Deserialize)]
700pub struct SecurityHolding {
701 pub isin: Option<Isin>,
703 pub wkn: Option<Wkn>,
705 pub name: String,
707 pub quantity: Decimal,
709 pub price: Option<Decimal>,
711 pub price_currency: Option<Currency>,
713 pub price_date: Option<Date>,
715 pub market_value: Option<Decimal>,
717 pub market_value_currency: Option<Currency>,
719 pub acquisition_value: Option<Decimal>,
721 pub acquisition_date: Option<Date>,
724 pub acquisition_price: Option<Decimal>,
726 pub acquisition_price_currency: Option<Currency>,
728 pub profit_loss: Option<Decimal>,
730 pub exchange: Option<String>,
732 pub depot_id: Option<String>,
734 pub statement_date: Option<Date>,
737 pub raw: serde_json::Value,
739}
740
741#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
743pub enum DepotTransactionDirection {
744 Receive,
746 Deliver,
748 Unknown,
750}
751
752#[derive(Debug, Clone, Serialize, Deserialize)]
754pub struct DepotTransaction {
755 pub isin: Option<Isin>,
756 pub wkn: Option<Wkn>,
757 pub name: String,
759 pub quantity: Decimal,
761 pub amount: Option<Decimal>,
763 pub currency: Option<Currency>,
764 pub direction: DepotTransactionDirection,
765 pub transaction_type: Option<String>,
767 pub effective_date: Option<Date>,
769 pub trade_date: Option<Date>,
771 pub settlement_date: Option<Date>,
773 pub price: Option<Decimal>,
775 pub price_currency: Option<Currency>,
776 pub is_reversal: bool,
778 pub details: Option<String>,
780 pub depot_id: Option<String>,
782 pub raw: serde_json::Value,
784}
785
786#[derive(Debug, Clone, Serialize, Deserialize)]
793pub struct Transaction {
794 pub date: Date,
798 pub valuta_date: Option<Date>,
800 pub amount: Decimal,
802 pub currency: Currency,
803 pub applicant_name: Option<String>,
804 pub applicant_iban: Option<Iban>,
805 pub applicant_bic: Option<Bic>,
806 pub purpose: Option<String>,
812 pub posting_text: Option<String>,
814 pub customer_reference: Option<String>,
818 pub bank_reference: Option<String>,
822 pub booking_id: Option<String>,
834 pub gvc: Option<String>,
838 pub prima_nota: Option<String>,
840 pub purpose_code: Option<String>,
842 pub mandate_id: Option<String>,
845 pub end_to_end_id: Option<String>,
848 pub creditor_id: Option<String>,
851 pub debtor_id: Option<String>,
855 pub ultimate_debtor: Option<String>,
860 pub ultimate_creditor: Option<String>,
864 pub reversal: bool,
867 pub original_amount: Option<(Decimal, Currency)>,
871 pub fees: Option<(Decimal, Currency)>,
875 pub return_reason: Option<String>,
879 pub sequence_type: Option<String>,
882 pub raw: serde_json::Value,
883 pub status: TransactionStatus,
885}
886
887#[cfg(test)]
888mod tests {
889 use super::*;
890
891 #[test]
892 fn currency_to_minor() {
893 let d = |s: &str| s.parse::<Decimal>().unwrap();
894 let eur = Currency::new("EUR");
895 assert_eq!(eur.to_minor(d("12.34")), Some(1234));
896 assert_eq!(eur.to_minor(d("12.3400")), Some(1234));
897 assert_eq!(eur.to_minor(d("12.345")), None);
898 assert_eq!(eur.to_minor(d("-0.5")), Some(-50));
899 assert_eq!(Currency::new("JPY").to_minor(d("100")), Some(100));
900 assert_eq!(Currency::new("JPY").to_minor(d("1.5")), None);
901 assert_eq!(Currency::new("KWD").to_minor(d("1.234")), Some(1234));
902 assert_eq!(Currency::new("XYZ").to_minor(d("1.23")), Some(123));
903 assert_eq!(eur.to_minor(Decimal::MAX), None);
904 assert_eq!(eur.to_minor(d("92233720368547758.07")), Some(i64::MAX));
905 assert_eq!(eur.to_minor(d("92233720368547758.08")), None);
906 }
907
908 fn field(bytes: &[u8]) -> Vec<u8> {
910 let mut out = u16::try_from(bytes.len()).unwrap().to_be_bytes().to_vec();
911 out.extend_from_slice(bytes);
912 out
913 }
914
915 #[test]
916 fn matrix_code_gives_the_picture() {
917 let picture = b"\x89PNG-synthetic";
918 let challenge = [field(b"image/png"), field(picture)].concat();
919 let expected = TanMedia::Image {
920 mime_type: "image/png".to_owned(),
921 data: picture.to_vec(),
922 };
923 assert_eq!(HhdUcData(challenge).decode(), Some(expected));
924 }
925
926 #[test]
927 fn printable_challenge_is_a_flicker_code() {
928 let code = "0248A0120452019980812345678";
929 let decoded = HhdUcData(format!(" {code} ").into_bytes()).decode();
930 assert_eq!(decoded, Some(TanMedia::Flicker(code.to_owned())));
931 }
932
933 #[test]
934 fn short_or_unprintable_challenge_is_none() {
935 let mut cut_off = [field(b"image/png"), field(&[7; 40])].concat();
936 cut_off.truncate(cut_off.len() - 1);
937 for challenge in [cut_off, Vec::new(), vec![0x00, 0x01, 0xff]] {
938 assert_eq!(HhdUcData(challenge).decode(), None);
939 }
940 }
941
942 #[test]
943 fn kontoart_ranges() {
944 let class = AccountClass::from_account_type;
945 assert_eq!(class(1), Some(AccountClass::Checking));
946 assert_eq!(class(9), Some(AccountClass::Checking));
947 assert_eq!(class(10), Some(AccountClass::Savings));
948 assert_eq!(class(35), Some(AccountClass::Depot));
949 assert_eq!(class(99), Some(AccountClass::Other));
950 assert_eq!(class(0), None);
951 assert_eq!(class(100), None);
952 }
953
954 fn class(kontoart: Option<u8>, jobs: &[&str]) -> Option<(AccountClass, ClassSource)> {
955 classify(kontoart, |job| jobs.contains(&job))
956 }
957
958 #[test]
959 fn kontoart_wins_over_allowed_jobs() {
960 assert_eq!(
961 class(Some(1), &["HKWPD"]),
962 Some((AccountClass::Checking, ClassSource::Kontoart))
963 );
964 assert_eq!(
965 class(Some(30), &["HKSAL"]),
966 Some((AccountClass::Depot, ClassSource::Kontoart))
967 );
968 }
969
970 #[test]
971 fn no_kontoart_hkwpd_only_is_depot() {
972 assert_eq!(
973 class(None, &["HKWPD", "HKPRO"]),
974 Some((AccountClass::Depot, ClassSource::AllowedJobs))
975 );
976 }
977
978 #[test]
979 fn no_kontoart_hkwpd_with_account_jobs_is_not_depot() {
980 for other in ["HKSAL", "HKKAZ", "HKCAZ"] {
981 assert_eq!(class(None, &["HKWPD", other]), None, "{other}");
982 }
983 }
984
985 #[test]
986 fn nothing_known_is_unclassified() {
987 assert_eq!(class(None, &[]), None);
988 assert_eq!(class(None, &["HKSAL"]), None);
989 assert_eq!(class(Some(0), &[]), None);
991 assert_eq!(
992 class(Some(0), &["HKWPD"]),
993 Some((AccountClass::Depot, ClassSource::AllowedJobs))
994 );
995 }
996
997 #[test]
998 fn account_key_is_normalised() {
999 let k = AccountKey::national(" 12345678", "0000000301", Some("")).unwrap();
1000 assert_eq!(
1001 k,
1002 AccountKey::National {
1003 blz: Blz::new("12345678"),
1004 number: "301".into(),
1005 subaccount: None,
1006 }
1007 );
1008 assert_eq!(k, AccountKey::national("12345678", "301", None).unwrap());
1009 assert_eq!(
1010 AccountKey::national("12345678", "000", Some(" 01 ")).unwrap(),
1011 AccountKey::National {
1012 blz: Blz::new("12345678"),
1013 number: "0".into(),
1014 subaccount: Some("01".into()),
1015 }
1016 );
1017 assert_eq!(AccountKey::national("", "301", None), None);
1018 assert_eq!(AccountKey::national("12345678", " ", None), None);
1019 assert_eq!(
1020 AccountKey::iban("de00 1234 5678 0000 0003 01", Some("")).unwrap(),
1021 AccountKey::Iban {
1022 iban: Iban::new("DE00123456780000000301"),
1023 subaccount: None,
1024 }
1025 );
1026 assert_eq!(AccountKey::iban("", None), None);
1027 assert_ne!(
1029 k,
1030 AccountKey::national("12345678", "301", Some("01")).unwrap()
1031 );
1032 }
1033
1034 #[test]
1035 fn account_key_string_round_trips() {
1036 let keys = [
1037 (
1038 AccountKey::national("12345678", "0301", None),
1039 "12345678/301",
1040 ),
1041 (
1042 AccountKey::national("12345678", "301", Some("01")),
1043 "12345678/301/01",
1044 ),
1045 (
1046 AccountKey::national("12345678", "30/1", Some("A/B")),
1047 "12345678/30%2F1/A/B",
1048 ),
1049 (
1050 AccountKey::iban("DE00123456780000000301", None),
1051 "iban:DE00123456780000000301",
1052 ),
1053 (
1054 AccountKey::iban("DE00123456780000000301", Some("TOKEN/1")),
1055 "iban:DE00123456780000000301/TOKEN/1",
1056 ),
1057 ];
1058 for (key, text) in keys {
1059 let key = key.unwrap();
1060 assert_eq!(key.to_string(), text);
1061 assert_eq!(text.parse::<AccountKey>().unwrap(), key, "{text}");
1062 let json = serde_json::to_string(&key).unwrap();
1063 assert_eq!(json, format!("\"{text}\""));
1064 assert_eq!(serde_json::from_str::<AccountKey>(&json).unwrap(), key);
1065 }
1066 for bad in [
1067 "",
1068 "12345678",
1069 "12345678/",
1070 "/301",
1071 "12345678/0301",
1072 "12345678/301/",
1073 "iban:",
1074 "iban:de00",
1075 ] {
1076 assert!(bad.parse::<AccountKey>().is_err(), "{bad:?}");
1077 }
1078 }
1079
1080 #[test]
1081 fn account_classes() {
1082 assert_eq!(
1083 AccountClass::from_account_type(1),
1084 Some(AccountClass::Checking)
1085 );
1086 assert_eq!(
1087 AccountClass::from_account_type(10),
1088 Some(AccountClass::Savings)
1089 );
1090 assert_eq!(
1091 AccountClass::from_account_type(39),
1092 Some(AccountClass::Depot)
1093 );
1094 assert_eq!(
1095 AccountClass::from_account_type(55),
1096 Some(AccountClass::CreditCard)
1097 );
1098 assert_eq!(AccountClass::from_account_type(0), None);
1099 assert_eq!(
1100 AccountClass::from_account_type(9),
1101 Some(AccountClass::Checking)
1102 );
1103 assert_eq!(
1104 AccountClass::from_account_type(20),
1105 Some(AccountClass::FixedDeposit)
1106 );
1107 assert_eq!(
1108 AccountClass::from_account_type(49),
1109 Some(AccountClass::Loan)
1110 );
1111 assert_eq!(
1112 AccountClass::from_account_type(60),
1113 Some(AccountClass::FundDepot)
1114 );
1115 assert_eq!(
1116 AccountClass::from_account_type(79),
1117 Some(AccountClass::HomeSavings)
1118 );
1119 assert_eq!(
1120 AccountClass::from_account_type(89),
1121 Some(AccountClass::Insurance)
1122 );
1123 assert_eq!(
1124 AccountClass::from_account_type(99),
1125 Some(AccountClass::Other)
1126 );
1127 assert_eq!(AccountClass::from_account_type(100), None);
1128 }
1129}