use std::collections::HashSet;
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use bytes::Bytes;
use rust_decimal::Decimal;
use super::common::{ServiceMessage, XmlDateTime};
use super::id::{
BuildingId, BuildingRightId, CadastralAreaCode, Czk, DocumentId, MunicipalityCode,
MunicipalityPartCode, OwnershipSheetId, ParcelId, ParcelNumber, ProceedingId, RegionCode,
ReportId, SubjectId, UnitId,
};
use super::legal_relation::LegalRelationCode;
use crate::{Error, Result};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ReportFamily {
PricesByProperties,
PricesByProceeding,
RightsRecord,
UnitInfo,
ParcelInfo,
BuildingRightInfo,
ProceedingInfo,
BuildingInfo,
OwnershipOverview,
OwnershipOverviewWithProperties,
DefinitionPoints,
AccountStatement,
OwnershipSheet,
Other(String),
}
impl ReportFamily {
pub(crate) const ALL: &'static [Self] = &[
Self::PricesByProperties,
Self::PricesByProceeding,
Self::RightsRecord,
Self::UnitInfo,
Self::ParcelInfo,
Self::BuildingRightInfo,
Self::ProceedingInfo,
Self::BuildingInfo,
Self::OwnershipOverview,
Self::OwnershipOverviewWithProperties,
Self::DefinitionPoints,
Self::AccountStatement,
Self::OwnershipSheet,
];
pub fn as_str(&self) -> &str {
match self {
Self::PricesByProperties => "CenoveUdajeDleNemovitosti",
Self::PricesByProceeding => "CenoveUdajeDleRizeni",
Self::RightsRecord => "EvidencePravProOsobu",
Self::UnitInfo => "InformaceOJednotkach",
Self::ParcelInfo => "InformaceOParcelach",
Self::BuildingRightInfo => "InformaceOPravechStavby",
Self::ProceedingInfo => "InformaceORizeni",
Self::BuildingInfo => "InformaceOStavbach",
Self::OwnershipOverview => "PrehledVlastnictvi",
Self::OwnershipOverviewWithProperties => "PrehledVlastnictviSNemovitostmi",
Self::DefinitionPoints => "SeznamDefinicnichBoduParcel",
Self::AccountStatement => "VypisStavuZakaznickehoUctu",
Self::OwnershipSheet => "VypisZKatastruNemovitosti",
Self::Other(raw) => raw,
}
}
pub fn default_version(&self) -> Option<ReportVersion> {
match self {
Self::Other(_) => None,
Self::OwnershipSheet => Some(ReportVersion::V3_0),
_ => Some(ReportVersion::V1_0),
}
}
pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
Self::ALL
.iter()
.find(|family| family.as_str() == raw)
.cloned()
.unwrap_or(Self::Other(raw))
}
}
impl fmt::Display for ReportFamily {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ReportVersion {
V1_0,
V3_0,
Other(String),
}
impl ReportVersion {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
let mut parts = value.split('.');
let valid =
parts.next().is_some_and(|part| {
!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())
}) && parts.next().is_some_and(|part| {
!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())
}) && parts.next().is_none();
if !valid {
return Err(Error::invalid_input(
"report_version",
"expected MAJOR.MINOR decimal digits",
));
}
Ok(match value.as_str() {
"1.0" => Self::V1_0,
"3.0" => Self::V3_0,
_ => Self::Other(value),
})
}
pub fn as_str(&self) -> &str {
match self {
Self::V1_0 => "1.0",
Self::V3_0 => "3.0",
Self::Other(raw) => raw,
}
}
}
impl FromStr for ReportVersion {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl fmt::Display for ReportVersion {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct ReportVersionInfo {
pub family: ReportFamily,
pub name: String,
pub versions: Vec<ReportVersion>,
}
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub enum ReportVersionSelection {
#[default]
DefaultForFamily,
Pinned(ReportVersion),
LatestAvailable,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum OutputFormat {
Pdf,
Xml,
}
impl OutputFormat {
pub fn as_str(self) -> &'static str {
match self {
Self::Pdf => "pdf",
Self::Xml => "xml",
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum AccountKind {
#[default]
Paying,
Free,
Verifying,
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub enum AccountContext {
Paying,
Free {
cislo_jednaci: String,
ucel_kod: u8,
},
Verifying {
poradove_cislo: String,
overovaci_dolozka: bool,
},
}
impl fmt::Debug for AccountContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Paying => formatter.write_str("Paying"),
Self::Free { ucel_kod, .. } => formatter
.debug_struct("Free")
.field("cislo_jednaci", &"[REDACTED]")
.field("ucel_kod", ucel_kod)
.finish(),
Self::Verifying {
overovaci_dolozka, ..
} => formatter
.debug_struct("Verifying")
.field("poradove_cislo", &"[REDACTED]")
.field("overovaci_dolozka", overovaci_dolozka)
.finish(),
}
}
}
impl AccountContext {
fn validate(&self) -> Result<()> {
match self {
Self::Paying => Ok(()),
Self::Free {
cislo_jednaci,
ucel_kod,
} => {
validate_character_length("cislo_jednaci", cislo_jednaci, 1, 50)?;
if !(1..=99).contains(ucel_kod) {
return Err(Error::invalid_input(
"ucel_kod",
"report purpose code must be in 1..=99",
));
}
Ok(())
}
Self::Verifying { poradove_cislo, .. } => {
validate_character_length("poradove_cislo", poradove_cislo, 1, 40)
}
}
}
fn is_verifying(&self) -> bool {
matches!(self, Self::Verifying { .. })
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReportOptions {
pub format: OutputFormat,
pub version: ReportVersionSelection,
pub attach_xml: bool,
pub account: AccountContext,
}
impl ReportOptions {
pub fn new(
format: OutputFormat,
version: ReportVersionSelection,
attach_xml: bool,
account: AccountContext,
) -> Self {
Self {
format,
version,
attach_xml,
account,
}
}
pub fn xml_default(account: AccountContext) -> Self {
Self::new(
OutputFormat::Xml,
ReportVersionSelection::DefaultForFamily,
false,
account,
)
}
pub fn xml(version: ReportVersion, account: AccountContext) -> Self {
Self::new(
OutputFormat::Xml,
ReportVersionSelection::Pinned(version),
false,
account,
)
}
pub fn xml_latest(account: AccountContext) -> Self {
Self::new(
OutputFormat::Xml,
ReportVersionSelection::LatestAvailable,
false,
account,
)
}
pub fn pdf(account: AccountContext) -> Self {
Self::new(
OutputFormat::Pdf,
ReportVersionSelection::DefaultForFamily,
false,
account,
)
}
pub fn pdf_with_xml(account: AccountContext) -> Self {
Self::new(
OutputFormat::Pdf,
ReportVersionSelection::DefaultForFamily,
true,
account,
)
}
fn validate(
&self,
family: &ReportFamily,
xml_only: bool,
verifying_allowed: bool,
) -> Result<()> {
self.account.validate()?;
if self.account.is_verifying() && !verifying_allowed {
return Err(Error::invalid_input(
"account",
"this generation operation is not available to verifying accounts",
));
}
if self.account.is_verifying() && self.format != OutputFormat::Pdf {
return Err(Error::invalid_input(
"format",
"verifying accounts may request only PDF output",
));
}
if xml_only && self.format != OutputFormat::Xml {
return Err(Error::invalid_input(
"format",
"this generation operation supports only XML output",
));
}
if self.attach_xml && self.format != OutputFormat::Pdf {
return Err(Error::invalid_input(
"attach_xml",
"attached XML requires a PDF primary output",
));
}
if self.attach_xml && self.account.is_verifying() {
return Err(Error::invalid_input(
"attach_xml",
"verifying accounts cannot request attached XML output",
));
}
if self.version == ReportVersionSelection::DefaultForFamily
&& family.default_version().is_none()
{
return Err(Error::invalid_input(
"version",
"no family-specific default version is known",
));
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ParcelNaturalKey {
pub cadastral_area: CadastralAreaCode,
pub number: ParcelNumber,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ParcelSelector {
Id(ParcelId),
NaturalKey(ParcelNaturalKey),
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum BuildingNumberKind {
Registration,
Evidence,
}
impl BuildingNumberKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Registration => "1",
Self::Evidence => "2",
}
}
}
macro_rules! report_number {
($name:ident, $integer:ty, $minimum:expr, $maximum:expr, $doc:literal) => {
#[doc = $doc]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $name($integer);
impl $name {
pub fn new(value: $integer) -> Result<Self> {
if !($minimum..=$maximum).contains(&value) {
return Err(Error::invalid_input(
"number",
concat!(
"value is outside the official range for ",
stringify!($name)
),
));
}
Ok(Self(value))
}
pub fn get(self) -> $integer {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
};
}
report_number!(
BuildingNumber,
u16,
1,
9_999,
"A building registration or evidence number in the range 1–9999."
);
report_number!(
UnitNumber,
u64,
0,
9_999_999_999,
"A unit number in the official range 0–9999999999."
);
report_number!(
OwnershipSheetNumber,
u32,
1,
999_999,
"An ownership-sheet number in the official range 1–999999."
);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct BuildingNaturalKey {
pub municipality_part: MunicipalityPartCode,
pub number_kind: BuildingNumberKind,
pub number: BuildingNumber,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum BuildingSelector {
Id(BuildingId),
NaturalKey(BuildingNaturalKey),
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct UnitNaturalKey {
pub building: BuildingNaturalKey,
pub unit_number: UnitNumber,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum UnitSelector {
Id(UnitId),
NaturalKey(UnitNaturalKey),
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ProceedingNumber(String);
impl ProceedingNumber {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if valid_proceeding_number(&value) {
Ok(Self(value))
} else {
Err(Error::invalid_input(
"proceeding_number",
"expected 1–3 letters, 1–8 digits, a four-digit year, and 2–3 workplace digits",
))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ProceedingNumber {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for ProceedingNumber {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
fn valid_proceeding_number(value: &str) -> bool {
let Some((kind, remainder)) = value.split_once('-') else {
return false;
};
let Some((sequence, remainder)) = remainder.split_once('/') else {
return false;
};
let Some((year, workplace)) = remainder.split_once('-') else {
return false;
};
(1..=3).contains(&kind.chars().count())
&& kind.chars().all(char::is_alphabetic)
&& (1..=8).contains(&sequence.len())
&& sequence.bytes().all(|byte| byte.is_ascii_digit())
&& year.len() == 4
&& year.bytes().all(|byte| byte.is_ascii_digit())
&& (2..=3).contains(&workplace.len())
&& workplace.bytes().all(|byte| byte.is_ascii_digit())
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ProceedingSelector {
Id(ProceedingId),
Number(ProceedingNumber),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReportObjectList {
Parcels(Vec<ParcelId>),
Buildings(Vec<BuildingId>),
Units(Vec<UnitId>),
BuildingRights(Vec<BuildingRightId>),
}
impl ReportObjectList {
pub fn kind_code(&self) -> &'static str {
match self {
Self::Parcels(_) => "PAR_S",
Self::Buildings(_) => "STA_S",
Self::Units(_) => "JED_S",
Self::BuildingRights(_) => "PRA_S",
}
}
pub fn len(&self) -> usize {
match self {
Self::Parcels(ids) => ids.len(),
Self::Buildings(ids) => ids.len(),
Self::Units(ids) => ids.len(),
Self::BuildingRights(ids) => ids.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn validate(&self) -> Result<()> {
if self.is_empty() {
return Err(Error::invalid_input(
"objects",
"the report object list cannot be empty",
));
}
let mut unique = HashSet::with_capacity(self.len());
let no_duplicates = match self {
Self::Parcels(ids) => ids.iter().all(|id| unique.insert(id.as_str())),
Self::Buildings(ids) => ids.iter().all(|id| unique.insert(id.as_str())),
Self::Units(ids) => ids.iter().all(|id| unique.insert(id.as_str())),
Self::BuildingRights(ids) => ids.iter().all(|id| unique.insert(id.as_str())),
};
if no_duplicates {
Ok(())
} else {
Err(Error::invalid_input(
"objects",
"the report object list contains duplicate identifiers",
))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MapCoordinates {
pub x: Decimal,
pub y: Decimal,
}
impl MapCoordinates {
pub fn new(x: Decimal, y: Decimal) -> Result<Self> {
let coordinates = Self { x, y };
coordinates.validate()?;
Ok(coordinates)
}
fn validate(&self) -> Result<()> {
validate_decimal("x", self.x, 9, 2)?;
validate_decimal("y", self.y, 8, 2)
}
}
fn validate_decimal(field: &'static str, value: Decimal, digits: usize, scale: u32) -> Result<()> {
let digits_used = value.mantissa().unsigned_abs().to_string().len();
if value.scale() > scale || digits_used > digits {
return Err(Error::invalid_input(
field,
"decimal exceeds the official total-digit or fractional-digit limit",
));
}
Ok(())
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DefinitionPointKind {
Parcel,
Building,
}
impl DefinitionPointKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Parcel => "p",
Self::Building => "s",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DefinitionPointQuery {
pub coordinates: MapCoordinates,
pub distance: Option<Decimal>,
pub kind: DefinitionPointKind,
}
impl DefinitionPointQuery {
fn validate(&self) -> Result<()> {
self.coordinates.validate()?;
if let Some(distance) = self.distance {
validate_decimal("distance", distance, 8, 2)?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum DefinitionPointsSelector {
CadastralArea(CadastralAreaCode),
Parcel(ParcelId),
Building(BuildingId),
Coordinates(DefinitionPointQuery),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OwnershipSheetSelector {
Id(OwnershipSheetId),
Number {
cadastral_area: CadastralAreaCode,
number: OwnershipSheetNumber,
},
Subject {
cadastral_area: CadastralAreaCode,
subject_id: SubjectId,
},
Objects {
objects: ReportObjectList,
partial: bool,
},
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum OwnershipOverviewTerritory {
Region(RegionCode),
Municipality(MunicipalityCode),
}
macro_rules! selected_report_request {
($name:ident, $selector:ty, $doc:literal) => {
#[doc = $doc]
#[derive(Clone, Debug, PartialEq)]
pub struct $name {
/// Operation-specific object selector.
pub selector: $selector,
pub as_of: Option<XmlDateTime>,
pub options: ReportOptions,
}
impl $name {
pub fn new(selector: $selector, options: ReportOptions) -> Self {
Self {
selector,
as_of: None,
options,
}
}
}
};
}
selected_report_request!(
ParcelInfoRequest,
ParcelSelector,
"Request for `generujInfoOParcelach`."
);
selected_report_request!(
BuildingInfoRequest,
BuildingSelector,
"Request for `generujInfoOStavbach`."
);
selected_report_request!(
UnitInfoRequest,
UnitSelector,
"Request for `generujInfoOJednotkach`."
);
#[derive(Clone, Debug, PartialEq)]
pub struct BuildingRightInfoRequest {
pub building_right_id: BuildingRightId,
pub as_of: Option<XmlDateTime>,
pub options: ReportOptions,
}
impl BuildingRightInfoRequest {
pub fn new(building_right_id: BuildingRightId, options: ReportOptions) -> Self {
Self {
building_right_id,
as_of: None,
options,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ProceedingInfoRequest {
pub selector: ProceedingSelector,
pub options: ReportOptions,
}
impl ProceedingInfoRequest {
pub fn new(selector: ProceedingSelector, options: ReportOptions) -> Self {
Self { selector, options }
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct DefinitionPointsRequest {
pub selector: DefinitionPointsSelector,
pub options: ReportOptions,
}
impl DefinitionPointsRequest {
pub fn new(selector: DefinitionPointsSelector, options: ReportOptions) -> Self {
Self { selector, options }
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct OwnershipSheetRequest {
pub selector: OwnershipSheetSelector,
pub as_of: Option<XmlDateTime>,
pub options: ReportOptions,
}
impl OwnershipSheetRequest {
pub fn new(selector: OwnershipSheetSelector, options: ReportOptions) -> Self {
Self {
selector,
as_of: None,
options,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct OwnershipOverviewRequest {
pub subject_id: SubjectId,
pub territory: Option<OwnershipOverviewTerritory>,
pub legal_relation: Option<LegalRelationCode>,
pub as_of: Option<XmlDateTime>,
pub options: ReportOptions,
}
impl OwnershipOverviewRequest {
pub fn new(subject_id: SubjectId, options: ReportOptions) -> Self {
Self {
subject_id,
territory: None,
legal_relation: None,
as_of: None,
options,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RightsRecordSubjectKind {
NaturalPerson,
LegalPerson,
}
impl RightsRecordSubjectKind {
pub fn as_str(self) -> &'static str {
match self {
Self::NaturalPerson => "OFO",
Self::LegalPerson => "OPO",
}
}
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct RightsRecordIdentifier(String);
impl RightsRecordIdentifier {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
validate_character_length("rc_ico", &value, 1, 10)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for RightsRecordIdentifier {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("RightsRecordIdentifier([REDACTED])")
}
}
#[derive(Clone, PartialEq)]
pub struct RightsRecordRequest {
pub subject_kind: RightsRecordSubjectKind,
pub name: String,
pub identifier: RightsRecordIdentifier,
pub options: ReportOptions,
}
impl fmt::Debug for RightsRecordRequest {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RightsRecordRequest")
.field("subject_kind", &self.subject_kind)
.field("name", &"[REDACTED]")
.field("identifier", &self.identifier)
.field("options", &self.options)
.finish()
}
}
impl RightsRecordRequest {
pub fn new(
subject_kind: RightsRecordSubjectKind,
name: impl Into<String>,
identifier: RightsRecordIdentifier,
options: ReportOptions,
) -> Self {
Self {
subject_kind,
name: name.into(),
identifier,
options,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AccountStatementRequest {
pub from: XmlDateTime,
pub to: Option<XmlDateTime>,
pub format: OutputFormat,
pub version: ReportVersionSelection,
pub account: AccountKind,
}
impl AccountStatementRequest {
pub fn new(from: XmlDateTime, format: OutputFormat) -> Self {
Self {
from,
to: None,
format,
version: ReportVersionSelection::DefaultForFamily,
account: AccountKind::Paying,
}
}
pub fn with_account(mut self, account: AccountKind) -> Self {
self.account = account;
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PricesByPropertiesRequest {
pub objects: ReportObjectList,
pub as_of: Option<XmlDateTime>,
pub options: ReportOptions,
}
impl PricesByPropertiesRequest {
pub fn new(objects: ReportObjectList, options: ReportOptions) -> Self {
Self {
objects,
as_of: None,
options,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PricesByProceedingRequest {
pub selector: ProceedingSelector,
pub options: ReportOptions,
}
impl PricesByProceedingRequest {
pub fn new(selector: ProceedingSelector, options: ReportOptions) -> Self {
Self { selector, options }
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PricesByCadastralAreaRequest {
pub cadastral_area: CadastralAreaCode,
pub year: u16,
pub month_from: u8,
pub month_to: u8,
pub account: AccountContext,
}
impl PricesByCadastralAreaRequest {
pub fn new(
cadastral_area: CadastralAreaCode,
year: u16,
month_from: u8,
month_to: u8,
account: AccountContext,
) -> Self {
Self {
cadastral_area,
year,
month_from,
month_to,
account,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MapPaperFormat {
A3,
A4,
}
impl MapPaperFormat {
pub fn as_str(self) -> &'static str {
match self {
Self::A3 => "A3",
Self::A4 => "A4",
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MapScale {
Scale500,
Scale1000,
Scale2000,
}
impl MapScale {
pub fn as_u16(self) -> u16 {
match self {
Self::Scale500 => 500,
Self::Scale1000 => 1_000,
Self::Scale2000 => 2_000,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum CadastralMapSelector {
Parcel(ParcelId),
Coordinates(MapCoordinates),
}
#[derive(Clone, Debug, PartialEq)]
pub struct CadastralMapRequest {
pub selector: CadastralMapSelector,
pub paper: MapPaperFormat,
pub landscape: bool,
pub scale: MapScale,
pub easements: bool,
pub as_of: Option<XmlDateTime>,
pub account: AccountContext,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollectionDocumentRequest {
pub document_id: DocumentId,
pub account: AccountContext,
}
impl CollectionDocumentRequest {
pub fn new(document_id: DocumentId, account: AccountContext) -> Self {
Self {
document_id,
account,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeometricPlanRequest {
pub document_id: DocumentId,
pub account: AccountContext,
}
impl GeometricPlanRequest {
pub fn new(document_id: DocumentId, account: AccountContext) -> Self {
Self {
document_id,
account,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GenerateReport {
OwnershipSheet(OwnershipSheetRequest),
CadastralMap(CadastralMapRequest),
ParcelInfo(ParcelInfoRequest),
BuildingInfo(BuildingInfoRequest),
UnitInfo(UnitInfoRequest),
BuildingRightInfo(BuildingRightInfoRequest),
ProceedingInfo(ProceedingInfoRequest),
DefinitionPoints(DefinitionPointsRequest),
OwnershipOverview(OwnershipOverviewRequest),
OwnershipOverviewWithProperties(OwnershipOverviewRequest),
RightsRecord(RightsRecordRequest),
AccountStatement(AccountStatementRequest),
PricesByProperties(PricesByPropertiesRequest),
PricesByProceeding(PricesByProceedingRequest),
PricesByCadastralArea(PricesByCadastralAreaRequest),
CollectionDocument(CollectionDocumentRequest),
GeometricPlan(GeometricPlanRequest),
}
impl GenerateReport {
pub fn family(&self) -> Option<ReportFamily> {
Some(match self {
Self::OwnershipSheet(_) => ReportFamily::OwnershipSheet,
Self::ParcelInfo(_) => ReportFamily::ParcelInfo,
Self::BuildingInfo(_) => ReportFamily::BuildingInfo,
Self::UnitInfo(_) => ReportFamily::UnitInfo,
Self::BuildingRightInfo(_) => ReportFamily::BuildingRightInfo,
Self::ProceedingInfo(_) => ReportFamily::ProceedingInfo,
Self::DefinitionPoints(_) => ReportFamily::DefinitionPoints,
Self::OwnershipOverview(_) => ReportFamily::OwnershipOverview,
Self::OwnershipOverviewWithProperties(_) => {
ReportFamily::OwnershipOverviewWithProperties
}
Self::RightsRecord(_) => ReportFamily::RightsRecord,
Self::AccountStatement(_) => ReportFamily::AccountStatement,
Self::PricesByProperties(_) => ReportFamily::PricesByProperties,
Self::PricesByProceeding(_) => ReportFamily::PricesByProceeding,
Self::CadastralMap(_)
| Self::PricesByCadastralArea(_)
| Self::CollectionDocument(_)
| Self::GeometricPlan(_) => return None,
})
}
pub fn validate(&self) -> Result<()> {
match self {
Self::OwnershipSheet(request) => {
if let OwnershipSheetSelector::Objects { objects, .. } = &request.selector {
objects.validate()?;
}
request
.options
.validate(&ReportFamily::OwnershipSheet, false, true)
}
Self::CadastralMap(request) => {
if let CadastralMapSelector::Coordinates(coordinates) = &request.selector {
coordinates.validate()?;
}
validate_fixed_account(&request.account, true)
}
Self::ParcelInfo(request) => {
request
.options
.validate(&ReportFamily::ParcelInfo, false, false)
}
Self::BuildingInfo(request) => {
request
.options
.validate(&ReportFamily::BuildingInfo, false, false)
}
Self::UnitInfo(request) => {
request
.options
.validate(&ReportFamily::UnitInfo, false, false)
}
Self::BuildingRightInfo(request) => {
request
.options
.validate(&ReportFamily::BuildingRightInfo, false, false)
}
Self::ProceedingInfo(request) => {
request
.options
.validate(&ReportFamily::ProceedingInfo, false, false)
}
Self::DefinitionPoints(request) => {
if let DefinitionPointsSelector::Coordinates(query) = &request.selector {
query.validate()?;
}
request
.options
.validate(&ReportFamily::DefinitionPoints, true, false)
}
Self::OwnershipOverview(request) => {
validate_overview(request)?;
request
.options
.validate(&ReportFamily::OwnershipOverview, false, false)
}
Self::OwnershipOverviewWithProperties(request) => {
validate_overview(request)?;
request.options.validate(
&ReportFamily::OwnershipOverviewWithProperties,
false,
true,
)
}
Self::RightsRecord(request) => {
validate_character_length("name", &request.name, 1, 255)?;
request
.options
.validate(&ReportFamily::RightsRecord, false, true)
}
Self::AccountStatement(request) => {
if request.account == AccountKind::Verifying && request.format != OutputFormat::Pdf
{
return Err(Error::invalid_input(
"format",
"verifying accounts may request only PDF account statements",
));
}
if request.version == ReportVersionSelection::DefaultForFamily
&& ReportFamily::AccountStatement.default_version().is_none()
{
return Err(Error::invalid_input(
"version",
"no family-specific default version is known",
));
}
Ok(())
}
Self::PricesByProperties(request) => {
request.objects.validate()?;
request
.options
.validate(&ReportFamily::PricesByProperties, false, false)
}
Self::PricesByProceeding(request) => {
request
.options
.validate(&ReportFamily::PricesByProceeding, false, false)
}
Self::PricesByCadastralArea(request) => {
if !(1_789..=9_999).contains(&request.year) {
return Err(Error::invalid_input("year", "year must be in 1789..=9999"));
}
if !(1..=12).contains(&request.month_from) || !(1..=12).contains(&request.month_to)
{
return Err(Error::invalid_input("month", "months must be in 1..=12"));
}
if request.month_from > request.month_to {
return Err(Error::invalid_input(
"month_to",
"last month cannot precede the first month",
));
}
validate_fixed_account(&request.account, false)
}
Self::CollectionDocument(request) => validate_fixed_account(&request.account, true),
Self::GeometricPlan(request) => validate_fixed_account(&request.account, false),
}
}
}
fn validate_fixed_account(account: &AccountContext, verifying_allowed: bool) -> Result<()> {
account.validate()?;
if account.is_verifying() && !verifying_allowed {
Err(Error::invalid_input(
"account",
"this generation operation is not available to verifying accounts",
))
} else {
Ok(())
}
}
fn validate_overview(request: &OwnershipOverviewRequest) -> Result<()> {
if let Some(code) = &request.legal_relation
&& !(1..=4).contains(&code.as_str().chars().count())
{
return Err(Error::invalid_input(
"legal_relation",
"legal-relation code must contain 1–4 characters",
));
}
Ok(())
}
fn validate_character_length(
field: &'static str,
value: &str,
minimum: usize,
maximum: usize,
) -> Result<()> {
let length = value.chars().count();
if (minimum..=maximum).contains(&length) {
Ok(())
} else {
Err(Error::invalid_input(
field,
format!("expected {minimum}–{maximum} characters"),
))
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ReportState {
Waiting,
Creating,
Signing,
Processed,
CreationFailed,
ProcessingFailed,
Charged,
Cancelled,
Other(String),
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ReportStateClass {
Pending,
Ready,
Failed,
Cancelled,
Unknown,
}
impl ReportState {
pub fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
match raw.as_str() {
"čeká" => Self::Waiting,
"vytváří se" => Self::Creating,
"podepisuje se" => Self::Signing,
"zpracován" => Self::Processed,
"chyba při vytváření" => Self::CreationFailed,
"chyba při zpracování" => Self::ProcessingFailed,
"zaúčtován" => Self::Charged,
"zrušen" => Self::Cancelled,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Waiting => "čeká",
Self::Creating => "vytváří se",
Self::Signing => "podepisuje se",
Self::Processed => "zpracován",
Self::CreationFailed => "chyba při vytváření",
Self::ProcessingFailed => "chyba při zpracování",
Self::Charged => "zaúčtován",
Self::Cancelled => "zrušen",
Self::Other(raw) => raw,
}
}
pub fn classification(&self) -> ReportStateClass {
match self {
Self::Waiting | Self::Creating | Self::Signing => ReportStateClass::Pending,
Self::Processed | Self::Charged => ReportStateClass::Ready,
Self::CreationFailed | Self::ProcessingFailed => ReportStateClass::Failed,
Self::Cancelled => ReportStateClass::Cancelled,
Self::Other(_) => ReportStateClass::Unknown,
}
}
pub fn is_pending(&self) -> bool {
self.classification() == ReportStateClass::Pending
}
pub fn is_ready(&self) -> bool {
self.classification() == ReportStateClass::Ready
}
pub fn is_failed(&self) -> bool {
self.classification() == ReportStateClass::Failed
}
pub fn is_cancelled(&self) -> bool {
self.classification() == ReportStateClass::Cancelled
}
pub fn is_unknown(&self) -> bool {
self.classification() == ReportStateClass::Unknown
}
}
impl fmt::Display for ReportState {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ReportFormat {
Pdf,
Xml,
Html,
Zip,
Other(String),
}
impl ReportFormat {
pub fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
match raw.as_str() {
"pdf" => Self::Pdf,
"xml" => Self::Xml,
"html" => Self::Html,
"zip" => Self::Zip,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Pdf => "pdf",
Self::Xml => "xml",
Self::Html => "html",
Self::Zip => "zip",
Self::Other(raw) => raw,
}
}
}
impl fmt::Display for ReportFormat {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct ReportMetadata {
pub id: ReportId,
pub name: String,
pub units: Option<Decimal>,
pub pages: Option<u16>,
pub price: Option<Czk>,
pub requested_at: XmlDateTime,
pub started_at: Option<XmlDateTime>,
pub created_at: Option<XmlDateTime>,
pub parent_id: Option<ReportId>,
pub child_ids: Vec<ReportId>,
pub state: ReportState,
pub format: ReportFormat,
pub version: Option<ReportVersion>,
pub electronic_seal: Option<bool>,
pub timestamp: Option<bool>,
}
impl fmt::Debug for ReportMetadata {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ReportMetadata")
.field("id", &self.id)
.field("name", &"[REDACTED]")
.field("state", &self.state)
.field("format", &self.format)
.field("version", &self.version)
.field("child_count", &self.child_ids.len())
.finish_non_exhaustive()
}
}
impl ReportMetadata {
pub fn id(&self) -> &ReportId {
&self.id
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ReportBatch {
pub reports: Vec<ReportMetadata>,
}
impl ReportBatch {
pub fn new(reports: Vec<ReportMetadata>) -> Self {
Self { reports }
}
pub fn as_slice(&self) -> &[ReportMetadata] {
&self.reports
}
pub fn into_single_report(self) -> Result<ReportMetadata> {
if self.reports.len() == 1 {
Ok(self
.reports
.into_iter()
.next()
.expect("length checked immediately before extraction"))
} else {
Err(Error::UnexpectedReportBatch {
ids: self
.reports
.iter()
.map(|report| report.id.clone())
.collect(),
})
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ChargeApproval {
FreeOnly,
UpTo(Czk),
Any,
}
impl ChargeApproval {
pub fn up_to(maximum: Czk) -> Self {
Self::UpTo(maximum)
}
pub fn accepts(&self, price: Option<Czk>) -> bool {
let Some(price) = price else {
return false;
};
match self {
Self::FreeOnly => price == Czk::ZERO,
Self::UpTo(maximum) => price.as_decimal() <= maximum.as_decimal(),
Self::Any => true,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WaitOptions {
pub initial_delay: Duration,
pub poll_interval: Duration,
pub max_wait: Duration,
pub max_poll_interval: Option<Duration>,
}
impl WaitOptions {
pub fn validate(&self) -> Result<()> {
if self.poll_interval.is_zero() {
return Err(Error::invalid_input(
"poll_interval",
"poll interval must be greater than zero",
));
}
if self
.max_poll_interval
.is_some_and(|interval| interval.is_zero())
{
return Err(Error::invalid_input(
"max_poll_interval",
"backoff cap must be greater than zero when supplied",
));
}
Ok(())
}
}
impl Default for WaitOptions {
fn default() -> Self {
Self {
initial_delay: Duration::from_secs(2),
poll_interval: Duration::from_secs(2),
max_wait: Duration::from_secs(120),
max_poll_interval: None,
}
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct DownloadedReport {
pub metadata: ReportMetadata,
pub messages: Vec<ServiceMessage>,
pub bytes: Bytes,
}
impl DownloadedReport {
pub fn id(&self) -> &ReportId {
self.metadata.id()
}
pub fn as_bytes(&self) -> &Bytes {
&self.bytes
}
}
impl fmt::Debug for DownloadedReport {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DownloadedReport")
.field("metadata", &self.metadata)
.field("message_count", &self.messages.len())
.field("byte_len", &self.bytes.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn paying_xml() -> ReportOptions {
ReportOptions::xml_default(AccountContext::Paying)
}
fn parcel_request(options: ReportOptions) -> GenerateReport {
GenerateReport::ParcelInfo(ParcelInfoRequest::new(
ParcelSelector::Id(ParcelId::new("123").unwrap()),
options,
))
}
#[test]
fn request_and_metadata_debug_redact_sensitive_text() {
let request = RightsRecordRequest::new(
RightsRecordSubjectKind::NaturalPerson,
"sensitive-person-name",
RightsRecordIdentifier::new("private-id").unwrap(),
ReportOptions::xml_default(AccountContext::Free {
cislo_jednaci: "sensitive-file-reference".to_owned(),
ucel_kod: 1,
}),
);
let request_debug = format!("{request:?}");
for sentinel in [
"sensitive-person-name",
"private-id",
"sensitive-file-reference",
] {
assert!(!request_debug.contains(sentinel));
}
let metadata = ReportMetadata {
id: ReportId::new("123").unwrap(),
name: "sensitive-report-name".to_owned(),
units: None,
pages: None,
price: None,
requested_at: XmlDateTime::new("2026-01-01T00:00:00Z").unwrap(),
started_at: None,
created_at: None,
parent_id: None,
child_ids: Vec::new(),
state: ReportState::Charged,
format: ReportFormat::Pdf,
version: None,
electronic_seal: None,
timestamp: None,
};
let metadata_debug = format!("{metadata:?}");
assert!(!metadata_debug.contains("sensitive-report-name"));
assert!(!metadata_debug.contains("123"));
}
#[test]
fn report_versions_are_lexical_and_open() {
assert_eq!(ReportVersion::new("1.0").unwrap(), ReportVersion::V1_0);
assert_eq!(ReportVersion::new("3.0").unwrap(), ReportVersion::V3_0);
assert_eq!(ReportVersion::new("03.00").unwrap().as_str(), "03.00");
assert!(ReportVersion::new("1").is_err());
assert!(ReportVersion::new("1.0.1").is_err());
assert!(ReportVersion::new("1.a").is_err());
}
#[test]
fn all_thirteen_families_have_unique_official_codes() {
let mut codes: Vec<_> = ReportFamily::ALL.iter().map(ReportFamily::as_str).collect();
codes.sort_unstable();
codes.dedup();
assert_eq!(ReportFamily::ALL.len(), 13);
assert_eq!(codes.len(), 13);
assert_eq!(
ReportFamily::from_raw("InformaceOParcelach"),
ReportFamily::ParcelInfo
);
assert_eq!(ReportFamily::from_raw("Future").as_str(), "Future");
}
#[test]
fn defaults_are_family_specific_and_pinned() {
assert_eq!(
ReportFamily::OwnershipSheet.default_version(),
Some(ReportVersion::V3_0)
);
for family in ReportFamily::ALL {
if *family != ReportFamily::OwnershipSheet {
assert_eq!(family.default_version(), Some(ReportVersion::V1_0));
}
}
assert_eq!(ReportFamily::Other("future".into()).default_version(), None);
assert_eq!(
paying_xml().version,
ReportVersionSelection::DefaultForFamily
);
assert_eq!(
ReportOptions::xml_latest(AccountContext::Paying).version,
ReportVersionSelection::LatestAvailable
);
}
#[test]
fn account_fields_and_verifying_combinations_are_validated() {
let invalid_free = AccountContext::Free {
cislo_jednaci: String::new(),
ucel_kod: 1,
};
assert!(
parcel_request(ReportOptions::xml_default(invalid_free))
.validate()
.is_err()
);
let invalid_purpose = AccountContext::Free {
cislo_jednaci: "A-1".into(),
ucel_kod: 0,
};
assert!(
parcel_request(ReportOptions::xml_default(invalid_purpose))
.validate()
.is_err()
);
let verifying = AccountContext::Verifying {
poradove_cislo: "42".into(),
overovaci_dolozka: true,
};
assert!(
parcel_request(ReportOptions::pdf(verifying.clone()))
.validate()
.is_err()
);
let sheet = GenerateReport::OwnershipSheet(OwnershipSheetRequest::new(
OwnershipSheetSelector::Id(OwnershipSheetId::new("1").unwrap()),
ReportOptions::pdf(verifying.clone()),
));
assert!(sheet.validate().is_ok());
let sheet_xml = GenerateReport::OwnershipSheet(OwnershipSheetRequest::new(
OwnershipSheetSelector::Id(OwnershipSheetId::new("1").unwrap()),
ReportOptions::xml_default(verifying),
));
assert!(sheet_xml.validate().is_err());
let statement = GenerateReport::AccountStatement(
AccountStatementRequest::new(
XmlDateTime::new("2026-01-01T00:00:00Z").unwrap(),
OutputFormat::Xml,
)
.with_account(AccountKind::Verifying),
);
assert!(statement.validate().is_err());
let pdf = GenerateReport::AccountStatement(
AccountStatementRequest::new(
XmlDateTime::new("2026-01-01T00:00:00Z").unwrap(),
OutputFormat::Pdf,
)
.with_account(AccountKind::Verifying),
);
assert!(pdf.validate().is_ok());
}
#[test]
fn xml_only_and_attached_xml_combinations_fail_before_serialization() {
let points = GenerateReport::DefinitionPoints(DefinitionPointsRequest::new(
DefinitionPointsSelector::CadastralArea(CadastralAreaCode::new("1").unwrap()),
ReportOptions::pdf(AccountContext::Paying),
));
assert!(points.validate().is_err());
assert!(
parcel_request(ReportOptions::new(
OutputFormat::Xml,
ReportVersionSelection::DefaultForFamily,
true,
AccountContext::Paying,
))
.validate()
.is_err()
);
assert!(
parcel_request(ReportOptions::pdf_with_xml(AccountContext::Paying))
.validate()
.is_ok()
);
}
#[test]
fn object_lists_are_homogeneous_nonempty_and_unique() {
assert!(ReportObjectList::Parcels(Vec::new()).validate().is_err());
assert!(
ReportObjectList::Parcels(vec![
ParcelId::new("1").unwrap(),
ParcelId::new("1").unwrap(),
])
.validate()
.is_err()
);
assert_eq!(
ReportObjectList::BuildingRights(vec![BuildingRightId::new("9").unwrap()]).kind_code(),
"PRA_S"
);
}
#[test]
fn proceeding_numbers_and_decimal_map_fields_follow_xsd_limits() {
assert!(ProceedingNumber::new("V-123/2015-101").is_ok());
assert!(ProceedingNumber::new("ABC-1/2015-01").is_ok());
assert!(ProceedingNumber::new("V123/2015-101").is_err());
assert!(ProceedingNumber::new("V-123456789/2015-101").is_err());
assert!(
MapCoordinates::new(Decimal::new(-123456789, 2), Decimal::new(-12345678, 2),).is_ok()
);
assert!(MapCoordinates::new(Decimal::new(1, 3), Decimal::ZERO).is_err());
assert!(MapCoordinates::new(Decimal::new(1234567890, 2), Decimal::ZERO).is_err());
}
#[test]
fn monthly_period_and_fixed_output_account_rules_are_checked() {
let request = GenerateReport::PricesByCadastralArea(PricesByCadastralAreaRequest::new(
CadastralAreaCode::new("1").unwrap(),
2026,
11,
10,
AccountContext::Paying,
));
assert!(request.validate().is_err());
let request = GenerateReport::GeometricPlan(GeometricPlanRequest::new(
DocumentId::new("1").unwrap(),
AccountContext::Verifying {
poradove_cislo: "1".into(),
overovaci_dolozka: false,
},
));
assert!(request.validate().is_err());
}
#[test]
fn every_known_report_state_has_stable_classification_and_raw_text() {
let cases = [
("čeká", ReportState::Waiting, ReportStateClass::Pending),
(
"vytváří se",
ReportState::Creating,
ReportStateClass::Pending,
),
(
"podepisuje se",
ReportState::Signing,
ReportStateClass::Pending,
),
("zpracován", ReportState::Processed, ReportStateClass::Ready),
(
"chyba při vytváření",
ReportState::CreationFailed,
ReportStateClass::Failed,
),
(
"chyba při zpracování",
ReportState::ProcessingFailed,
ReportStateClass::Failed,
),
("zaúčtován", ReportState::Charged, ReportStateClass::Ready),
(
"zrušen",
ReportState::Cancelled,
ReportStateClass::Cancelled,
),
];
for (raw, state, class) in cases {
assert_eq!(ReportState::from_raw(raw), state);
assert_eq!(state.as_str(), raw);
assert_eq!(state.classification(), class);
}
let unknown = ReportState::from_raw("budouci stav");
assert!(unknown.is_unknown());
assert_eq!(unknown.as_str(), "budouci stav");
assert_eq!(ReportFormat::from_raw("future").as_str(), "future");
}
#[test]
fn approval_requires_a_price_and_compares_exact_amounts() {
let zero = Czk::ZERO;
let ten = Czk::from_major_units(10);
let above = Czk::from_str("10.01").unwrap();
assert!(ChargeApproval::FreeOnly.accepts(Some(zero)));
assert!(!ChargeApproval::FreeOnly.accepts(Some(ten)));
assert!(ChargeApproval::UpTo(ten).accepts(Some(ten)));
assert!(!ChargeApproval::UpTo(ten).accepts(Some(above)));
assert!(ChargeApproval::Any.accepts(Some(above)));
assert!(!ChargeApproval::Any.accepts(None));
}
#[test]
fn wait_defaults_are_bounded_and_validated() {
let options = WaitOptions::default();
assert_eq!(options.initial_delay, Duration::from_secs(2));
assert_eq!(options.poll_interval, Duration::from_secs(2));
assert_eq!(options.max_wait, Duration::from_secs(120));
assert_eq!(options.max_poll_interval, None);
assert!(options.validate().is_ok());
let invalid = WaitOptions {
poll_interval: Duration::ZERO,
..options
};
assert!(invalid.validate().is_err());
}
}