use jiff::civil::Date;
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::parser::RawSegment;
macro_rules! text_type {
($(#[$doc:meta])* $ty:ident) => {
$(#[$doc])*
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct $ty(String);
impl $ty {
pub fn new(text: impl Into<String>) -> Self {
Self(text.into())
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl fmt::Display for $ty {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.0.as_str(), out)
}
}
impl AsRef<str> for $ty {
fn as_ref(&self) -> &str {
self.as_str()
}
}
};
}
text_type!(
Blz
);
text_type!(
UserId
);
text_type!(
SystemId
);
text_type!(
ProductId
);
text_type!(
DialogId
);
text_type!(
SecurityFunction
);
text_type!(
TaskReference
);
text_type!(
SegmentType
);
text_type!(
TanMediumName
);
text_type!(
TouchdownPoint
);
text_type!(
SegmentRef
);
text_type!(
Currency
);
impl Currency {
pub fn exponent(&self) -> u32 {
match self.0.to_ascii_uppercase().as_str() {
"BIF" | "CLP" | "DJF" | "GNF" | "ISK" | "JPY" | "KMF" | "KRW" | "PYG" | "RWF"
| "UGX" | "UYI" | "VND" | "VUV" | "XAF" | "XOF" | "XPF" => 0,
"BHD" | "IQD" | "JOD" | "KWD" | "LYD" | "OMR" | "TND" => 3,
_ => 2,
}
}
pub fn to_minor(&self, amount: Decimal) -> Option<i64> {
let amount = amount.normalize();
let exponent = self.exponent();
if amount.scale() > exponent {
return None;
}
let minor = amount.checked_mul(Decimal::from(10_i64.pow(exponent)))?;
minor.to_i64()
}
}
text_type!(
Iban
);
text_type!(
Bic
);
text_type!(
BankName
);
text_type!(
FinTSUrl
);
text_type!(
ChallengeText
);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HhdUcData(pub Vec<u8>);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TanMedia {
Image { mime_type: String, data: Vec<u8> },
Flicker(String),
}
impl HhdUcData {
pub fn decode(&self) -> Option<TanMedia> {
let bytes = &self.0[..];
matrix_code(bytes).or_else(|| flicker_code(bytes))
}
}
fn length_prefixed(input: &[u8]) -> Option<(&[u8], &[u8])> {
let (len, rest) = input.split_first_chunk::<2>()?;
let len = usize::from(u16::from_be_bytes(*len));
(rest.len() >= len).then(|| rest.split_at(len))
}
fn matrix_code(bytes: &[u8]) -> Option<TanMedia> {
let (media_type, rest) = length_prefixed(bytes)?;
let plausible = matches!(media_type.len(), 3..=100)
&& media_type.iter().all(u8::is_ascii_graphic)
&& media_type.contains(&b'/');
if !plausible {
return None;
}
let (picture, _) = length_prefixed(rest)?;
Some(TanMedia::Image {
mime_type: String::from_utf8_lossy(media_type).into_owned(),
data: picture.to_vec(),
})
}
fn flicker_code(bytes: &[u8]) -> Option<TanMedia> {
if bytes.is_empty() || bytes.iter().any(|b| !(b' '..=b'~').contains(b)) {
return None;
}
let text = std::str::from_utf8(bytes).ok()?;
Some(TanMedia::Flicker(text.trim().to_owned()))
}
#[derive(Debug, Clone, Default)]
pub struct Mt940Data(pub Vec<u8>);
impl Mt940Data {
pub fn new() -> Self {
Self::default()
}
pub fn as_bytes(&self) -> &[u8] {
self.0.as_slice()
}
pub fn is_empty(&self) -> bool {
self.as_bytes().is_empty()
}
pub fn extend(&mut self, page: Vec<u8>) {
self.0.extend_from_slice(&page);
}
}
#[derive(Clone)]
pub struct Pin(String);
impl Pin {
pub fn new(pin: impl Into<String>) -> Self {
Self(pin.into())
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
const HIDDEN: &str = "****";
impl fmt::Debug for Pin {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(out, "Pin({HIDDEN})")
}
}
impl fmt::Display for Pin {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
out.write_str(HIDDEN)
}
}
const NOT_YET_ASSIGNED: &str = "0";
fn assigned(id: &str) -> bool {
!matches!(id, "" | NOT_YET_ASSIGNED)
}
impl SystemId {
pub fn unassigned() -> Self {
Self::new(NOT_YET_ASSIGNED)
}
pub fn is_assigned(&self) -> bool {
assigned(&self.0)
}
}
impl DialogId {
pub fn unassigned() -> Self {
Self::new(NOT_YET_ASSIGNED)
}
pub fn is_assigned(&self) -> bool {
assigned(&self.0)
}
}
impl SecurityFunction {
pub fn pin_only() -> Self {
Self::new("999")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TanProcess {
OneStep,
TwoStep,
}
impl TanProcess {
pub fn from_str_val(code: &str) -> Self {
if code == "1" {
Self::OneStep
} else {
Self::TwoStep
}
}
}
pub(crate) fn read_str(seg: &RawSegment, deg: usize, de: usize) -> String {
seg.deg(deg).get_str(de)
}
pub(crate) fn read_opt_str(seg: &RawSegment, deg: usize, de: usize) -> Option<String> {
Some(read_str(seg, deg, de)).filter(|text| !text.is_empty())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TanMethod {
pub security_function: SecurityFunction,
pub tan_process: TanProcess,
pub name: String,
pub needs_tan_medium: bool,
pub decoupled_max_polls: i32,
pub wait_before_first_poll: i32,
pub wait_before_next_poll: i32,
pub is_decoupled: bool,
pub hktan_version: u16,
pub zka_name: Option<String>,
pub decoupled_auto_polling: Option<bool>,
pub challenge_structured: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AccountKey {
National {
blz: Blz,
number: String,
subaccount: Option<String>,
},
Iban {
iban: Iban,
subaccount: Option<String>,
},
}
impl AccountKey {
pub fn national(blz: &str, number: &str, subaccount: Option<&str>) -> Option<Self> {
let (blz, number) = (blz.trim(), number.trim());
if blz.is_empty() || number.is_empty() {
return None;
}
let stripped = number.trim_start_matches('0');
Some(Self::National {
blz: Blz::new(blz),
number: if stripped.is_empty() { "0" } else { stripped }.to_string(),
subaccount: normal_subaccount(subaccount),
})
}
pub fn iban(iban: &str, subaccount: Option<&str>) -> Option<Self> {
let iban: String = iban
.chars()
.filter(|c| !c.is_whitespace())
.collect::<String>()
.to_ascii_uppercase();
(!iban.is_empty()).then(|| Self::Iban {
iban: Iban::new(iban),
subaccount: normal_subaccount(subaccount),
})
}
pub fn subaccount(&self) -> Option<&str> {
match self {
Self::National { subaccount, .. } | Self::Iban { subaccount, .. } => {
subaccount.as_deref()
}
}
}
}
fn normal_subaccount(subaccount: Option<&str>) -> Option<String> {
subaccount
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
const KEY_IBAN_PREFIX: &str = "iban:";
fn key_escape(s: &str) -> String {
s.replace('%', "%25").replace('/', "%2F")
}
fn key_unescape(s: &str) -> String {
s.replace("%2F", "/")
.replace("%2f", "/")
.replace("%25", "%")
}
impl fmt::Display for AccountKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let subaccount = match self {
Self::National { blz, number, .. } => {
write!(f, "{}/{}", key_escape(blz.as_str()), key_escape(number))?;
self.subaccount()
}
Self::Iban { iban, .. } => {
write!(f, "{KEY_IBAN_PREFIX}{}", key_escape(iban.as_str()))?;
self.subaccount()
}
};
match subaccount {
Some(s) => write!(f, "/{s}"),
None => Ok(()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountKeyError(String);
impl fmt::Display for AccountKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "not an account key: {:?}", self.0)
}
}
impl std::error::Error for AccountKeyError {}
impl std::str::FromStr for AccountKey {
type Err = AccountKeyError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let err = || AccountKeyError(s.to_string());
let key = if let Some(rest) = s.strip_prefix(KEY_IBAN_PREFIX) {
let (iban, sub) = match rest.split_once('/') {
Some((iban, sub)) => (iban, Some(sub)),
None => (rest, None),
};
AccountKey::iban(&key_unescape(iban), sub)
} else {
let mut parts = s.splitn(3, '/');
let blz = parts.next().ok_or_else(err)?;
let number = parts.next().ok_or_else(err)?;
AccountKey::national(&key_unescape(blz), &key_unescape(number), parts.next())
};
key.filter(|k| k.to_string() == s).ok_or_else(err)
}
}
impl Serialize for AccountKey {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for AccountKey {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
pub(crate) fn classify(
account_type: Option<u8>,
allows: impl Fn(&str) -> bool,
) -> Option<(AccountClass, ClassSource)> {
if let Some(class) = account_type.and_then(AccountClass::from_account_type) {
return Some((class, ClassSource::Kontoart));
}
if allows("HKWPD") && !allows("HKSAL") && !allows("HKKAZ") && !allows("HKCAZ") {
return Some((AccountClass::Depot, ClassSource::AllowedJobs));
}
None
}
#[derive(Debug, Clone)]
pub(crate) struct SepaAccount {
pub iban: Iban,
pub bic: Bic,
pub account_number: String,
pub sub_account: String,
pub blz: Blz,
pub owner: Option<String>,
pub product_name: Option<String>,
pub currency: Option<Currency>,
pub account_type: Option<u8>,
#[cfg_attr(not(any(test, feature = "trace")), allow(dead_code))]
pub allowed_jobs: Vec<String>,
}
impl SepaAccount {
#[cfg(any(test, feature = "trace"))]
pub(crate) fn classify(&self) -> Option<(AccountClass, ClassSource)> {
classify(self.account_type, |job| {
self.allowed_jobs.iter().any(|j| j == job)
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClassSource {
Kontoart,
AllowedJobs,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccountClass {
Checking,
Savings,
FixedDeposit,
Depot,
Loan,
CreditCard,
FundDepot,
HomeSavings,
Insurance,
Other,
}
impl AccountClass {
const BY_TENS: [Self; 10] = [
Self::Checking,
Self::Savings,
Self::FixedDeposit,
Self::Depot,
Self::Loan,
Self::CreditCard,
Self::FundDepot,
Self::HomeSavings,
Self::Insurance,
Self::Other,
];
pub fn from_account_type(account_type: u8) -> Option<Self> {
if !(1..=99).contains(&account_type) {
return None;
}
Some(Self::BY_TENS[usize::from(account_type / 10)])
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountBalance {
pub amount: Decimal,
pub date: Option<Date>,
pub currency: Currency,
pub credit_line: Option<Decimal>,
pub available: Option<Decimal>,
pub pending_amount: Option<Decimal>,
pub pending_date: Option<Date>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BankTime {
pub datetime: jiff::civil::DateTime,
pub offset: Option<jiff::tz::Offset>,
}
impl BankTime {
pub fn timestamp(&self) -> Option<jiff::Timestamp> {
self.offset.and_then(|o| o.to_timestamp(self.datetime).ok())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionStatus {
Booked,
Pending,
}
text_type!(
Isin
);
text_type!(
Wkn
);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityHolding {
pub isin: Option<Isin>,
pub wkn: Option<Wkn>,
pub name: String,
pub quantity: Decimal,
pub price: Option<Decimal>,
pub price_currency: Option<Currency>,
pub price_date: Option<Date>,
pub market_value: Option<Decimal>,
pub market_value_currency: Option<Currency>,
pub acquisition_value: Option<Decimal>,
pub acquisition_date: Option<Date>,
pub acquisition_price: Option<Decimal>,
pub acquisition_price_currency: Option<Currency>,
pub profit_loss: Option<Decimal>,
pub exchange: Option<String>,
pub depot_id: Option<String>,
pub statement_date: Option<Date>,
pub raw: serde_json::Value,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DepotTransactionDirection {
Receive,
Deliver,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepotTransaction {
pub isin: Option<Isin>,
pub wkn: Option<Wkn>,
pub name: String,
pub quantity: Decimal,
pub amount: Option<Decimal>,
pub currency: Option<Currency>,
pub direction: DepotTransactionDirection,
pub transaction_type: Option<String>,
pub effective_date: Option<Date>,
pub trade_date: Option<Date>,
pub settlement_date: Option<Date>,
pub price: Option<Decimal>,
pub price_currency: Option<Currency>,
pub is_reversal: bool,
pub details: Option<String>,
pub depot_id: Option<String>,
pub raw: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transaction {
pub date: Date,
pub valuta_date: Option<Date>,
pub amount: Decimal,
pub currency: Currency,
pub applicant_name: Option<String>,
pub applicant_iban: Option<Iban>,
pub applicant_bic: Option<Bic>,
pub purpose: Option<String>,
pub posting_text: Option<String>,
pub customer_reference: Option<String>,
pub bank_reference: Option<String>,
pub booking_id: Option<String>,
pub gvc: Option<String>,
pub prima_nota: Option<String>,
pub purpose_code: Option<String>,
pub mandate_id: Option<String>,
pub end_to_end_id: Option<String>,
pub creditor_id: Option<String>,
pub debtor_id: Option<String>,
pub ultimate_debtor: Option<String>,
pub ultimate_creditor: Option<String>,
pub reversal: bool,
pub original_amount: Option<(Decimal, Currency)>,
pub fees: Option<(Decimal, Currency)>,
pub return_reason: Option<String>,
pub sequence_type: Option<String>,
pub raw: serde_json::Value,
pub status: TransactionStatus,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn currency_to_minor() {
let d = |s: &str| s.parse::<Decimal>().unwrap();
let eur = Currency::new("EUR");
assert_eq!(eur.to_minor(d("12.34")), Some(1234));
assert_eq!(eur.to_minor(d("12.3400")), Some(1234));
assert_eq!(eur.to_minor(d("12.345")), None);
assert_eq!(eur.to_minor(d("-0.5")), Some(-50));
assert_eq!(Currency::new("JPY").to_minor(d("100")), Some(100));
assert_eq!(Currency::new("JPY").to_minor(d("1.5")), None);
assert_eq!(Currency::new("KWD").to_minor(d("1.234")), Some(1234));
assert_eq!(Currency::new("XYZ").to_minor(d("1.23")), Some(123));
assert_eq!(eur.to_minor(Decimal::MAX), None);
assert_eq!(eur.to_minor(d("92233720368547758.07")), Some(i64::MAX));
assert_eq!(eur.to_minor(d("92233720368547758.08")), None);
}
fn field(bytes: &[u8]) -> Vec<u8> {
let mut out = u16::try_from(bytes.len()).unwrap().to_be_bytes().to_vec();
out.extend_from_slice(bytes);
out
}
#[test]
fn matrix_code_gives_the_picture() {
let picture = b"\x89PNG-synthetic";
let challenge = [field(b"image/png"), field(picture)].concat();
let expected = TanMedia::Image {
mime_type: "image/png".to_owned(),
data: picture.to_vec(),
};
assert_eq!(HhdUcData(challenge).decode(), Some(expected));
}
#[test]
fn printable_challenge_is_a_flicker_code() {
let code = "0248A0120452019980812345678";
let decoded = HhdUcData(format!(" {code} ").into_bytes()).decode();
assert_eq!(decoded, Some(TanMedia::Flicker(code.to_owned())));
}
#[test]
fn short_or_unprintable_challenge_is_none() {
let mut cut_off = [field(b"image/png"), field(&[7; 40])].concat();
cut_off.truncate(cut_off.len() - 1);
for challenge in [cut_off, Vec::new(), vec![0x00, 0x01, 0xff]] {
assert_eq!(HhdUcData(challenge).decode(), None);
}
}
#[test]
fn kontoart_ranges() {
let class = AccountClass::from_account_type;
assert_eq!(class(1), Some(AccountClass::Checking));
assert_eq!(class(9), Some(AccountClass::Checking));
assert_eq!(class(10), Some(AccountClass::Savings));
assert_eq!(class(35), Some(AccountClass::Depot));
assert_eq!(class(99), Some(AccountClass::Other));
assert_eq!(class(0), None);
assert_eq!(class(100), None);
}
fn class(kontoart: Option<u8>, jobs: &[&str]) -> Option<(AccountClass, ClassSource)> {
classify(kontoart, |job| jobs.contains(&job))
}
#[test]
fn kontoart_wins_over_allowed_jobs() {
assert_eq!(
class(Some(1), &["HKWPD"]),
Some((AccountClass::Checking, ClassSource::Kontoart))
);
assert_eq!(
class(Some(30), &["HKSAL"]),
Some((AccountClass::Depot, ClassSource::Kontoart))
);
}
#[test]
fn no_kontoart_hkwpd_only_is_depot() {
assert_eq!(
class(None, &["HKWPD", "HKPRO"]),
Some((AccountClass::Depot, ClassSource::AllowedJobs))
);
}
#[test]
fn no_kontoart_hkwpd_with_account_jobs_is_not_depot() {
for other in ["HKSAL", "HKKAZ", "HKCAZ"] {
assert_eq!(class(None, &["HKWPD", other]), None, "{other}");
}
}
#[test]
fn nothing_known_is_unclassified() {
assert_eq!(class(None, &[]), None);
assert_eq!(class(None, &["HKSAL"]), None);
assert_eq!(class(Some(0), &[]), None);
assert_eq!(
class(Some(0), &["HKWPD"]),
Some((AccountClass::Depot, ClassSource::AllowedJobs))
);
}
#[test]
fn account_key_is_normalised() {
let k = AccountKey::national(" 12345678", "0000000301", Some("")).unwrap();
assert_eq!(
k,
AccountKey::National {
blz: Blz::new("12345678"),
number: "301".into(),
subaccount: None,
}
);
assert_eq!(k, AccountKey::national("12345678", "301", None).unwrap());
assert_eq!(
AccountKey::national("12345678", "000", Some(" 01 ")).unwrap(),
AccountKey::National {
blz: Blz::new("12345678"),
number: "0".into(),
subaccount: Some("01".into()),
}
);
assert_eq!(AccountKey::national("", "301", None), None);
assert_eq!(AccountKey::national("12345678", " ", None), None);
assert_eq!(
AccountKey::iban("de00 1234 5678 0000 0003 01", Some("")).unwrap(),
AccountKey::Iban {
iban: Iban::new("DE00123456780000000301"),
subaccount: None,
}
);
assert_eq!(AccountKey::iban("", None), None);
assert_ne!(
k,
AccountKey::national("12345678", "301", Some("01")).unwrap()
);
}
#[test]
fn account_key_string_round_trips() {
let keys = [
(
AccountKey::national("12345678", "0301", None),
"12345678/301",
),
(
AccountKey::national("12345678", "301", Some("01")),
"12345678/301/01",
),
(
AccountKey::national("12345678", "30/1", Some("A/B")),
"12345678/30%2F1/A/B",
),
(
AccountKey::iban("DE00123456780000000301", None),
"iban:DE00123456780000000301",
),
(
AccountKey::iban("DE00123456780000000301", Some("TOKEN/1")),
"iban:DE00123456780000000301/TOKEN/1",
),
];
for (key, text) in keys {
let key = key.unwrap();
assert_eq!(key.to_string(), text);
assert_eq!(text.parse::<AccountKey>().unwrap(), key, "{text}");
let json = serde_json::to_string(&key).unwrap();
assert_eq!(json, format!("\"{text}\""));
assert_eq!(serde_json::from_str::<AccountKey>(&json).unwrap(), key);
}
for bad in [
"",
"12345678",
"12345678/",
"/301",
"12345678/0301",
"12345678/301/",
"iban:",
"iban:de00",
] {
assert!(bad.parse::<AccountKey>().is_err(), "{bad:?}");
}
}
#[test]
fn account_classes() {
assert_eq!(
AccountClass::from_account_type(1),
Some(AccountClass::Checking)
);
assert_eq!(
AccountClass::from_account_type(10),
Some(AccountClass::Savings)
);
assert_eq!(
AccountClass::from_account_type(39),
Some(AccountClass::Depot)
);
assert_eq!(
AccountClass::from_account_type(55),
Some(AccountClass::CreditCard)
);
assert_eq!(AccountClass::from_account_type(0), None);
assert_eq!(
AccountClass::from_account_type(9),
Some(AccountClass::Checking)
);
assert_eq!(
AccountClass::from_account_type(20),
Some(AccountClass::FixedDeposit)
);
assert_eq!(
AccountClass::from_account_type(49),
Some(AccountClass::Loan)
);
assert_eq!(
AccountClass::from_account_type(60),
Some(AccountClass::FundDepot)
);
assert_eq!(
AccountClass::from_account_type(79),
Some(AccountClass::HomeSavings)
);
assert_eq!(
AccountClass::from_account_type(89),
Some(AccountClass::Insurance)
);
assert_eq!(
AccountClass::from_account_type(99),
Some(AccountClass::Other)
);
assert_eq!(AccountClass::from_account_type(100), None);
}
}