wsdp 0.1.0

Async high-level client for ČÚZK WSDP real-estate cadastre services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::fmt;
use std::str::FromStr;

use rust_decimal::Decimal;

use super::common::positive_integer_digits;
use super::id::{CadastralAreaCode, MunicipalityPartCode, OwnershipSheetId, ParcelId, UnitId};
use super::search::{
    AuthorizedSubject, Building, BuildingRight, BuildingTypeCode, CadastralAreaReference,
    Ownership, Parcel, Unit,
};
use crate::{Error, Result};

/// A building number used by the information natural key (`CisloStavbyType`).
///
/// This is not an internal `BuildingId`; the XSD independently permits 30 digits.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct UnitBuildingNumber(String);

impl UnitBuildingNumber {
    /// Validates a positive decimal integer of at most 30 digits.
    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(
                "building_number",
                "expected a positive decimal integer with at most 30 digits",
            ));
        };
        if digits.len() > 30 {
            return Err(Error::invalid_input(
                "building_number",
                "expected a positive decimal integer with at most 30 digits",
            ));
        }
        Ok(Self(value))
    }

    /// Returns the exact original number.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for UnitBuildingNumber {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for UnitBuildingNumber {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for UnitBuildingNumber {
    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)
    }
}

/// `dejMBRParcel` request. At least one parcel ID is required.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelBoundingBoxRequest {
    /// Internal parcel IDs, encoded as repeated `parcelaId` elements.
    pub parcel_ids: Vec<ParcelId>,
}

impl ParcelBoundingBoxRequest {
    /// Validates the XSD's non-empty ID list.
    pub fn new(parcel_ids: Vec<ParcelId>) -> Result<Self> {
        let value = Self { parcel_ids };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if self.parcel_ids.is_empty() {
            return Err(Error::invalid_input(
                "parcel_ids",
                "at least one parcel ID is required",
            ));
        }
        Ok(())
    }
}

/// Unit-overview lookup by internal ID or natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UnitOverviewSelector {
    /// Internal unit ID (`idJednotky`).
    Id(UnitId),
    /// Municipality part, building type/number, and unit number.
    Number(UnitOverviewNaturalKey),
}

/// Natural key accepted by `dejInfoOJednotce`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitOverviewNaturalKey {
    /// Municipality-part code.
    pub municipality_part: MunicipalityPartCode,
    /// Building-type code.
    pub building_type: BuildingTypeCode,
    /// Building number, which is distinct from an internal building ID.
    pub building_number: UnitBuildingNumber,
    /// Unit number in 0–9999999999.
    pub unit_number: u64,
}

impl UnitOverviewNaturalKey {
    /// Validates the unit-number range from `CisloJednotkyType`.
    pub fn new(
        municipality_part: MunicipalityPartCode,
        building_type: BuildingTypeCode,
        building_number: UnitBuildingNumber,
        unit_number: u64,
    ) -> Result<Self> {
        let value = Self {
            municipality_part,
            building_type,
            building_number,
            unit_number,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if self.unit_number > 9_999_999_999 {
            return Err(Error::invalid_input(
                "unit_number",
                "unit number must be at most 9999999999",
            ));
        }
        Ok(())
    }
}

/// `dejInfoOJednotce` request. Account eligibility remains a server decision.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitOverviewRequest {
    /// ID/natural-key choice.
    pub selector: UnitOverviewSelector,
}

impl UnitOverviewRequest {
    pub(crate) fn validate(&self) -> Result<()> {
        match &self.selector {
            UnitOverviewSelector::Id(_) => Ok(()),
            UnitOverviewSelector::Number(key) => key.validate(),
        }
    }
}

/// Ownership-sheet preview lookup by internal ID or natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OwnershipSheetPreviewSelector {
    /// Internal ownership-sheet ID (`lvId`).
    Id(OwnershipSheetId),
    /// Cadastral area and ownership-sheet number.
    Number(OwnershipSheetNaturalKey),
}

/// Natural key accepted by `dejNahledLV`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OwnershipSheetNaturalKey {
    /// Cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Ownership-sheet number in 1–999999.
    pub sheet_number: u32,
}

