149 lines
5.1 KiB
Rust
149 lines
5.1 KiB
Rust
//! QR Platba: a checked Czech IBAN and the SPAYD 1.0 string a banking app scans.
|
|
|
|
use crate::money::Haler;
|
|
use std::fmt;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
|
pub enum PayError {
|
|
#[error("not a valid Czech account number or IBAN")]
|
|
Account,
|
|
#[error("the amount must be between 0,01 and 9 999 999,99 CZK")]
|
|
Amount,
|
|
#[error("a variable symbol is 1-10 digits")]
|
|
VariableSymbol,
|
|
#[error("a text has control characters")]
|
|
Text,
|
|
}
|
|
|
|
/// A Czech IBAN (`CZ` + 22 digits) whose check digits are right.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct Iban(String);
|
|
|
|
/// The largest amount QR Platba carries: 9 999 999,99 CZK.
|
|
pub const MAX_AMOUNT: Haler = Haler(999_999_999);
|
|
|
|
/// The remainder mod 97 of a string of digits and letters (A = 10 … Z = 35), as IBAN check digits use.
|
|
fn mod97(s: &str) -> Option<u32> {
|
|
let mut r: u32 = 0;
|
|
for c in s.chars() {
|
|
let v = c.to_digit(36)?;
|
|
r = if v < 10 { (r * 10 + v) % 97 } else { (r * 100 + v) % 97 };
|
|
}
|
|
Some(r)
|
|
}
|
|
|
|
/// The Czech weighted mod-11 check of an account prefix or number, right-aligned to the weights.
|
|
fn mod11(digits: &str, weights: &[u32]) -> bool {
|
|
if digits.len() > weights.len() {
|
|
return false;
|
|
}
|
|
let pad = weights.len() - digits.len();
|
|
let sum: u32 = digits.bytes().enumerate().map(|(i, b)| u32::from(b - b'0') * weights[pad + i]).sum();
|
|
sum.is_multiple_of(11)
|
|
}
|
|
|
|
const PREFIX_WEIGHTS: [u32; 6] = [10, 5, 8, 4, 2, 1];
|
|
const NUMBER_WEIGHTS: [u32; 10] = [6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
|
|
|
|
fn all_digits(s: &str) -> bool {
|
|
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
|
|
}
|
|
|
|
impl Iban {
|
|
/// `CZ65 0800 0000 1920 0014 5399` (spaces and case do not matter) or a Czech account
|
|
/// `[prefix-]number/bank` such as `19-2000145399/0800`.
|
|
pub fn parse(text: &str) -> Result<Iban, PayError> {
|
|
let t = text.trim();
|
|
if let Some((account, bank)) = t.split_once('/') {
|
|
return Iban::from_czech(account.trim(), bank.trim());
|
|
}
|
|
let compact: String = t.chars().filter(|c| *c != ' ').collect::<String>().to_ascii_uppercase();
|
|
if compact.len() != 24 || !compact.starts_with("CZ") || !all_digits(&compact[2..]) {
|
|
return Err(PayError::Account);
|
|
}
|
|
let rearranged = format!("{}{}", &compact[4..], &compact[..4]);
|
|
if mod97(&rearranged) != Some(1) {
|
|
return Err(PayError::Account);
|
|
}
|
|
// The BBAN inside must itself be a valid Czech account.
|
|
let (prefix, number) = (&compact[8..14], &compact[14..]);
|
|
if !mod11(prefix, &PREFIX_WEIGHTS) || !mod11(number, &NUMBER_WEIGHTS) {
|
|
return Err(PayError::Account);
|
|
}
|
|
Ok(Iban(compact))
|
|
}
|
|
|
|
fn from_czech(account: &str, bank: &str) -> Result<Iban, PayError> {
|
|
let (prefix, number) = account.split_once('-').unwrap_or(("", account));
|
|
let ok = (prefix.is_empty() || (all_digits(prefix) && prefix.len() <= 6))
|
|
&& all_digits(number)
|
|
&& (2..=10).contains(&number.len())
|
|
&& bank.len() == 4
|
|
&& all_digits(bank)
|
|
&& mod11(prefix, &PREFIX_WEIGHTS)
|
|
&& mod11(number, &NUMBER_WEIGHTS);
|
|
if !ok {
|
|
return Err(PayError::Account);
|
|
}
|
|
let bban = format!("{bank}{prefix:0>6}{number:0>10}");
|
|
let check = 98 - mod97(&format!("{bban}CZ00")).ok_or(PayError::Account)?;
|
|
Iban::parse(&format!("CZ{check:02}{bban}"))
|
|
}
|
|
|
|
pub fn as_str(&self) -> &str {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Iban {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str(&self.0)
|
|
}
|
|
}
|
|
|
|
/// A SPAYD text value: `*` written as `%2A`, cut to `max` characters without splitting an escape.
|
|
fn text(value: &str, max: usize) -> Result<String, PayError> {
|
|
if value.chars().any(|c| c.is_control()) {
|
|
return Err(PayError::Text);
|
|
}
|
|
let mut out = String::new();
|
|
let mut count = 0;
|
|
for c in value.trim().chars() {
|
|
let piece = if c == '*' { "%2A".to_string() } else { c.to_string() };
|
|
let n = piece.chars().count();
|
|
if count + n > max {
|
|
break;
|
|
}
|
|
out.push_str(&piece);
|
|
count += n;
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// `SPD*1.0*ACC:<IBAN>*AM:<amount>*CC:CZK[*RN:<name>]*MSG:<message>[*X-VS:<vs>]`.
|
|
/// The amount is positive and written from haléře (`450.00`); the name is cut to 35 characters and the
|
|
/// message to 60.
|
|
pub fn spayd(iban: &Iban, amount: Haler, name: Option<&str>, message: &str, vs: Option<&str>) -> Result<String, PayError> {
|
|
if amount.0 <= 0 || amount > MAX_AMOUNT {
|
|
return Err(PayError::Amount);
|
|
}
|
|
let mut s = format!("SPD*1.0*ACC:{}*AM:{}.{:02}*CC:CZK", iban.0, amount.0 / 100, amount.0 % 100);
|
|
if let Some(name) = name {
|
|
let rn = text(name, 35)?;
|
|
if !rn.is_empty() {
|
|
s.push_str(&format!("*RN:{rn}"));
|
|
}
|
|
}
|
|
let msg = text(message, 60)?;
|
|
if !msg.is_empty() {
|
|
s.push_str(&format!("*MSG:{msg}"));
|
|
}
|
|
if let Some(vs) = vs {
|
|
if !all_digits(vs) || vs.len() > 10 {
|
|
return Err(PayError::VariableSymbol);
|
|
}
|
|
s.push_str(&format!("*X-VS:{vs}"));
|
|
}
|
|
Ok(s)
|
|
}
|