use std::fmt;
use std::str::FromStr;
use jiff::civil::Date;
use crate::error::{Error, Result};
const ID_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DataBoxId(String);
impl DataBoxId {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
validate_id(&value)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for DataBoxId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for DataBoxId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl fmt::Debug for DataBoxId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, formatter)
}
}
impl FromStr for DataBoxId {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl TryFrom<&str> for DataBoxId {
type Error = Error;
fn try_from(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl TryFrom<String> for DataBoxId {
type Error = Error;
fn try_from(value: String) -> Result<Self> {
Self::new(value)
}
}
impl From<DataBoxId> for String {
fn from(id: DataBoxId) -> Self {
id.0
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for DataBoxId {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DataBoxId {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <String as serde::Deserialize>::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum DataBoxType {
NaturalPerson,
SelfEmployedPerson,
LegalEntity,
PublicAuthority,
Other(String),
}
impl DataBoxType {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if value.is_empty() {
return Err(Error::invalid_input(
"db_type",
"databox type must not be empty",
));
}
Ok(match value.as_str() {
"FO" => Self::NaturalPerson,
"PFO" => Self::SelfEmployedPerson,
"PO" => Self::LegalEntity,
"OVM" => Self::PublicAuthority,
_ => Self::Other(value),
})
}
pub fn as_str(&self) -> &str {
match self {
Self::NaturalPerson => "FO",
Self::SelfEmployedPerson => "PFO",
Self::LegalEntity => "PO",
Self::PublicAuthority => "OVM",
Self::Other(value) => value,
}
}
}
impl fmt::Display for DataBoxType {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for DataBoxType {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DataBox {
pub id: Option<DataBoxId>,
pub identified_in_population_register: Option<bool>,
pub box_type: Option<DataBoxType>,
pub identification_number: Option<String>,
pub given_names: Option<String>,
pub last_name: Option<String>,
pub firm_name: Option<String>,
pub birth_date: Option<Date>,
pub birth_city: Option<String>,
pub birth_county: Option<String>,
pub birth_state: Option<String>,
pub address_code: Option<String>,
pub address_city: Option<String>,
pub address_district: Option<String>,
pub address_street: Option<String>,
pub address_number_in_street: Option<String>,
pub address_number_in_municipality: Option<String>,
pub address_zip_code: Option<String>,
pub address_state: Option<String>,
pub nationality: Option<String>,
pub public_authority_id: Option<String>,
pub state: Option<i64>,
pub open_addressing: Option<bool>,
pub upper_id: Option<DataBoxId>,
}
impl DataBox {
pub fn by_id(id: DataBoxId) -> Self {
Self {
id: Some(id),
..Self::default()
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct DataBoxSearchResult {
pub boxes: Vec<DataBox>,
pub truncated: bool,
pub postal_delivery_restricted: bool,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct DataBoxState(i32);
impl DataBoxState {
pub(crate) fn from_code(code: i32) -> Self {
Self(code)
}
pub fn code(self) -> i32 {
self.0
}
pub fn is_active(self) -> bool {
self.0 == 1
}
}
fn validate_id(value: &str) -> Result<()> {
if value.len() != 7 || !value.is_ascii() {
return Err(Error::invalid_input(
"db_id",
"a databox ID must contain exactly seven ASCII characters",
));
}
let bytes = value.as_bytes();
if bytes.iter().any(|byte| !ID_ALPHABET.contains(byte)) {
return Err(Error::invalid_input(
"db_id",
"databox ID contains a character outside the ISDS alphabet",
));
}
let expected = check_character(&bytes[..6]);
if bytes[6] != expected {
return Err(Error::invalid_input(
"db_id",
"databox ID has an invalid Luhn32 check character",
));
}
Ok(())
}
fn check_character(data: &[u8]) -> u8 {
let sum = data.iter().enumerate().fold(0_u32, |sum, (index, byte)| {
let mut value = ID_ALPHABET.iter().position(|item| item == byte).unwrap() as u32;
if index % 2 == 1 {
value *= 2;
if value >= 32 {
value = value - 32 + 1;
}
}
sum + value
});
ID_ALPHABET[((32 - sum % 32) % 32) as usize]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_valid_ids() {
for id in ["egtk37z", "n94k37v", "djwk5ns"] {
assert_eq!(DataBoxId::new(id).unwrap().as_str(), id);
}
}
#[test]
fn rejects_invalid_checksum_and_characters() {
assert!(DataBoxId::new("egtk37x").is_err());
assert!(DataBoxId::new("EGTK37Z").is_err());
assert!(DataBoxId::new("egtk37").is_err());
assert!(DataBoxId::new("egtk37zz").is_err());
}
#[test]
fn preserves_unknown_state_codes() {
let state = DataBoxState::from_code(99);
assert_eq!(state.code(), 99);
assert!(!state.is_active());
}
#[test]
fn databox_type_maps_base_types_and_preserves_other_codes() {
for (raw, expected) in [
("FO", DataBoxType::NaturalPerson),
("PFO", DataBoxType::SelfEmployedPerson),
("PO", DataBoxType::LegalEntity),
("OVM", DataBoxType::PublicAuthority),
] {
let value = DataBoxType::new(raw).unwrap();
assert_eq!(value, expected);
assert_eq!(value.as_str(), raw);
}
for raw in ["PFO_ADVOK", "OVM_NOTAR", "FUTURE_TYPE"] {
let value = DataBoxType::new(raw).unwrap();
assert_eq!(value, DataBoxType::Other(raw.to_owned()));
assert_eq!(value.as_str(), raw);
}
assert!(DataBoxType::new("").is_err());
}
}