dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
use std::fmt;

use crate::model::{Area, InfrastructurePartInfo};
use crate::{Error, Result};

const MAX_INQUIRY_PARCELS: usize = 400;
const MAX_INQUIRY_AREA_SQUARE_METRES: f64 = 2_000_000.0;

macro_rules! redacted_debug {
    ($($name:ident),+ $(,)?) => {
        $(
            impl fmt::Debug for $name {
                fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                    formatter.write_str(concat!(stringify!($name), "([REDACTED])"))
                }
            }
        )+
    };
}

/// The explicit territorial choice for an R49 infrastructure-manager inquiry.
///
/// A request selects either RÚIAN parcel identifiers or one GML area, never
/// both. Parcel selectors contain 1 through 400 identifiers. Area selectors
/// must use S-JTSK and have a planar area of at most 2,000,000 m² (200 ha).
#[derive(Clone, PartialEq)]
pub enum InfrastructureManagerInquirySelector {
    /// RÚIAN parcel references (`Parcely/Parcela/isdmvsRuian:Id`).
    Parcels(Vec<i64>),
    /// Territorial geometry (`UzemniVymezeni`).
    Area(Area),
}

impl InfrastructureManagerInquirySelector {
    /// Creates a selector containing 1 through 400 RÚIAN parcel identifiers.
    pub fn parcels(parcel_ids: Vec<i64>) -> Result<Self> {
        let selector = Self::Parcels(parcel_ids);
        selector.validate()?;
        Ok(selector)
    }

    /// Creates an S-JTSK area selector of at most 2,000,000 m².
    pub fn area(area: Area) -> Result<Self> {
        area.ensure_maximum_s_jtsk_area(MAX_INQUIRY_AREA_SQUARE_METRES)?;
        Ok(Self::Area(area))
    }

    pub(crate) fn validate(&self) -> Result<()> {
        match self {
            Self::Parcels(parcel_ids) => {
                if parcel_ids.is_empty() || parcel_ids.len() > MAX_INQUIRY_PARCELS {
                    return Err(Error::invalid_input(
                        "selection.parcels",
                        "between 1 and 400 parcel identifiers are required",
                    ));
                }
                Ok(())
            }
            Self::Area(area) => area.ensure_maximum_s_jtsk_area(MAX_INQUIRY_AREA_SQUARE_METRES),
        }
    }
}

/// Validated input for R49 `zjistiUzemiSpravcuDti`.
///
/// The business identification is serialized as required by the XSD without
/// inventing a local format restriction. Server-side authorization and input
/// validation still apply.
#[derive(Clone, PartialEq)]
pub struct InfrastructureManagerInquiryRequest {
    pub(crate) selector: InfrastructureManagerInquirySelector,
    pub(crate) identification: String,
    pub(crate) notification_email: Option<String>,
}

impl InfrastructureManagerInquiryRequest {
    /// Creates an inquiry from an explicit selector and the required business
    /// identification (`Identifikace`). The requester subject comes from the
    /// client configuration.
    pub fn new(
        selector: InfrastructureManagerInquirySelector,
        identification: impl Into<String>,
    ) -> Result<Self> {
        selector.validate()?;
        Ok(Self {
            selector,
            identification: identification.into(),
            notification_email: None,
        })
    }

    /// Sets the optional notification e-mail (`NotifikacniEmail`).
    pub fn with_notification_email(mut self, email: impl Into<String>) -> Self {
        self.notification_email = Some(email.into());
        self
    }
}

/// The opaque `IdPodani` returned in an R49 overall result.
///
/// This identifier is deliberately distinct from the asynchronous
/// [`crate::RequestId`] used to retrieve that result.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct InquirySubmissionId(String);

impl InquirySubmissionId {
    /// Creates an opaque inquiry submission identifier without interpreting it.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        if value.is_empty()
            || value.len() > 256
            || value.trim() != value
            || value.chars().any(char::is_control)
        {
            return Err(Error::invalid_input(
                "inquiry_submission_id",
                "expected a non-empty, trimmed string of at most 256 bytes without control characters",
            ));
        }
        Ok(Self(value))
    }

    /// Returns the identifier exactly as supplied by the service.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A RÚIAN municipality reference in an R49 overall result.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryMunicipality {
    /// RÚIAN municipality code (`Obec/Kod`).
    pub code: i64,
    /// Municipality name (`Obec/Nazev`), which may be empty.
    pub name: String,
}

/// A RÚIAN cadastral area reference in an R49 overall result.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryCadastralArea {
    /// Cadastral-area code (`KatastralniUzemi/Kod`).
    pub code: i64,
    /// Cadastral-area name (`KatastralniUzemi/Nazev`), which may be empty.
    pub name: String,
    /// Municipality containing the cadastral area.
    pub municipality: InquiryMunicipality,
}

/// One RÚIAN parcel returned in an R49 overall result.
///
/// The four components declared as XSD `integer` are retained as strings so
/// valid arbitrary-precision values cannot overflow a machine integer.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryParcel {
    /// RÚIAN parcel identifier (`Id`), represented as the XSD `long` value.
    pub id: i64,
    /// Main parcel number (`KmenoveCislo`) as an arbitrary-precision integer string.
    pub main_number: String,
    /// Optional subdivision number (`PoddeleniCisla`) as an integer string.
    pub subdivision_number: Option<String>,
    /// Numbering type (`DruhCislovani`) as an arbitrary-precision integer string.
    pub numbering_type: String,
    /// Parcel type (`DruhPozemku`) as an arbitrary-precision integer string.
    pub parcel_type: String,
    /// Whether only part of the parcel is affected (`PouzeCast`).
    pub only_part: bool,
}

