use std::fmt;
use std::str::FromStr;
use super::common::{
MessageCode, ServiceMessage, XmlDateTime, positive_integer_digits, valid_xml_date,
};
pub(crate) use super::common::{trim_xml_whitespace, unsigned_integer_digits};
use super::id::{
BuildingId, BuildingRightId, CadastralAreaCode, CompanyId, DocumentId, MunicipalityPartCode,
OwnershipId, OwnershipSheetId, ParcelId, ParcelNumber, PersonalIdentifier, ProceedingId,
SubjectId, UnitId, WorkplaceCode,
};
use crate::{Error, Result};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct XmlDate(String);
impl XmlDate {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if valid_xml_date(trim_xml_whitespace(&value)) {
Ok(Self(value))
} else {
Err(Error::invalid_input(
"date",
"expected an XML date with an optional offset",
))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for XmlDate {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for XmlDate {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct BuildingTypeCode(String);
impl BuildingTypeCode {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
let valid = positive_integer_digits(&value).is_some_and(|digits| {
matches!(digits.trim_start_matches('0').as_bytes(), [b'1'..=b'9'])
});
if valid {
Ok(Self(value))
} else {
Err(Error::invalid_input(
"building_type",
"expected a decimal building-type code in 1..=9",
))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for BuildingTypeCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for BuildingTypeCode {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BuildingTypeCode {
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)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct FractionComponent(String);
impl FractionComponent {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
let Some(digits) = positive_integer_digits(&value) else {
return Err(Error::invalid_input(
"fraction_component",
"expected a positive decimal integer with at most 30 digits",
));
};
if digits.len() > 30 {
return Err(Error::invalid_input(
"fraction_component",
"expected a positive decimal integer with at most 30 digits",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for FractionComponent {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for FractionComponent {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for FractionComponent {
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, Eq, Hash, PartialEq)]
pub struct ShortPersonalIdentifier(String);
impl ShortPersonalIdentifier {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if !(1..=10).contains(&value.chars().count()) {
return Err(Error::invalid_input(
"short_personal_identifier",
"expected between 1 and 10 characters",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ShortPersonalIdentifier {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ShortPersonalIdentifier([REDACTED])")
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ParcelKind {
Cadastral,
Simplified,
Other(String),
}
impl ParcelKind {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"PKN" => Self::Cadastral,
"PZE" => Self::Simplified,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Cadastral => "PKN",
Self::Simplified => "PZE",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ParcelNumberingKind {
One,
Two,
Other(String),
}
impl ParcelNumberingKind {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"1" => Self::One,
"2" => Self::Two,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::One => "1",
Self::Two => "2",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum YesNo {
Yes,
No,
Other(String),
}
impl YesNo {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"a" => Self::Yes,
"n" => Self::No,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Yes => "a",
Self::No => "n",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum BuildingAttachment {
BuildingRight,
Parcel,
Other(String),
}
impl BuildingAttachment {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"R" => Self::BuildingRight,
"P" => Self::Parcel,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::BuildingRight => "R",
Self::Parcel => "P",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SubjectKind {
NaturalPerson,
LegalPerson,
Partnership,
Other(String),
}
impl SubjectKind {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"OFO" => Self::NaturalPerson,
"OPO" => Self::LegalPerson,
"BSM" => Self::Partnership,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::NaturalPerson => "OFO",
Self::LegalPerson => "OPO",
Self::Partnership => "BSM",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum AddressNumberKind {
Descriptive,
Evidentiary,
Other(String),
}
impl AddressNumberKind {
pub(crate) fn from_raw(raw: String) -> Self {
match raw.as_str() {
"1" => Self::Descriptive,
"2" => Self::Evidentiary,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Descriptive => "1",
Self::Evidentiary => "2",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CadastralAreaReference {
pub code: Option<CadastralAreaCode>,
pub name: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MunicipalityPartReference {
pub code: MunicipalityPartCode,
pub name: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelIdentity {
pub id: ParcelId,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub cadastral_area: CadastralAreaCode,
pub root_number: u32,
pub kind: ParcelKind,
pub numbering_kind: ParcelNumberingKind,
pub subdivision: Option<u16>,
pub original_cadastral_area: Option<CadastralAreaCode>,
pub simplified_registration_kind: Option<String>,
pub part: Option<u16>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingLocation {
Address {
municipality_part: MunicipalityPartCode,
house_number: String,
},
Parcel(ParcelIdentity),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingIdentity {
pub id: BuildingId,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub building_type: BuildingTypeCode,
pub location: BuildingLocation,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightIdentity {
pub id: BuildingRightId,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub identifying_parcel: ParcelIdentity,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Parcel {
pub id: ParcelId,
pub kind: ParcelKind,
pub cadastral_area: CadastralAreaCode,
pub original_cadastral_area: Option<CadastralAreaCode>,
pub root_number: u32,
pub subdivision: Option<u16>,
pub part: Option<u16>,
pub area_determination_code: Option<String>,
pub simplified_registration_kind: Option<String>,
pub land_type_code: Option<String>,
pub land_use_code: Option<String>,
pub parcel_type_code: Option<String>,
pub area: u32,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub numbering_kind: ParcelNumberingKind,
pub building: Option<BuildingIdentity>,
pub building_is_part: YesNo,
pub building_right: Option<BuildingRightIdentity>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Building {
pub id: BuildingId,
pub building_type: BuildingTypeCode,
pub municipality_part: Option<MunicipalityPartReference>,
pub house_number: Option<String>,
pub use_code: Option<String>,
pub identifying_parcel: Option<ParcelIdentity>,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub attachment: Option<BuildingAttachment>,
pub building_right: Option<BuildingRightIdentity>,
pub temporary: Option<YesNo>,
pub defined_units: Option<YesNo>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Unit {
pub id: UnitId,
pub building: BuildingIdentity,
pub unit_type_code: String,
pub number: u64,
pub use_code: Option<String>,
pub ownership_sheet_id: Option<OwnershipSheetId>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightPurpose {
pub code: String,
pub name: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRight {
pub id: BuildingRightId,
pub valid_until: XmlDate,
pub ownership_sheet_id: Option<OwnershipSheetId>,
pub purposes: Vec<BuildingRightPurpose>,
pub only_identifying_parcel: YesNo,
pub parcels: Vec<ParcelIdentity>,
}
#[derive(Clone, Eq, PartialEq)]
pub struct SubjectBase {
pub id: SubjectId,
pub name: Option<String>,
pub company_id: Option<CompanyId>,
pub company_id_suffix: Option<String>,
pub surname: Option<String>,
pub given_name: Option<String>,
pub title_before: Option<String>,
pub title_after: Option<String>,
pub short_personal_id: Option<ShortPersonalIdentifier>,
pub street: Option<String>,
pub house_number: Option<String>,
pub orientation_number: Option<String>,
pub municipality_part_name: Option<String>,
pub municipality_name: Option<String>,
pub city_district_name: Option<String>,
pub city_borough_name: Option<String>,
pub postal_code: Option<String>,
pub kind: SubjectKind,
pub address_number_kind: Option<AddressNumberKind>,
pub country_name: Option<String>,
pub district_name: Option<String>,
pub characteristic_code: Option<String>,
}
impl fmt::Debug for SubjectBase {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("SubjectBase([REDACTED])")
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct AuthorizedSubject {
pub base: SubjectBase,
pub partner1: Option<SubjectBase>,
pub partner2: Option<SubjectBase>,
}
impl fmt::Debug for AuthorizedSubject {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("AuthorizedSubject([REDACTED])")
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Proceeding {
pub id: ProceedingId,
pub workplace: WorkplaceCode,
pub proceeding_type: String,
pub serial_number: u32,
pub year: u16,
pub external_id: Option<String>,
pub created_at: XmlDateTime,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollectionDocument {
pub id: DocumentId,
pub designation: String,
pub executed_at: Option<XmlDateTime>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeometricPlan {
pub cadastral_area: CadastralAreaCode,
pub survey_result_number: i32,
pub document_id: DocumentId,
pub file_name: String,
pub proceeding: Proceeding,
pub change_proposal_number: Option<String>,
pub confirmed_on: Option<XmlDate>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OwnershipTarget {
Subject(SubjectId),
Parcel(ParcelId),
Building(BuildingId),
Unit(UnitId),
BuildingRight(BuildingRightId),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ownership {
pub id: OwnershipId,
pub ownership_sheet_id: OwnershipSheetId,
pub share_numerator: FractionComponent,
pub share_denominator: FractionComponent,
pub legal_relation_code: String,
pub cadastral_area: CadastralAreaCode,
pub ownership_sheet_number: u32,
pub target: OwnershipTarget,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParcelSearchSelector {
Id(ParcelId),
Number(ParcelSearchKey),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelSearchKey {
pub cadastral_area: CadastralAreaCode,
pub number: ParcelNumber,
}
impl ParcelSearchKey {
pub(crate) fn validate(&self) -> Result<()> {
self.number.validate()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelSearch {
pub selector: ParcelSearchSelector,
pub valid_at: Option<XmlDateTime>,
}
impl ParcelSearch {
pub(crate) fn validate(&self) -> Result<()> {
validate_parcel_selector(&self.selector)
}
}
fn validate_parcel_selector(selector: &ParcelSearchSelector) -> Result<()> {
match selector {
ParcelSearchSelector::Id(_) => Ok(()),
ParcelSearchSelector::Number(key) => key.validate(),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingSearchSelector {
Id(BuildingId),
Number(BuildingSearchKey),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingSearchKey {
pub municipality_part: MunicipalityPartCode,
pub building_type: BuildingTypeCode,
pub house_number: u16,
}
impl BuildingSearchKey {
pub fn new(
municipality_part: MunicipalityPartCode,
building_type: BuildingTypeCode,
house_number: u16,
) -> Result<Self> {
let value = Self {
municipality_part,
building_type,
house_number,
};
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
if !(1..=9999).contains(&self.house_number) {
return Err(Error::invalid_input(
"house_number",
"house number must be in 1..=9999",
));
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingSearch {
pub selector: BuildingSearchSelector,
pub valid_at: Option<XmlDateTime>,
}
impl BuildingSearch {
pub(crate) fn validate(&self) -> Result<()> {
validate_building_selector(&self.selector)
}
}
fn validate_building_selector(selector: &BuildingSearchSelector) -> Result<()> {
match selector {
BuildingSearchSelector::Id(_) => Ok(()),
BuildingSearchSelector::Number(key) => key.validate(),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UnitSearchSelector {
Id(UnitId),
Number(UnitSearchKey),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitSearchKey {
pub building: BuildingSearchSelector,
pub number: Option<u64>,
}
impl UnitSearchKey {
pub fn new(building: BuildingSearchSelector, number: Option<u64>) -> Result<Self> {
let value = Self { building, number };
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
validate_building_selector(&self.building)?;
if self.number.is_some_and(|value| value > 9_999_999_999) {
return Err(Error::invalid_input(
"unit_number",
"unit number must be at most 9999999999",
));
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitSearch {
pub selector: UnitSearchSelector,
pub valid_at: Option<XmlDateTime>,
}
impl UnitSearch {
pub(crate) fn validate(&self) -> Result<()> {
match &self.selector {
UnitSearchSelector::Id(_) => Ok(()),
UnitSearchSelector::Number(key) => key.validate(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingRightSelector {
Id(BuildingRightId),
Parcel(ParcelSearchSelector),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightSearch {
pub selector: BuildingRightSelector,
pub valid_at: Option<XmlDateTime>,
}
impl BuildingRightSearch {
pub(crate) fn validate(&self) -> Result<()> {
match &self.selector {
BuildingRightSelector::Id(_) => Ok(()),
BuildingRightSelector::Parcel(selector) => validate_parcel_selector(selector),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProceedingSearchKey {
pub proceeding_type: String,
pub serial_number: u32,
pub year: u16,
pub workplace: WorkplaceCode,
}
impl ProceedingSearchKey {
pub fn new(
proceeding_type: impl Into<String>,
serial_number: u32,
year: u16,
workplace: WorkplaceCode,
) -> Result<Self> {
let value = Self {
proceeding_type: proceeding_type.into(),
serial_number,
year,
workplace,
};
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
if !(1..=3).contains(&self.proceeding_type.chars().count()) {
return Err(Error::invalid_input(
"proceeding_type",
"proceeding type must contain 1 to 3 characters",
));
}
if !(1..=99_999_999).contains(&self.serial_number) {
return Err(Error::invalid_input(
"serial_number",
"proceeding serial number must be in 1..=99999999",
));
}
if !(1..=9999).contains(&self.year) {
return Err(Error::invalid_input(
"year",
"proceeding year must be in 1..=9999",
));
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProceedingSearchSelector {
Id(ProceedingId),
Number(ProceedingSearchKey),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProceedingSearch {
pub selector: ProceedingSearchSelector,
}
impl ProceedingSearch {
pub(crate) fn validate(&self) -> Result<()> {
validate_proceeding_selector(&self.selector)
}
}
fn validate_proceeding_selector(selector: &ProceedingSearchSelector) -> Result<()> {
match selector {
ProceedingSearchSelector::Id(_) => Ok(()),
ProceedingSearchSelector::Number(key) => key.validate(),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollectionDocumentSearch {
pub proceeding: ProceedingSearchSelector,
}
impl CollectionDocumentSearch {
pub(crate) fn validate(&self) -> Result<()> {
validate_proceeding_selector(&self.proceeding)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeometricPlanSearch {
pub cadastral_area: CadastralAreaCode,
pub survey_result_number: i32,
}
impl GeometricPlanSearch {
pub fn new(cadastral_area: CadastralAreaCode, survey_result_number: i32) -> Result<Self> {
let value = Self {
cadastral_area,
survey_result_number,
};
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
if !(-99_999..=99_999).contains(&self.survey_result_number) {
return Err(Error::invalid_input(
"survey_result_number",
"survey-result number must be in -99999..=99999",
));
}
Ok(())
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct LegalPersonSearch {
pub company_id: Option<CompanyId>,
pub name: Option<String>,
}
impl LegalPersonSearch {
pub fn new(company_id: Option<CompanyId>, name: Option<String>) -> Result<Self> {
let value = Self { company_id, name };
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
if self.company_id.is_none() && self.name.is_none() {
return Err(Error::invalid_input(
"legal_person",
"company ID or name is required",
));
}
if self
.name
.as_deref()
.is_some_and(|value| !(2..=255).contains(&value.chars().count()))
{
return Err(Error::invalid_input(
"name",
"legal-person search name must contain 2 to 255 characters",
));
}
Ok(())
}
}
impl fmt::Debug for LegalPersonSearch {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LegalPersonSearch")
.field(
"company_id",
&self.company_id.as_ref().map(|_| "[REDACTED]"),
)
.field("name", &self.name.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub enum PersonBirthSelector {
PersonalIdentifier(PersonalIdentifier),
BirthDate(XmlDate),
}
impl fmt::Debug for PersonBirthSelector {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::PersonalIdentifier(_) => "PersonalIdentifier([REDACTED])",
Self::BirthDate(_) => "BirthDate([REDACTED])",
})
}
}
#[derive(Clone, Default, Eq, PartialEq)]
pub struct SubjectAddressFilter {
pub municipality: Option<String>,
pub municipality_part: Option<String>,
pub street: Option<String>,
pub orientation_number: Option<String>,
pub house_number: Option<u16>,
}
impl SubjectAddressFilter {
pub(crate) fn validate(&self) -> Result<()> {
validate_optional_length(self.municipality.as_deref(), "municipality", 1, 48)?;
validate_optional_length(
self.municipality_part.as_deref(),
"municipality_part",
1,
48,
)?;
validate_optional_length(self.street.as_deref(), "street", 1, 48)?;
validate_optional_length(
self.orientation_number.as_deref(),
"orientation_number",
1,
4,
)?;
if self
.house_number
.is_some_and(|value| !(1..=9999).contains(&value))
{
return Err(Error::invalid_input(
"house_number",
"house number must be in 1..=9999",
));
}
Ok(())
}
}
impl fmt::Debug for SubjectAddressFilter {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SubjectAddressFilter")
.field(
"municipality",
&self.municipality.as_ref().map(|_| "[REDACTED]"),
)
.field(
"municipality_part",
&self.municipality_part.as_ref().map(|_| "[REDACTED]"),
)
.field("street", &self.street.as_ref().map(|_| "[REDACTED]"))
.field(
"orientation_number",
&self.orientation_number.as_ref().map(|_| "[REDACTED]"),
)
.field("house_number", &self.house_number.map(|_| "[REDACTED]"))
.finish()
}
}
fn validate_optional_length(
value: Option<&str>,
field: &'static str,
minimum: usize,
maximum: usize,
) -> Result<()> {
if value.is_some_and(|value| !(minimum..=maximum).contains(&value.chars().count())) {
return Err(Error::invalid_input(
field,
format!("value must contain {minimum} to {maximum} characters"),
));
}
Ok(())
}
#[derive(Clone, Default, Eq, PartialEq)]
pub struct PersonOrPartnershipSearch {
pub given_name: Option<String>,
pub surname: Option<String>,
pub birth: Option<PersonBirthSelector>,
pub address: Option<SubjectAddressFilter>,
}
impl PersonOrPartnershipSearch {
pub(crate) fn validate(&self) -> Result<()> {
validate_optional_length(self.given_name.as_deref(), "given_name", 2, 100)?;
validate_optional_length(self.surname.as_deref(), "surname", 2, 100)?;
if let Some(address) = &self.address {
address.validate()?;
}
Ok(())
}
}
impl fmt::Debug for PersonOrPartnershipSearch {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PersonOrPartnershipSearch")
.field(
"given_name",
&self.given_name.as_ref().map(|_| "[REDACTED]"),
)
.field("surname", &self.surname.as_ref().map(|_| "[REDACTED]"))
.field("birth", &self.birth)
.field("address", &self.address)
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub enum SubjectSearchSelector {
LegalPerson(LegalPersonSearch),
PersonOrPartnership(PersonOrPartnershipSearch),
}
impl fmt::Debug for SubjectSearchSelector {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::LegalPerson(search) => {
formatter.debug_tuple("LegalPerson").field(search).finish()
}
Self::PersonOrPartnership(search) => formatter
.debug_tuple("PersonOrPartnership")
.field(search)
.finish(),
}
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct SubjectSearch {
pub selector: SubjectSearchSelector,
pub valid_at: Option<XmlDateTime>,
}
impl SubjectSearch {
pub(crate) fn validate(&self) -> Result<()> {
match &self.selector {
SubjectSearchSelector::LegalPerson(search) => search.validate(),
SubjectSearchSelector::PersonOrPartnership(search) => search.validate(),
}
}
}
impl fmt::Debug for SubjectSearch {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SubjectSearch")
.field("selector", &self.selector)
.field("valid_at", &self.valid_at)
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub enum SearchRequest {
Parcel(ParcelSearch),
Unit(UnitSearch),
Building(BuildingSearch),
Subject(SubjectSearch),
BuildingRight(BuildingRightSearch),
Proceeding(ProceedingSearch),
CollectionDocument(CollectionDocumentSearch),
GeometricPlan(GeometricPlanSearch),
}
impl SearchRequest {
pub(crate) fn validate(&self) -> Result<()> {
match self {
Self::Parcel(request) => request.validate(),
Self::Unit(request) => request.validate(),
Self::Building(request) => request.validate(),
Self::Subject(request) => request.validate(),
Self::BuildingRight(request) => request.validate(),
Self::Proceeding(request) => request.validate(),
Self::CollectionDocument(request) => request.validate(),
Self::GeometricPlan(request) => request.validate(),
}
}
}
impl fmt::Debug for SearchRequest {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parcel(request) => formatter.debug_tuple("Parcel").field(request).finish(),
Self::Unit(request) => formatter.debug_tuple("Unit").field(request).finish(),
Self::Building(request) => formatter.debug_tuple("Building").field(request).finish(),
Self::Subject(request) => formatter.debug_tuple("Subject").field(request).finish(),
Self::BuildingRight(request) => formatter
.debug_tuple("BuildingRight")
.field(request)
.finish(),
Self::Proceeding(request) => {
formatter.debug_tuple("Proceeding").field(request).finish()
}
Self::CollectionDocument(request) => formatter
.debug_tuple("CollectionDocument")
.field(request)
.finish(),
Self::GeometricPlan(request) => formatter
.debug_tuple("GeometricPlan")
.field(request)
.finish(),
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SearchCompletion {
Complete,
Empty,
LimitExceeded,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SearchResult<T> {
pub items: Vec<T>,
pub completion: SearchCompletion,
}
impl<T> SearchResult<T> {
pub fn from_items(items: Vec<T>) -> Self {
let completion = if items.is_empty() {
SearchCompletion::Empty
} else {
SearchCompletion::Complete
};
Self { items, completion }
}
pub fn refine_completion(&mut self, messages: &[ServiceMessage]) {
self.completion = if messages
.iter()
.any(|message| message.code == MessageCode::ResultLimitExceeded)
{
SearchCompletion::LimitExceeded
} else if self.items.is_empty()
|| messages
.iter()
.any(|message| message.code == MessageCode::NoData)
{
SearchCompletion::Empty
} else {
SearchCompletion::Complete
};
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SearchResponse {
Parcels(SearchResult<Parcel>),
Units(SearchResult<Unit>),
Buildings(SearchResult<Building>),
Subjects(SearchResult<AuthorizedSubject>),
BuildingRights(SearchResult<BuildingRight>),
Proceedings(SearchResult<Proceeding>),
CollectionDocuments(SearchResult<CollectionDocument>),
GeometricPlans(SearchResult<GeometricPlan>),
}
impl SearchResponse {
pub fn refine_completion(&mut self, messages: &[ServiceMessage]) {
match self {
Self::Parcels(result) => result.refine_completion(messages),
Self::Units(result) => result.refine_completion(messages),
Self::Buildings(result) => result.refine_completion(messages),
Self::Subjects(result) => result.refine_completion(messages),
Self::BuildingRights(result) => result.refine_completion(messages),
Self::Proceedings(result) => result.refine_completion(messages),
Self::CollectionDocuments(result) => result.refine_completion(messages),
Self::GeometricPlans(result) => result.refine_completion(messages),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{MessageLevel, ServiceMessage};
#[test]
fn xml_date_retains_naive_and_offset_forms() {
for raw in [
"2026-11-20",
"2026-11-20Z",
"2026-11-20+01:00",
"2024-02-29-14:00",
" \t2026-11-20+14:00\r\n",
"-0001-01-01Z",
"10000-01-01",
] {
assert_eq!(XmlDate::new(raw).unwrap().as_str(), raw);
}
for raw in [
"20.11.2026",
"2026-02-29",
"2026-11-20z",
"2026-11-20+14:01",
"2026-11-20+15:00",
"2026-11-20+01:00:01",
"0000-01-01",
] {
assert!(XmlDate::new(raw).is_err(), "{raw}");
}
}
#[test]
fn completion_uses_limit_and_no_data_messages() {
let mut result = SearchResult::from_items(vec![1]);
result.refine_completion(&[ServiceMessage {
code: MessageCode::from_raw(" \t+000310\r\n"),
level: MessageLevel::Warning,
text: String::new(),
}]);
assert_eq!(result.completion, SearchCompletion::LimitExceeded);
result.refine_completion(&[]);
assert_eq!(result.completion, SearchCompletion::Complete);
result.items.clear();
result.refine_completion(&[]);
assert_eq!(result.completion, SearchCompletion::Empty);
}
#[test]
fn integer_lexical_forms_are_preserved_while_digit_limits_and_ranges_hold() {
let building = BuildingTypeCode::new(" \t+0009\r\n").unwrap();
assert_eq!(building.as_str(), " \t+0009\r\n");
assert!(BuildingTypeCode::new("+10").is_err());
assert!(BuildingTypeCode::new(" +0 ").is_err());
assert!(BuildingTypeCode::new("++1").is_err());
let raw = "123456789012345678901234567890";
let fraction = FractionComponent::new(format!(" \t+{raw}\r\n")).unwrap();
assert_eq!(fraction.as_str(), " \t+123456789012345678901234567890\r\n");
assert!(FractionComponent::new(" +1234567890123456789012345678901 ").is_err());
assert!(FractionComponent::new("+000").is_err());
}
#[cfg(feature = "serde")]
#[test]
fn search_integer_deserialization_uses_validating_constructors() {
let code: BuildingTypeCode = serde_json::from_str("\" +0009 \"").unwrap();
assert_eq!(code.as_str(), " +0009 ");
assert!(serde_json::from_str::<BuildingTypeCode>("\"10\"").is_err());
let component: FractionComponent = serde_json::from_str("\" +0001 \"").unwrap();
assert_eq!(component.as_str(), " +0001 ");
assert!(serde_json::from_str::<FractionComponent>("\"0\"").is_err());
}
#[test]
fn directly_constructed_request_fields_recheck_all_constructor_invariants() {
assert!(
ParcelNumber {
root: 100_000,
subdivision: None,
}
.validate()
.is_err()
);
assert!(
ParcelNumber {
root: 1,
subdivision: Some(0),
}
.validate()
.is_err()
);
let building = BuildingSearchKey {
municipality_part: MunicipalityPartCode::new("1").unwrap(),
building_type: BuildingTypeCode::new("1").unwrap(),
house_number: 0,
};
assert!(building.validate().is_err());
let unit = UnitSearchKey {
building: BuildingSearchSelector::Number(building),
number: Some(10_000_000_000),
};
assert!(unit.validate().is_err());
let proceeding = ProceedingSearchKey {
proceeding_type: String::new(),
serial_number: 0,
year: 10_000,
workplace: WorkplaceCode::new("1").unwrap(),
};
assert!(proceeding.validate().is_err());
assert!(
GeometricPlanSearch {
cadastral_area: CadastralAreaCode::new("1").unwrap(),
survey_result_number: 100_000,
}
.validate()
.is_err()
);
assert!(
LegalPersonSearch {
company_id: None,
name: None,
}
.validate()
.is_err()
);
assert!(
LegalPersonSearch {
company_id: None,
name: Some("x".to_owned()),
}
.validate()
.is_err()
);
assert!(
PersonOrPartnershipSearch {
given_name: Some("J".to_owned()),
surname: None,
birth: None,
address: Some(SubjectAddressFilter {
house_number: Some(0),
..SubjectAddressFilter::default()
}),
}
.validate()
.is_err()
);
}
#[test]
fn sensitive_subject_queries_are_redacted_at_every_debug_layer() {
let person = PersonOrPartnershipSearch {
given_name: Some("given-secret".to_owned()),
surname: Some("surname-secret".to_owned()),
birth: Some(PersonBirthSelector::BirthDate(
XmlDate::new("2001-02-03").unwrap(),
)),
address: Some(SubjectAddressFilter {
municipality: Some("municipality-secret".to_owned()),
municipality_part: Some("part-secret".to_owned()),
street: Some("street-secret".to_owned()),
orientation_number: Some("77A".to_owned()),
house_number: Some(13_579),
}),
};
let selector = SubjectSearchSelector::PersonOrPartnership(person.clone());
let subject = SubjectSearch {
selector: selector.clone(),
valid_at: None,
};
let request = SearchRequest::Subject(subject.clone());
let debug = format!("{person:?} {selector:?} {subject:?} {request:?}");
for sentinel in [
"given-secret",
"surname-secret",
"2001-02-03",
"municipality-secret",
"part-secret",
"street-secret",
"77A",
"13579",
] {
assert!(!debug.contains(sentinel), "{debug}");
}
let legal = LegalPersonSearch::new(
Some(CompanyId::new("12345678").unwrap()),
Some("legal-secret".to_owned()),
)
.unwrap();
let subject = SubjectSearch {
selector: SubjectSearchSelector::LegalPerson(legal.clone()),
valid_at: None,
};
let request = SearchRequest::Subject(subject.clone());
let debug = format!("{legal:?} {subject:?} {request:?}");
assert!(!debug.contains("legal-secret"));
assert!(!debug.contains("12345678"));
}
#[test]
fn personal_identifiers_are_debug_redacted() {
let short = ShortPersonalIdentifier::new("123456").unwrap();
assert!(!format!("{short:?}").contains("123456"));
let full = PersonalIdentifier::new("123456789").unwrap();
let selector = PersonBirthSelector::PersonalIdentifier(full);
assert!(!format!("{selector:?}").contains("123456789"));
}
}