impl OwnershipSheetNaturalKey {
    /// Validates the ownership-sheet number range.
    pub fn new(cadastral_area: CadastralAreaCode, sheet_number: u32) -> Result<Self> {
        let value = Self {
            cadastral_area,
            sheet_number,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if !(1..=999_999).contains(&self.sheet_number) {
            return Err(Error::invalid_input(
                "sheet_number",
                "ownership-sheet number must be in 1..=999999",
            ));
        }
        Ok(())
    }
}

/// `dejNahledLV` request for current, limited LV data. Account eligibility applies.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OwnershipSheetPreviewRequest {
    /// ID/natural-key choice.
    pub selector: OwnershipSheetPreviewSelector,
}

impl OwnershipSheetPreviewRequest {
    pub(crate) fn validate(&self) -> Result<()> {
        match &self.selector {
            OwnershipSheetPreviewSelector::Id(_) => Ok(()),
            OwnershipSheetPreviewSelector::Number(key) => key.validate(),
        }
    }
}

/// One of the three WSDP 3.1 `informace` requests.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InformationRequest {
    /// `dejMBRParcel`.
    ParcelBoundingBoxes(ParcelBoundingBoxRequest),
    /// `dejInfoOJednotce`.
    UnitOverview(UnitOverviewRequest),
    /// `dejNahledLV`.
    OwnershipSheetPreview(OwnershipSheetPreviewRequest),
}

impl InformationRequest {
    pub(crate) fn validate(&self) -> Result<()> {
        match self {
            Self::ParcelBoundingBoxes(request) => request.validate(),
            Self::UnitOverview(request) => request.validate(),
            Self::OwnershipSheetPreview(request) => request.validate(),
        }
    }
}

/// Optional GML coordinate-reference metadata from `SRSReferenceGroup`.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SpatialReference {
    /// CRS URI or well-known identifier (`srsName`).
    pub name: Option<String>,
    /// Coordinate dimension (`srsDimension`).
    pub dimension: Option<u32>,
    /// Ordered axis labels (`axisLabels`).
    pub axis_labels: Option<Vec<String>>,
    /// Ordered unit labels (`uomLabels`).
    pub unit_labels: Option<Vec<String>>,
}

/// One two-dimensional S-JTSK position in explicit **Y, X** order.
///
/// Coordinates are exact decimals; no binary floating-point conversion is used.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SJtskPoint {
    /// S-JTSK Y ordinate (the first value on the wire).
    pub y: Decimal,
    /// S-JTSK X ordinate (the second value on the wire).
    pub x: Decimal,
    /// Metadata placed directly on `lowerCorner`, `upperCorner`, or `pos`.
    pub reference: SpatialReference,
}

/// The GML representation used for the two envelope corners.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EnvelopeEncoding {
    /// Preferred `lowerCorner` and `upperCorner` elements.
    Corners,
    /// Deprecated pair of `pos` elements, normalized into lower and upper points.
    Positions,
    /// Deprecated `coordinates` element, parsed using its explicit separators.
    Coordinates {
        /// Decimal separator, defaulting to `.`.
        decimal_separator: String,
        /// Separator between Y and X, defaulting to `,`.
        coordinate_separator: String,
        /// Separator between positions, defaulting to a space.
        tuple_separator: String,
    },
}

/// A GML envelope with normalized lower and upper S-JTSK **Y, X** corners.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BoundingEnvelope {
    /// Corner containing the minimal ordinates.
    pub lower: SJtskPoint,
    /// Corner containing the maximal ordinates.
    pub upper: SJtskPoint,
    /// Original GML corner representation and deprecated-format separators.
    pub encoding: EnvelopeEncoding,
    /// CRS metadata on the `Envelope` itself.
    pub reference: SpatialReference,
}

/// A legitimate GML `Null` geometry and its optional-reason text.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GmlNull {
    /// The `gml:Null` value, retained verbatim (including an empty anyURI value).
    pub reason: String,
}

/// The required GML `boundedBy` choice.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BoundingGeometry {
    /// A two-dimensional envelope.
    Envelope(Box<BoundingEnvelope>),
    /// No geometry, represented explicitly rather than as a missing result.
    Null(GmlNull),
}

/// One MBR entry and all parcel IDs grouped under it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelBoundingBox {
    /// One or more parcel IDs from `IDList/ID`; this response element is `xs:string`.
    pub parcel_ids: Vec<String>,
    /// Fixed XSD object-kind attribute, normally `PAR_S`.
    pub id_kind: String,
    /// Envelope or explicit GML null geometry.
    pub geometry: BoundingGeometry,
    /// Optional `nilReason` on `gml:boundedBy`.
    pub nil_reason: Option<String>,
}