/// All parcels associated with one cadastral area in an R49 overall result.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryParcelGroup {
    /// Cadastral-area and municipality reference.
    pub cadastral_area: InquiryCadastralArea,
    /// Returned parcels in service order; the required wrapper may be empty.
    pub parcels: Vec<InquiryParcel>,
}

/// Overall data returned by R49 `ctiVysledekZjistiUzemiSpravcuDti`.
///
/// These counts and parcel groups are independent of the common response-header
/// processing state and of per-part validation results. No infrastructure-part
/// page or PDF report is retrieved implicitly.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct OverallResult {
    /// Result `IdPodani`, distinct from the asynchronous polling request ID.
    pub submission_id: InquirySubmissionId,
    /// Cadastral-area groups and their parcels in service order.
    pub parcel_groups: Vec<InquiryParcelGroup>,
    /// Declared total infrastructure-part count (`PocetCastiDti`), checked nonnegative.
    pub infrastructure_part_count: u64,
    /// Whether server-side validation has completed (`ValidaceDokoncena`).
    pub validation_completed: bool,
    /// Optional declared valid-part count (`PocetValidnichCastiDti`), checked nonnegative.
    pub valid_infrastructure_part_count: Option<u64>,
}

/// Contact details supplied for obtaining a statement about one infrastructure part.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryContactDetails {
    /// Optional contact URL (`Url`), retained as text and never fetched implicitly.
    pub url: Option<String>,
    /// Optional data-box identifier (`Idds`).
    pub idds: Option<String>,
    /// Optional e-mail address (`Email`).
    pub email: Option<String>,
    /// Optional telephone number (`Telefon`).
    pub phone: Option<String>,
    /// Optional free-form note (`Poznamka`).
    pub note: Option<String>,
}

/// Validation outcome attached to one infrastructure part in an R49 page.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InquiryValidationResult {
    /// Whether the part is valid (`Validni`).
    pub valid: bool,
    /// Required validation description (`Popis`), which may be empty.
    pub description: String,
}

/// One infrastructure part returned by R49
/// `ctiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti`.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct InfrastructureInquiryPart {
    /// Shared infrastructure-part information, including any role contacts and people.
    pub info: InfrastructurePartInfo,
    /// Required statement-contact wrapper and its optional contact fields.
    pub contact: InquiryContactDetails,
    /// Required per-part validation result, kept separate from response state.
    pub validation: InquiryValidationResult,
}

redacted_debug!(
    InfrastructureManagerInquirySelector,
    InfrastructureManagerInquiryRequest,
    InquirySubmissionId,
    InquiryMunicipality,
    InquiryCadastralArea,
    InquiryParcel,
    InquiryParcelGroup,
    OverallResult,
    InquiryContactDetails,
    InquiryValidationResult,
    InfrastructureInquiryPart,
);

#[cfg(test)]
mod tests {
    use geo_types::{LineString, Polygon, coord};

    use super::*;
    use crate::model::CoordinateReferenceSystem;

    fn rectangle(height: f64) -> Area {
        Area::s_jtsk(Polygon::new(
            LineString::from(vec![
                coord! { x: 0.0, y: 0.0 },
                coord! { x: 2_000.0, y: 0.0 },
                coord! { x: 2_000.0, y: height },
                coord! { x: 0.0, y: height },
                coord! { x: 0.0, y: 0.0 },
            ]),
            Vec::new(),
        ))
        .unwrap()
    }

    #[test]
    fn selector_enforces_parcel_and_area_bounds() {
        assert!(InfrastructureManagerInquirySelector::parcels(Vec::new()).is_err());
        assert!(InfrastructureManagerInquirySelector::parcels(vec![1; 400]).is_ok());
        assert!(InfrastructureManagerInquirySelector::parcels(vec![1; 401]).is_err());
        assert!(InfrastructureManagerInquirySelector::area(rectangle(1_000.0)).is_ok());
        assert!(InfrastructureManagerInquirySelector::area(rectangle(1_001.0)).is_err());

        let other_crs = Area::new(
            rectangle(1.0).geometry().clone(),
            CoordinateReferenceSystem::new("urn:ogc:def:crs:EPSG::4326").unwrap(),
        )
        .unwrap();
        assert!(InfrastructureManagerInquirySelector::area(other_crs).is_err());

        // Direct enum construction cannot bypass validation at the request boundary.
        assert!(
            InfrastructureManagerInquiryRequest::new(
                InfrastructureManagerInquirySelector::Parcels(Vec::new()),
                "business-id",
            )
            .is_err()
        );
    }

    #[test]
    fn request_debug_redacts_business_identifiers_email_and_geometry() {
        let request = InfrastructureManagerInquiryRequest::new(
            InfrastructureManagerInquirySelector::Parcels(vec![5_000_000_000]),
            "private-business-id",
        )
        .unwrap()
        .with_notification_email("private@example.invalid");
        let debug = format!("{request:?}");
        for private in [
            "5000000000",
            "private-business-id",
            "private@example.invalid",
        ] {
            assert!(!debug.contains(private), "debug output contained {private}");
        }

        let area = InfrastructureManagerInquirySelector::area(rectangle(1.0)).unwrap();
        assert!(!format!("{area:?}").contains("2000.0"));
        assert_eq!(
            format!(
                "{:?}",
                InquirySubmissionId::new("private-submission").unwrap()
            ),
            "InquirySubmissionId([REDACTED])"
        );
    }
}