use super::soap::XmlWriter as Writer;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use roxmltree::Node;
use super::files;
use super::gml;
use super::mtom::Attachments;
use super::registry;
use super::soap::{self, Service, XmlResult};
use crate::model::{
InfrastructureInquiryPart, InfrastructureManagerInquiryRequest,
InfrastructureManagerInquirySelector, InquiryCadastralArea, InquiryContactDetails,
InquiryMunicipality, InquiryParcel, InquiryParcelGroup, InquirySubmissionId,
InquiryValidationResult, OverallResult, Page, PageRequest, RequestId,
};
use crate::{Error, Result};
pub(crate) const COMMON_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Common:v1";
pub(crate) const COMMON_SUBJECTS_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Subjekty:v1";
pub(crate) const IS_RUIAN_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Ruian:v1";
pub(crate) const IS_DTI_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Dti:v1";
fn write_data(
writer: &mut Writer,
declarations: &[(&str, &str)],
write_contents: impl FnOnce(&mut Writer) -> XmlResult,
) -> XmlResult {
let mut data = BytesStart::new("Data");
for declaration in declarations {
data.push_attribute(*declaration);
}
writer.write_event(Event::Start(data))?;
write_contents(writer)?;
writer.write_event(Event::End(BytesEnd::new("Data")))?;
Ok(())
}
pub(crate) fn write_inquiry_request(
writer: &mut Writer,
subject: &crate::SubjectId,
request: &InfrastructureManagerInquiryRequest,
) -> XmlResult {
let declarations: &[(&str, &str)] = match request.selector {
InfrastructureManagerInquirySelector::Parcels(_) => &[
("xmlns:commonSubjekty", COMMON_SUBJECTS_NS),
("xmlns:isdmvsRuian", IS_RUIAN_NS),
],
InfrastructureManagerInquirySelector::Area(_) => {
&[("xmlns:commonSubjekty", COMMON_SUBJECTS_NS)]
}
};
write_data(writer, declarations, |writer| {
soap::element(writer, "Subjekt", |writer| {
soap::text_element(writer, "commonSubjekty:Id", subject.as_str())
})?;
match &request.selector {
InfrastructureManagerInquirySelector::Parcels(parcel_ids) => {
soap::element(writer, "Parcely", |writer| {
for id in parcel_ids {
soap::element(writer, "Parcela", |writer| {
soap::text_element(writer, "isdmvsRuian:Id", &id.to_string())
})?;
}
Ok(())
})?;
}
InfrastructureManagerInquirySelector::Area(area) => {
gml::write_area(writer, "UzemniVymezeni", area)?;
}
}
soap::text_element(writer, "Identifikace", &request.identification)?;
if let Some(email) = &request.notification_email {
soap::text_element(writer, "NotifikacniEmail", email)?;
}
Ok(())
})
}
pub(crate) fn write_result_request(writer: &mut Writer, request_id: &RequestId) -> XmlResult {
let mut data = BytesStart::new("iMsg:Data");
data.push_attribute(("xmlns:iMsg", soap::ISDMVS_MESSAGES_NS));
data.push_attribute(("xmlns:msg", soap::MESSAGES_NS));
writer.write_event(Event::Start(data))?;
soap::text_element(writer, "msg:IdPozadavku", request_id.as_str())?;
writer.write_event(Event::End(BytesEnd::new("iMsg:Data")))?;
Ok(())
}
pub(crate) fn write_parts_request(
writer: &mut Writer,
request_id: &RequestId,
only_valid: Option<bool>,
page: PageRequest,
) -> XmlResult {
write_data(writer, &[("xmlns:commonCommon", COMMON_NS)], |writer| {
soap::text_element(writer, "commonCommon:ZaznamyOd", &page.offset.to_string())?;
soap::text_element(
writer,
"commonCommon:MaximalniPocetZaznamu",
&page.limit.to_string(),
)?;
soap::text_element(
writer,
"commonCommon:VratCelkovyPocetZaznamu",
soap::xml_bool(page.include_total),
)?;
soap::text_element(writer, "IdPozadavku", request_id.as_str())?;
if let Some(only_valid) = only_valid {
soap::text_element(writer, "PouzeValidni", soap::xml_bool(only_valid))?;
}
Ok(())
})
}
fn required_child<'a, 'input>(
node: Node<'a, 'input>,
namespace: &str,
name: &str,
) -> Result<Node<'a, 'input>> {
soap::child(node, namespace, name)?
.ok_or_else(|| Error::invalid_response(format!("required XML element {name} is missing")))
}
fn decode_i64(node: Node<'_, '_>, namespace: &str, name: &str) -> Result<i64> {
soap::parse(&soap::required_text(node, namespace, name)?, name)
}
fn decode_nonnegative_long(node: Node<'_, '_>, name: &str) -> Result<u64> {
let value = decode_i64(node, Service::R49.namespace(), name)?;
u64::try_from(value).map_err(|_| Error::invalid_response(format!("{name} is negative")))
}
fn decode_integer(node: Node<'_, '_>, name: &str) -> Result<String> {
integer_string(soap::required_text(node, IS_RUIAN_NS, name)?, name)
}
fn decode_optional_integer(node: Node<'_, '_>, name: &str) -> Result<Option<String>> {
soap::optional_text(node, IS_RUIAN_NS, name)?
.map(|value| integer_string(value, name))
.transpose()
}
fn integer_string(value: String, name: &str) -> Result<String> {
let value = value.trim();
let digits = value
.strip_prefix('+')
.or_else(|| value.strip_prefix('-'))
.unwrap_or(value);
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(Error::invalid_response(format!(
"{name} is not an XML integer"
)));
}
Ok(value.to_owned())
}
pub(crate) fn decode_submission(data: Option<Node<'_, '_>>) -> Result<RequestId> {
let data =
data.ok_or_else(|| Error::invalid_response("submission response Data is missing"))?;
let raw = soap::required_text(data, soap::MESSAGES_NS, "IdPozadavku")?;
RequestId::new(raw).map_err(|_| Error::invalid_response("asynchronous request ID is invalid"))
}
fn decode_submission_id(raw: String) -> Result<InquirySubmissionId> {
InquirySubmissionId::new(raw)
.map_err(|_| Error::invalid_response("inquiry submission identifier is invalid"))
}
fn decode_parcel(node: Node<'_, '_>) -> Result<InquiryParcel> {
Ok(InquiryParcel {
id: decode_i64(node, IS_RUIAN_NS, "Id")?,
main_number: decode_integer(node, "KmenoveCislo")?,
subdivision_number: decode_optional_integer(node, "PoddeleniCisla")?,
numbering_type: decode_integer(node, "DruhCislovani")?,
parcel_type: decode_integer(node, "DruhPozemku")?,
only_part: soap::parse_bool(
&soap::required_text(node, Service::R49.namespace(), "PouzeCast")?,
"PouzeCast",
)?,
})
}
fn decode_parcel_group(node: Node<'_, '_>) -> Result<InquiryParcelGroup> {
let service = Service::R49.namespace();
let cadastral = required_child(node, service, "KatastralniUzemi")?;
let municipality = required_child(cadastral, IS_RUIAN_NS, "Obec")?;
let parcels = required_child(node, service, "Parcely")?;
Ok(InquiryParcelGroup {
cadastral_area: InquiryCadastralArea {
code: decode_i64(cadastral, IS_RUIAN_NS, "Kod")?,
name: soap::required_text_or_empty(cadastral, IS_RUIAN_NS, "Nazev")?,
municipality: InquiryMunicipality {
code: decode_i64(municipality, IS_RUIAN_NS, "Kod")?,
name: soap::required_text_or_empty(municipality, IS_RUIAN_NS, "Nazev")?,
},
},
parcels: soap::children(parcels, service, "Parcela")
.map(decode_parcel)
.collect::<Result<Vec<_>>>()?,
})
}
pub(crate) fn decode_overall_result(data: Option<Node<'_, '_>>) -> Result<Option<OverallResult>> {
let Some(data) = data else {
return Ok(None);
};
let service = Service::R49.namespace();
let groups = required_child(data, service, "Parcely")?;
Ok(Some(OverallResult {
submission_id: decode_submission_id(soap::required_text(data, service, "IdPodani")?)?,
parcel_groups: soap::children(groups, service, "Parcely")
.map(decode_parcel_group)
.collect::<Result<Vec<_>>>()?,
infrastructure_part_count: decode_nonnegative_long(data, "PocetCastiDti")?,
validation_completed: soap::parse_bool(
&soap::required_text(data, service, "ValidaceDokoncena")?,
"ValidaceDokoncena",
)?,
valid_infrastructure_part_count: soap::optional_text(
data,
service,
"PocetValidnichCastiDti",
)?
.map(|value| {
let value = soap::parse::<i64>(&value, "PocetValidnichCastiDti")?;
u64::try_from(value)
.map_err(|_| Error::invalid_response("PocetValidnichCastiDti is negative"))
})
.transpose()?,
}))
}
fn decode_part(node: Node<'_, '_>) -> Result<InfrastructureInquiryPart> {
let service = Service::R49.namespace();
let info = required_child(node, service, "CastDti")?;
let contact = required_child(node, service, "KontaktniUdajeProZiskaniStanoviska")?;
let validation = required_child(node, service, "VysledekValidace")?;
Ok(InfrastructureInquiryPart {
info: registry::decode_infrastructure_part_info(info)?,
contact: InquiryContactDetails {
url: soap::optional_text(contact, IS_DTI_NS, "Url")?,
idds: soap::optional_text(contact, IS_DTI_NS, "Idds")?,
email: soap::optional_text(contact, IS_DTI_NS, "Email")?,
phone: soap::optional_text(contact, IS_DTI_NS, "Telefon")?,
note: soap::optional_text(contact, IS_DTI_NS, "Poznamka")?,
},
validation: InquiryValidationResult {
valid: soap::parse_bool(
&soap::required_text(validation, service, "Validni")?,
"Validni",
)?,
description: soap::required_text_or_empty(validation, service, "Popis")?,
},
})
}
pub(crate) fn decode_parts(
data: Option<Node<'_, '_>>,
requested_offset: u32,
) -> Result<Page<InfrastructureInquiryPart>> {
let Some(data) = data else {
return Ok(Page {
offset: requested_offset,
count: 0,
total: None,
items: Vec::new(),
});
};
let offset = soap::parse(
&soap::required_text(data, COMMON_NS, "ZaznamyOd")?,
"ZaznamyOd",
)?;
let count = soap::parse(
&soap::required_text(data, COMMON_NS, "PocetZaznamu")?,
"PocetZaznamu",
)?;
let total = soap::optional_text(data, COMMON_NS, "CelkovyPocetZaznamu")?
.map(|value| soap::parse(&value, "CelkovyPocetZaznamu"))
.transpose()?;
let service = Service::R49.namespace();
let wrapper = required_child(data, service, "CastiDti")?;
let items = soap::children(wrapper, service, "CastDti")
.map(decode_part)
.collect::<Result<Vec<_>>>()?;
if count as usize != items.len() {
return Err(Error::invalid_response(
"R49 page record count does not match the number of returned items",
));
}
Ok(Page {
offset,
count,
total,
items,
})
}
pub(crate) fn decode_report(
data: Option<Node<'_, '_>>,
attachments: &Attachments<'_>,
) -> Result<Option<crate::FilePayload>> {
let Some(data) = data else {
return Ok(None);
};
let report = required_child(data, Service::R49.namespace(), "Report")?;
files::decode_output_file(report, attachments).map(Some)
}
#[cfg(test)]
mod tests {
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use geo_types::{LineString, Polygon, coord};
use sha2::{Digest, Sha256};
use super::*;
use crate::model::{
Area, CorrelationId, InfrastructurePartInfo, IntegrityStatus, Person, ProcessingState,
Response, SubjectId,
};
use crate::wire::files::FILES_NS;
use crate::wire::mtom::{MimeLimits, SoapBody};
use crate::wire::registry::{
ADDRESSES_NS, CODELISTS_NS, COMMON_DTI_NS, IS_SUBJECTS_NS, PERSONS_NS,
};
use crate::wire::soap::Operation;
const REQUEST_UUID: &str = "ed8af7af-5b39-4dff-96ab-7561214336f1";
const RESPONSE_UUID: &str = "c5f073e9-d3e9-4845-aae0-de3ef42357be";
const OTHER_UUID: &str = "11111111-1111-4111-8111-111111111111";
const REPORT_BYTES: &[u8] = b"%PDF-synthetic\n";
const SUBMIT: Operation = Operation::new(
Service::R49,
"zjistiUzemiSpravcuDti",
"ZjistiUzemiSpravcuDti",
"ZjistiUzemiSpravcuDtiOdpoved",
)
.with_response_data_namespace(soap::ISDMVS_MESSAGES_NS);
const OVERALL: Operation = Operation::new(
Service::R49,
"ctiVysledekZjistiUzemiSpravcuDti",
"CtiVysledekZjistiUzemiSpravcuDti",
"CtiVysledekZjistiUzemiSpravcuDtiOdpoved",
);
const PARTS: Operation = Operation::new(
Service::R49,
"ctiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
"CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
"CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDtiOdpoved",
);
const REPORT: Operation = Operation::new(
Service::R49,
"ctiVysledekZjistiUzemiSpravcuDtiReport",
"CtiVysledekZjistiUzemiSpravcuDtiReport",
"CtiVysledekZjistiUzemiSpravcuDtiReportOdpoved",
);
fn area() -> Area {
Area::s_jtsk(Polygon::new(
LineString::from(vec![
coord! { x: 0.0, y: 0.0 },
coord! { x: 1.0, y: 0.0 },
coord! { x: 1.0, y: 1.0 },
coord! { x: 0.0, y: 0.0 },
]),
Vec::new(),
))
.unwrap()
}
fn limits() -> soap::XmlLimits {
soap::XmlLimits {
max_nodes: 65_536,
max_depth: 128,
}
}
fn mime_limits() -> MimeLimits {
MimeLimits {
max_parts: 4,
max_decoded_bytes: 1024,
max_total_decoded_bytes: 2048,
}
}
fn request_xml(operation: Operation, write: impl FnOnce(&mut Writer) -> XmlResult) -> String {
String::from_utf8(soap::request(operation, REQUEST_UUID.parse().unwrap(), write).unwrap())
.unwrap()
}
fn service_request_data(
operation: Operation,
write: impl FnOnce(&mut Writer) -> XmlResult,
) -> String {
let xml = request_xml(operation, write);
roxmltree::Document::parse(&xml).unwrap();
let start = xml.find("<Data").unwrap();
let end = xml.rfind("</Data>").unwrap() + "</Data>".len();
xml[start..end].to_owned()
}
fn response_envelope(operation: Operation, state: &str, data: Option<&str>) -> String {
let data = data
.map(|data| {
if operation.response_data_namespace == soap::ISDMVS_MESSAGES_NS {
format!("<iMsg:Data>{data}</iMsg:Data>")
} else {
format!("<r:Data>{data}</r:Data>")
}
})
.unwrap_or_default();
format!(
"<s:Envelope xmlns:s=\"{}\" xmlns:r=\"{}\" xmlns:iMsg=\"{}\" xmlns:msg=\"{}\" xmlns:c=\"{COMMON_NS}\" xmlns:ru=\"{IS_RUIAN_NS}\" xmlns:d=\"{IS_DTI_NS}\" xmlns:cd=\"{COMMON_DTI_NS}\" xmlns:cs=\"{COMMON_SUBJECTS_NS}\" xmlns:cl=\"{CODELISTS_NS}\" xmlns:sub=\"{IS_SUBJECTS_NS}\" xmlns:o=\"{PERSONS_NS}\" xmlns:a=\"{ADDRESSES_NS}\" xmlns:f=\"{FILES_NS}\" xmlns:xop=\"http://www.w3.org/2004/08/xop/include\"><s:Body><r:{}><msg:Hlavicka><msg:UidOdpovedi>{RESPONSE_UUID}</msg:UidOdpovedi><msg:Vysledek stav=\"{state}\"><msg:UidZadosti>{REQUEST_UUID}</msg:UidZadosti><msg:Hlaseni><msg:Hlaseni kod=\"1030\" typ=\"Informace\"><msg:Zprava>Synthetic response</msg:Zprava></msg:Hlaseni></msg:Hlaseni></msg:Vysledek></msg:Hlavicka>{data}</r:{}></s:Body></s:Envelope>",
soap::SOAP_11_NS,
operation.service.namespace(),
soap::ISDMVS_MESSAGES_NS,
soap::MESSAGES_NS,
operation.response,
operation.response,
)
}
fn decode_body<T>(
bytes: &[u8],
content_type: Option<&str>,
operation: Operation,
decode: impl FnOnce(Option<Node<'_, '_>>, &Attachments<'_>) -> Result<T>,
) -> Result<Response<T>> {
let body = SoapBody::parse(bytes, content_type, mime_limits())?;
soap::decode_with_attachments(
body.xml,
&body.attachments,
operation,
REQUEST_UUID.parse().unwrap(),
limits(),
decode,
)
}
fn decode_without_files<T>(
operation: Operation,
xml: &str,
decode: impl FnOnce(Option<Node<'_, '_>>) -> Result<T>,
) -> Result<Response<T>> {
soap::decode(
xml.as_bytes(),
operation,
REQUEST_UUID.parse().unwrap(),
limits(),
decode,
)
}
fn bare_sha256(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn report_file(content: &str, checksum: &str) -> String {
format!(
"<f:Obsah>{content}</f:Obsah><f:Nazev>report.pdf</f:Nazev><f:Velikost>{}</f:Velikost><f:KontrolniSoucet>{checksum}</f:KontrolniSoucet>",
REPORT_BYTES.len()
)
}
fn multipart(xml: &str) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(b"--dmvs-boundary\r\nContent-Type: application/xop+xml; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\nContent-ID: <root@dmvs>\r\n\r\n");
body.extend_from_slice(xml.as_bytes());
body.extend_from_slice(b"\r\n--dmvs-boundary\r\nContent-Type: application/pdf\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <report@dmvs>\r\n\r\n");
body.extend_from_slice(REPORT_BYTES);
body.extend_from_slice(b"\r\n--dmvs-boundary--\r\n");
body
}
#[test]
fn writes_both_explicit_submission_selector_shapes_in_xsd_order() {
let parcels = InfrastructureManagerInquiryRequest::new(
InfrastructureManagerInquirySelector::parcels(vec![5_000_000_000, -42]).unwrap(),
"business-identification",
)
.unwrap()
.with_notification_email("notify@example.invalid");
assert_eq!(
service_request_data(SUBMIT, |writer| {
write_inquiry_request(writer, &SubjectId::new("subject-1").unwrap(), &parcels)
}),
"<Data xmlns:commonSubjekty=\"urn:cz:isvs:dmvs:common:schemas:Subjekty:v1\" xmlns:isdmvsRuian=\"urn:cz:isvs:dmvs:isdmvs:schemas:Ruian:v1\"><Subjekt><commonSubjekty:Id>subject-1</commonSubjekty:Id></Subjekt><Parcely><Parcela><isdmvsRuian:Id>5000000000</isdmvsRuian:Id></Parcela><Parcela><isdmvsRuian:Id>-42</isdmvsRuian:Id></Parcela></Parcely><Identifikace>business-identification</Identifikace><NotifikacniEmail>notify@example.invalid</NotifikacniEmail></Data>"
);
let area = InfrastructureManagerInquiryRequest::new(
InfrastructureManagerInquirySelector::area(area()).unwrap(),
"area & identification",
)
.unwrap();
assert_eq!(
service_request_data(SUBMIT, |writer| {
write_inquiry_request(writer, &SubjectId::new("subject-2").unwrap(), &area)
}),
"<Data xmlns:commonSubjekty=\"urn:cz:isvs:dmvs:common:schemas:Subjekty:v1\"><Subjekt><commonSubjekty:Id>subject-2</commonSubjekty:Id></Subjekt><UzemniVymezeni><gml:Polygon xmlns:gml=\"http://www.opengis.net/gml/3.2\" gml:id=\"dmvs.area.0\" srsDimension=\"2\" srsName=\"urn:ogc:def:crs:EPSG::5514\"><gml:exterior><gml:LinearRing><gml:posList>0 0 1 0 1 1 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></UzemniVymezeni><Identifikace>area & identification</Identifikace></Data>"
);
}
#[test]
fn writes_imsg_result_requests_and_service_paginated_request() {
let id = RequestId::new("durable-request-id").unwrap();
for operation in [OVERALL, REPORT] {
let xml = request_xml(operation, |writer| write_result_request(writer, &id));
assert!(xml.contains(&format!(
"<iMsg:Data xmlns:iMsg=\"{}\" xmlns:msg=\"{}\"><msg:IdPozadavku>durable-request-id</msg:IdPozadavku></iMsg:Data>",
soap::ISDMVS_MESSAGES_NS,
soap::MESSAGES_NS
)));
}
let page = PageRequest {
offset: 7,
limit: 25,
include_total: false,
};
assert_eq!(
service_request_data(PARTS, |writer| {
write_parts_request(writer, &id, Some(true), page)
}),
"<Data xmlns:commonCommon=\"urn:cz:isvs:dmvs:common:schemas:Common:v1\"><commonCommon:ZaznamyOd>7</commonCommon:ZaznamyOd><commonCommon:MaximalniPocetZaznamu>25</commonCommon:MaximalniPocetZaznamu><commonCommon:VratCelkovyPocetZaznamu>false</commonCommon:VratCelkovyPocetZaznamu><IdPozadavku>durable-request-id</IdPozadavku><PouzeValidni>true</PouzeValidni></Data>"
);
let omitted = service_request_data(PARTS, |writer| {
write_parts_request(writer, &id, None, PageRequest::default())
});
assert!(!omitted.contains("PouzeValidni"));
}
#[test]
fn decodes_submission_from_isdmvs_messages_data() {
let xml = response_envelope(
SUBMIT,
"Prijato",
Some("<msg:IdPozadavku>durable-request-id</msg:IdPozadavku>"),
);
let response = decode_without_files(SUBMIT, &xml, decode_submission).unwrap();
assert_eq!(response.value.as_str(), "durable-request-id");
assert_eq!(response.metadata.state, ProcessingState::Accepted);
let missing = response_envelope(SUBMIT, "Prijato", None);
assert!(decode_without_files(SUBMIT, &missing, decode_submission).is_err());
}
#[test]
fn decodes_nested_overall_groups_with_large_ids_and_arbitrary_integers() {
let huge = "12345678901234567890123456789012345678901234567890";
let data = format!(
"<r:IdPodani>private-submission-id</r:IdPodani><r:Parcely><r:Parcely><r:KatastralniUzemi><ru:Kod>6000000000</ru:Kod><ru:Nazev>private cadastral name</ru:Nazev><ru:Obec><ru:Kod>7000000000</ru:Kod><ru:Nazev>private municipality</ru:Nazev></ru:Obec></r:KatastralniUzemi><r:Parcely><r:Parcela><ru:Id>5000000001</ru:Id><ru:KmenoveCislo>{huge}</ru:KmenoveCislo><ru:PoddeleniCisla>+0002</ru:PoddeleniCisla><ru:DruhCislovani>1</ru:DruhCislovani><ru:DruhPozemku>2</ru:DruhPozemku><r:PouzeCast>true</r:PouzeCast></r:Parcela><r:Parcela><ru:Id>-5000000002</ru:Id><ru:KmenoveCislo>-99</ru:KmenoveCislo><ru:DruhCislovani>3</ru:DruhCislovani><ru:DruhPozemku>4</ru:DruhPozemku><r:PouzeCast>false</r:PouzeCast></r:Parcela></r:Parcely></r:Parcely><r:Parcely><r:KatastralniUzemi><ru:Kod>8</ru:Kod><ru:Nazev></ru:Nazev><ru:Obec><ru:Kod>9</ru:Kod><ru:Nazev></ru:Nazev></ru:Obec></r:KatastralniUzemi><r:Parcely/></r:Parcely></r:Parcely><r:PocetCastiDti>3</r:PocetCastiDti><r:ValidaceDokoncena>false</r:ValidaceDokoncena><r:PocetValidnichCastiDti>2</r:PocetValidnichCastiDti>"
);
let xml = response_envelope(OVERALL, "Zpracovano", Some(&data));
let response = decode_without_files(OVERALL, &xml, decode_overall_result).unwrap();
let result = response.value.unwrap();
assert_eq!(result.submission_id.as_str(), "private-submission-id");
assert_eq!(result.parcel_groups.len(), 2);
let group = &result.parcel_groups[0];
assert_eq!(group.cadastral_area.code, 6_000_000_000);
assert_eq!(group.cadastral_area.municipality.code, 7_000_000_000);
assert_eq!(group.parcels[0].id, 5_000_000_001);
assert_eq!(group.parcels[0].main_number, huge);
assert_eq!(
group.parcels[0].subdivision_number.as_deref(),
Some("+0002")
);
assert!(group.parcels[0].only_part);
assert_eq!(group.parcels[1].id, -5_000_000_002);
assert_eq!(group.parcels[1].subdivision_number, None);
assert!(result.parcel_groups[1].parcels.is_empty());
assert_eq!(result.infrastructure_part_count, 3);
assert!(!result.validation_completed);
assert_eq!(result.valid_infrastructure_part_count, Some(2));
let debug = format!("{result:?}");
for private in [
"private-submission-id",
"private cadastral name",
"private municipality",
"5000000001",
] {
assert!(!debug.contains(private));
}
let negative = data.replace(
"<r:PocetCastiDti>3</r:PocetCastiDti>",
"<r:PocetCastiDti>-1</r:PocetCastiDti>",
);
let xml = response_envelope(OVERALL, "Zpracovano", Some(&negative));
assert!(decode_without_files(OVERALL, &xml, decode_overall_result).is_err());
let invalid_integer = data.replace(huge, "12.5");
let xml = response_envelope(OVERALL, "Zpracovano", Some(&invalid_integer));
assert!(decode_without_files(OVERALL, &xml, decode_overall_result).is_err());
}
fn minimal_cast_info(id: &str) -> String {
format!(
"<cd:Id>{id}</cd:Id><d:Nazev>private part name</d:Nazev><d:SkupinaPrvku><cl:Kod>future-group</cl:Kod></d:SkupinaPrvku><d:Administrator><cs:Id>private-administrator</cs:Id></d:Administrator>"
)
}
fn owner_xml() -> &'static str {
"<d:Vlastnik><cs:Id>private-owner-id</cs:Id><sub:Osoba><o:FyzickaOsoba><o:Adresa><a:AdresaVolna><a:AdresaTextem>private-address</a:AdresaTextem><a:KodZeme>CZ</a:KodZeme></a:AdresaVolna></o:Adresa><o:Nazev>private person</o:Nazev><o:Jmeno>Private</o:Jmeno><o:Prijmeni>Person</o:Prijmeni></o:FyzickaOsoba></sub:Osoba><sub:Email>owner@example.invalid</sub:Email><sub:Telefon>+420 000</sub:Telefon></d:Vlastnik>"
}
fn outer_part(id: &str, owner: &str, valid: bool, description: &str) -> String {
let contact = if valid {
"<d:Url>https://private.example.invalid/statement</d:Url><d:Idds>private-data-box</d:Idds><d:Email>contact@example.invalid</d:Email><d:Telefon>+420 111</d:Telefon><d:Poznamka>private note</d:Poznamka>"
} else {
"<d:Email></d:Email>"
};
format!(
"<r:CastDti><r:CastDti>{}{}</r:CastDti><r:KontaktniUdajeProZiskaniStanoviska>{contact}</r:KontaktniUdajeProZiskaniStanoviska><r:VysledekValidace><r:Validni>{valid}</r:Validni><r:Popis>{description}</r:Popis></r:VysledekValidace></r:CastDti>",
minimal_cast_info(id),
owner
)
}
fn assert_shared_person(info: &InfrastructurePartInfo) {
let owner = info.owner.as_ref().unwrap();
assert_eq!(owner.info.id.as_str(), "private-owner-id");
assert_eq!(owner.email.as_deref(), Some("owner@example.invalid"));
let Person::Physical(person) = &owner.info.person else {
panic!("expected physical person");
};
assert_eq!(person.given_name.as_deref(), Some("Private"));
}
#[test]
fn decodes_paginated_valid_and_invalid_parts_contacts_and_shared_people() {
let data = format!(
"<c:ZaznamyOd>7</c:ZaznamyOd><c:PocetZaznamu>2</c:PocetZaznamu><c:CelkovyPocetZaznamu>9</c:CelkovyPocetZaznamu><r:CastiDti>{}{}</r:CastiDti>",
outer_part(
"private-part-1",
owner_xml(),
true,
"private valid description"
),
outer_part("private-part-2", "", false, "private invalid description")
);
let xml = response_envelope(PARTS, "Zpracovano", Some(&data));
let response = decode_without_files(PARTS, &xml, |data| decode_parts(data, 7)).unwrap();
let page = response.value;
assert_eq!(page.offset, 7);
assert_eq!(page.count, 2);
assert_eq!(page.total, Some(9));
let first = &page.items[0];
assert_eq!(first.info.id.as_str(), "private-part-1");
assert_shared_person(&first.info);
assert!(first.validation.valid);
assert_eq!(first.validation.description, "private valid description");
assert_eq!(
first.contact.url.as_deref(),
Some("https://private.example.invalid/statement")
);
assert_eq!(first.contact.idds.as_deref(), Some("private-data-box"));
assert_eq!(
first.contact.email.as_deref(),
Some("contact@example.invalid")
);
assert_eq!(first.contact.phone.as_deref(), Some("+420 111"));
assert_eq!(first.contact.note.as_deref(), Some("private note"));
assert!(!page.items[1].validation.valid);
assert_eq!(
page.items[1].validation.description,
"private invalid description"
);
assert_eq!(page.items[1].contact.email.as_deref(), Some(""));
let debug = format!("{page:?}");
for private in [
"private-part-1",
"private-owner-id",
"private person",
"private-address",
"private.example.invalid",
"private-data-box",
"contact@example.invalid",
"private note",
"private valid description",
"private invalid description",
] {
assert!(!debug.contains(private), "debug output contained {private}");
}
let mismatch = data.replace(
"<c:PocetZaznamu>2</c:PocetZaznamu>",
"<c:PocetZaznamu>1</c:PocetZaznamu>",
);
let xml = response_envelope(PARTS, "Zpracovano", Some(&mismatch));
assert!(decode_without_files(PARTS, &xml, |data| decode_parts(data, 7)).is_err());
}
#[test]
fn decodes_inline_and_mtom_reports_and_preserves_official_bare_checksum() {
let checksum = bare_sha256(REPORT_BYTES);
assert_eq!(checksum.len(), 64);
let data = format!(
"<r:Report>{}</r:Report>",
report_file(&BASE64_STANDARD.encode(REPORT_BYTES), &checksum)
);
let xml = response_envelope(REPORT, "Zpracovano", Some(&data));
let response = decode_body(
xml.as_bytes(),
Some("text/xml; charset=utf-8"),
REPORT,
decode_report,
)
.unwrap();
let file = response.value.unwrap();
assert_eq!(file.bytes().as_ref(), REPORT_BYTES);
assert_eq!(file.metadata.name, "report.pdf");
assert_eq!(file.metadata.checksum.as_str(), checksum);
assert_eq!(file.metadata.checksum.declared_algorithm(), None);
assert_eq!(
file.metadata.checksum.verify(file.bytes()).unwrap(),
IntegrityStatus::Unverified
);
assert_eq!(file.verify_sha256().unwrap(), IntegrityStatus::Verified);
assert_eq!(file.metadata.checksum.declared_algorithm(), None);
let mtom_data = format!(
"<r:Report>{}</r:Report>",
report_file("<xop:Include href=\"cid:report@dmvs\"/>", &checksum)
);
let xml = response_envelope(REPORT, "Zpracovano", Some(&mtom_data));
let multipart = multipart(&xml);
let response = decode_body(
&multipart,
Some("multipart/related; boundary=dmvs-boundary; type=\"application/xop+xml\"; start=\"<root@dmvs>\""),
REPORT,
decode_report,
)
.unwrap();
let file = response.value.unwrap();
assert_eq!(file.bytes().as_ref(), REPORT_BYTES);
assert_eq!(file.metadata.checksum.declared_algorithm(), None);
}
#[test]
fn absent_data_and_correlation_have_operation_specific_behavior() {
let xml = response_envelope(OVERALL, "ProbihaZpracovani", None);
let response = decode_without_files(OVERALL, &xml, decode_overall_result).unwrap();
assert!(response.value.is_none());
assert_eq!(response.metadata.state, ProcessingState::InProgress);
let xml = response_envelope(PARTS, "ProbihaZpracovani", None);
let response = decode_without_files(PARTS, &xml, |data| decode_parts(data, 23)).unwrap();
assert_eq!(response.value.offset, 23);
assert_eq!(response.value.count, 0);
assert_eq!(response.value.total, None);
assert!(response.value.items.is_empty());
let xml = response_envelope(REPORT, "ProbihaZpracovani", None);
let response =
decode_body(xml.as_bytes(), Some("text/xml"), REPORT, decode_report).unwrap();
assert!(response.value.is_none());
let xml = response_envelope(OVERALL, "Zpracovano", None);
let wrong_correlation = xml.replace(REQUEST_UUID, OTHER_UUID);
let error =
decode_without_files(OVERALL, &wrong_correlation, decode_overall_result).unwrap_err();
assert!(matches!(error, Error::InvalidResponse { .. }));
let wrong_expected = soap::decode(
xml.as_bytes(),
OVERALL,
CorrelationId::new(),
limits(),
decode_overall_result,
)
.unwrap_err();
assert!(matches!(wrong_expected, Error::InvalidResponse { .. }));
}
}