/// Response to `dejMBRParcel`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelBoundingBoxResponse {
    /// `None` means optional `infoList` was absent; `Some(vec![])` means it was
    /// present with an empty `MBRList`.
    pub entries: Option<Vec<ParcelBoundingBox>>,
}

/// Lightweight ownership-sheet identity returned by information operations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OwnershipSheet {
    /// Internal ownership-sheet ID.
    pub id: OwnershipSheetId,
    /// Cadastral area with optional code and name.
    pub cadastral_area: CadastralAreaReference,
    /// Ownership-sheet number.
    pub number: u32,
}

/// A unit extended with display names for its type and use (`JednotkaLongType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DetailedUnit {
    /// All base `JednotkaType` fields.
    pub unit: Unit,
    /// Unit-type display name.
    pub type_name: Option<String>,
    /// Unit-use display name.
    pub use_name: Option<String>,
}

/// Response to `dejInfoOJednotce`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitOverviewResponse {
    /// Related ownership sheet, when supplied.
    pub ownership_sheet: Option<OwnershipSheet>,
    /// Unit with optional display names, when supplied.
    pub unit: Option<DetailedUnit>,
    /// Building, when supplied.
    pub building: Option<Building>,
    /// Zero or more authorized subjects.
    pub subjects: Vec<AuthorizedSubject>,
    /// Zero or more ownership records.
    pub ownerships: Vec<Ownership>,
}

/// Current limited-content response to `dejNahledLV`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OwnershipSheetPreviewResponse {
    /// Ownership sheet, when supplied.
    pub ownership_sheet: Option<OwnershipSheet>,
    /// Zero or more authorized subjects.
    pub subjects: Vec<AuthorizedSubject>,
    /// Zero or more ownership records.
    pub ownerships: Vec<Ownership>,
    /// Zero or more parcels.
    pub parcels: Vec<Parcel>,
    /// Zero or more buildings.
    pub buildings: Vec<Building>,
    /// Zero or more detailed units.
    pub units: Vec<DetailedUnit>,
    /// Zero or more building rights.
    pub building_rights: Vec<BuildingRight>,
}

/// Typed result of one of the three information operations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InformationResponse {
    /// Parcel MBR entries.
    ParcelBoundingBoxes(ParcelBoundingBoxResponse),
    /// Unit overview.
    UnitOverview(Box<UnitOverviewResponse>),
    /// LV preview.
    OwnershipSheetPreview(OwnershipSheetPreviewResponse),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn requests_validate_nonempty_and_natural_key_ranges() {
        assert!(ParcelBoundingBoxRequest::new(Vec::new()).is_err());
        assert!(OwnershipSheetNaturalKey::new(CadastralAreaCode::new("1").unwrap(), 0).is_err());
        assert!(UnitBuildingNumber::new("123456789012345678901234567890").is_ok());
        assert!(UnitBuildingNumber::new("1234567890123456789012345678901").is_err());
        let raw = " \t+123456789012345678901234567890\r\n";
        assert_eq!(UnitBuildingNumber::new(raw).unwrap().as_str(), raw);
        assert!(UnitBuildingNumber::new(" +1234567890123456789012345678901 ").is_err());
        assert!(UnitBuildingNumber::new("++1").is_err());
        assert!(
            ParcelBoundingBoxRequest {
                parcel_ids: Vec::new()
            }
            .validate()
            .is_err()
        );
        assert!(
            UnitOverviewNaturalKey {
                municipality_part: MunicipalityPartCode::new("1").unwrap(),
                building_type: BuildingTypeCode::new("1").unwrap(),
                building_number: UnitBuildingNumber::new("1").unwrap(),
                unit_number: 10_000_000_000,
            }
            .validate()
            .is_err()
        );
        assert!(
            OwnershipSheetNaturalKey {
                cadastral_area: CadastralAreaCode::new("1").unwrap(),
                sheet_number: 0,
            }
            .validate()
            .is_err()
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn building_number_deserialization_uses_the_validating_constructor() {
        let number: UnitBuildingNumber = serde_json::from_str("\" +0001 \"").unwrap();
        assert_eq!(number.as_str(), " +0001 ");
        assert!(serde_json::from_str::<UnitBuildingNumber>("\"0\"").is_err());
    }
}