dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
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::soap::{self, XmlResult};
use crate::model::{
    Address, Area, FreeAddress, InfrastructureElementGroup, InfrastructurePartId,
    InfrastructurePartInfo, InfrastructureRespondentPart, InfrastructureSubjectRole, LegalPerson,
    Page, PageRequest, Person, PhysicalPerson, RuianAddress, Subject, SubjectId, SubjectInfo,
};
use crate::{Error, Result};

pub(crate) const COMMON_DTI_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Dti:v1";
pub(crate) const IS_DTI_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Dti:v1";
pub(crate) const COMMON_SUBJECTS_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Subjekty:v1";
pub(crate) const IS_SUBJECTS_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Subjekty:v1";
pub(crate) const PERSONS_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Osoby:v1";
pub(crate) const ADDRESSES_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Adresy:v1";
pub(crate) const CODELISTS_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Ciselniky:v1";
pub(crate) const COMMON_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Common: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(())
}

fn write_page_request(writer: &mut Writer, page: PageRequest) -> XmlResult {
    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),
    )
}

pub(crate) fn write_infrastructure_respondents_request(
    writer: &mut Writer,
    area: &Area,
    page: PageRequest,
) -> XmlResult {
    write_data(writer, &[("xmlns:commonCommon", COMMON_NS)], |writer| {
        write_page_request(writer, page)?;
        gml::write_area(writer, "UzemniVymezeni", area)
    })
}

pub(crate) fn write_subject_request(writer: &mut Writer, id: &SubjectId) -> XmlResult {
    write_data(
        writer,
        &[("xmlns:commonSubjekty", COMMON_SUBJECTS_NS)],
        |writer| {
            soap::element(writer, "Subjekt", |writer| {
                soap::text_element(writer, "commonSubjekty:Id", id.as_str())
            })
        },
    )
}

pub(crate) fn write_subject_by_organization_number_request(
    writer: &mut Writer,
    organization_number: &str,
) -> XmlResult {
    write_data(writer, &[], |writer| {
        soap::text_element(writer, "Ico", organization_number)
    })
}

pub(crate) fn write_subjects_by_identification_request(
    writer: &mut Writer,
    name: &str,
    role: Option<&InfrastructureSubjectRole>,
    page: PageRequest,
) -> XmlResult {
    write_data(writer, &[("xmlns:commonCommon", COMMON_NS)], |writer| {
        write_page_request(writer, page)?;
        soap::text_element(writer, "Nazev", name)?;
        if let Some(role) = role {
            soap::text_element(writer, "TypSubjektu", role.as_str())?;
        }
        Ok(())
    })
}

pub(crate) fn write_subjects_by_part_request(
    writer: &mut Writer,
    id: &InfrastructurePartId,
    role: Option<&InfrastructureSubjectRole>,
) -> XmlResult {
    write_data(writer, &[("xmlns:commonDti", COMMON_DTI_NS)], |writer| {
        soap::element(writer, "Cast", |writer| {
            soap::text_element(writer, "commonDti:Id", id.as_str())
        })?;
        if let Some(role) = role {
            soap::text_element(writer, "TypSubjektu", role.as_str())?;
        }
        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_u32(node: Node<'_, '_>, namespace: &str, name: &str) -> Result<u32> {
    soap::parse(&soap::required_text(node, namespace, name)?, name)
}

fn decode_i64(node: Node<'_, '_>, namespace: &str, name: &str) -> Result<i64> {
    soap::parse(&soap::required_text_or_empty(node, namespace, name)?, name)
}

fn decode_infrastructure_part_id(raw: String) -> Result<InfrastructurePartId> {
    InfrastructurePartId::new(raw)
        .map_err(|_| Error::invalid_response("infrastructure-part identifier is invalid"))
}

fn decode_subject_id(raw: String) -> Result<SubjectId> {
    SubjectId::new(raw).map_err(|_| Error::invalid_response("subject identifier is invalid"))
}

fn decode_page<T>(
    data: Option<Node<'_, '_>>,
    service_namespace: &str,
    requested_offset: u32,
    wrapper_name: &str,
    item_name: &str,
    decode_item: impl FnMut(Node<'_, '_>) -> Result<T>,
) -> Result<Page<T>> {
    let Some(data) = data else {
        return Ok(Page {
            offset: requested_offset,
            count: 0,
            total: None,
            items: Vec::new(),
        });
    };
    let offset = decode_u32(data, COMMON_NS, "ZaznamyOd")?;
    let count = decode_u32(data, COMMON_NS, "PocetZaznamu")?;
    let total = soap::optional_text(data, COMMON_NS, "CelkovyPocetZaznamu")?
        .map(|value| soap::parse(&value, "CelkovyPocetZaznamu"))
        .transpose()?;
    let wrapper = required_child(data, service_namespace, wrapper_name)?;
    let items = soap::children(wrapper, service_namespace, item_name)
        .map(decode_item)
        .collect::<Result<Vec<_>>>()?;
    if count as usize != items.len() {
        return Err(Error::invalid_response(
            "page record count does not match the number of returned items",
        ));
    }
    Ok(Page {
        offset,
        count,
        total,
        items,
    })
}

fn decode_address(node: Node<'_, '_>) -> Result<Address> {
    let free = soap::child(node, ADDRESSES_NS, "AdresaVolna")?;
    let ruian = soap::child(node, ADDRESSES_NS, "AdresaRuian")?;
    match (free, ruian) {
        (Some(free), None) => Ok(Address::Free(FreeAddress {
            text: soap::optional_text(free, ADDRESSES_NS, "AdresaTextem")?,
            country_code: soap::optional_text(free, ADDRESSES_NS, "KodZeme")?,
        })),
        (None, Some(ruian)) => {
            let address_point = required_child(ruian, ADDRESSES_NS, "AdresniMisto")?;
            Ok(Address::Ruian(RuianAddress {
                address_point_code: decode_i64(address_point, ADDRESSES_NS, "Kod")?,
                street: soap::optional_text(ruian, ADDRESSES_NS, "Ulice")?,
                municipality: soap::required_text_or_empty(ruian, ADDRESSES_NS, "Obec")?,
                house_number: decode_i64(ruian, ADDRESSES_NS, "CisloDomovni")?,
                orientation_number: soap::optional_text(ruian, ADDRESSES_NS, "CisloOrientacni")?
                    .map(|value| soap::parse(&value, "CisloOrientacni"))
                    .transpose()?,
                orientation_number_letter: soap::optional_text(
                    ruian,
                    ADDRESSES_NS,
                    "CisloOrientacniPismeno",
                )?,
                postal_code: decode_i64(ruian, ADDRESSES_NS, "Psc")?,
            }))
        }
        _ => Err(Error::invalid_response(
            "address must contain exactly one free-form or RUIAN representation",
        )),
    }
}

struct PersonBase {
    address: Address,
    name: String,
    data_box: Option<String>,
}

fn decode_person_base(node: Node<'_, '_>) -> Result<PersonBase> {
    let address = required_child(node, PERSONS_NS, "Adresa")?;
    Ok(PersonBase {
        address: decode_address(address)?,
        name: soap::required_text_or_empty(node, PERSONS_NS, "Nazev")?,
        data_box: soap::optional_text(node, PERSONS_NS, "DatovaSchranka")?,
    })
}

fn decode_person(node: Node<'_, '_>) -> Result<Person> {
    let physical = soap::child(node, PERSONS_NS, "FyzickaOsoba")?;
    let legal = soap::child(node, PERSONS_NS, "PravnickaOsoba")?;
    match (physical, legal) {
        (Some(physical), None) => {
            let base = decode_person_base(physical)?;
            Ok(Person::Physical(PhysicalPerson {
                address: base.address,
                name: base.name,
                data_box: base.data_box,
                given_name: soap::optional_text(physical, PERSONS_NS, "Jmeno")?,
                surname: soap::optional_text(physical, PERSONS_NS, "Prijmeni")?,
            }))
        }
        (None, Some(legal)) => {
            let base = decode_person_base(legal)?;
            Ok(Person::Legal(LegalPerson {
                address: base.address,
                name: base.name,
                data_box: base.data_box,
                organization_number: soap::optional_text(legal, PERSONS_NS, "Ico")?,
            }))
        }
        _ => Err(Error::invalid_response(
            "person must contain exactly one physical or legal representation",
        )),
    }
}

fn decode_subject_info(node: Node<'_, '_>) -> Result<SubjectInfo> {
    let person = required_child(node, IS_SUBJECTS_NS, "Osoba")?;
    Ok(SubjectInfo {
        id: decode_subject_id(soap::required_text_or_empty(
            node,
            COMMON_SUBJECTS_NS,
            "Id",
        )?)?,
        person: decode_person(person)?,
    })
}

fn decode_subject(node: Node<'_, '_>) -> Result<Subject> {
    Ok(Subject {
        info: decode_subject_info(node)?,
        email: soap::optional_text(node, IS_SUBJECTS_NS, "Email")?,
        phone: soap::optional_text(node, IS_SUBJECTS_NS, "Telefon")?,
    })
}

pub(crate) fn decode_infrastructure_part_info(
    node: Node<'_, '_>,
) -> Result<InfrastructurePartInfo> {
    let group = required_child(node, IS_DTI_NS, "SkupinaPrvku")?;
    let administrator = required_child(node, IS_DTI_NS, "Administrator")?;
    Ok(InfrastructurePartInfo {
        id: decode_infrastructure_part_id(soap::required_text_or_empty(
            node,
            COMMON_DTI_NS,
            "Id",
        )?)?,
        name: soap::required_text_or_empty(node, IS_DTI_NS, "Nazev")?,
        element_group: InfrastructureElementGroup {
            code: soap::required_text_or_empty(group, CODELISTS_NS, "Kod")?,
        },
        administrator: decode_subject_id(soap::required_text_or_empty(
            administrator,
            COMMON_SUBJECTS_NS,
            "Id",
        )?)?,
        owner: soap::child(node, IS_DTI_NS, "Vlastnik")?
            .map(decode_subject)
            .transpose()?,
        manager: soap::child(node, IS_DTI_NS, "Spravce")?
            .map(decode_subject)
            .transpose()?,
        operator: soap::child(node, IS_DTI_NS, "Provozovatel")?
            .map(decode_subject)
            .transpose()?,
        respondent: soap::child(node, IS_DTI_NS, "Vyjadrovatel")?
            .map(decode_subject)
            .transpose()?,
    })
}

fn decode_infrastructure_respondent_part(
    node: Node<'_, '_>,
    attachments: &Attachments<'_>,
) -> Result<InfrastructureRespondentPart> {
    let service = super::soap::Service::R18a.namespace();
    let respondent = required_child(node, service, "Vyjadrovatel")?;
    let supporting_file = soap::child(node, service, "PodkladyProVyjadrovatele")?
        .map(|node| files::decode_output_file(node, attachments))
        .transpose()?;
    Ok(InfrastructureRespondentPart {
        id: decode_infrastructure_part_id(soap::required_text_or_empty(node, service, "Id")?)?,
        name: soap::required_text_or_empty(node, service, "Nazev")?,
        respondent: decode_subject_info(respondent)?,
        supporting_file,
    })
}

pub(crate) fn decode_infrastructure_respondents(
    data: Option<Node<'_, '_>>,
    requested_offset: u32,
    attachments: &Attachments<'_>,
) -> Result<Page<InfrastructureRespondentPart>> {
    decode_page(
        data,
        super::soap::Service::R18a.namespace(),
        requested_offset,
        "Casti",
        "Cast",
        |node| decode_infrastructure_respondent_part(node, attachments),
    )
}

pub(crate) fn decode_subject_response(data: Option<Node<'_, '_>>) -> Result<Option<SubjectInfo>> {
    let Some(data) = data else {
        return Ok(None);
    };
    let service = super::soap::Service::R18b.namespace();
    let subject = required_child(data, service, "Subjekt")?;
    decode_subject_info(subject).map(Some)
}

pub(crate) fn decode_subjects_by_identification(
    data: Option<Node<'_, '_>>,
    requested_offset: u32,
) -> Result<Page<SubjectInfo>> {
    decode_page(
        data,
        super::soap::Service::R18b.namespace(),
        requested_offset,
        "Subjekty",
        "Subjekt",
        decode_subject_info,
    )
}

pub(crate) fn decode_subjects_by_part(data: Option<Node<'_, '_>>) -> Result<Vec<SubjectInfo>> {
    let Some(data) = data else {
        return Ok(Vec::new());
    };
    let service = super::soap::Service::R18b.namespace();
    let subjects = required_child(data, service, "Subjekty")?;
    soap::children(subjects, service, "Subjekt")
        .map(decode_subject_info)
        .collect()
}

#[cfg(test)]
mod tests {
    use base64::Engine as _;
    use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
    use geo_types::{LineString, Polygon, coord};

    use super::*;
    use crate::model::Response;
    use crate::wire::mtom::{MimeLimits, SoapBody};
    use crate::wire::soap::{Operation, Service};

    const REQUEST_UUID: &str = "ed8af7af-5b39-4dff-96ab-7561214336f1";
    const RESPONSE_UUID: &str = "c5f073e9-d3e9-4845-aae0-de3ef42357be";
    const FILE_BYTES: &[u8] = b"synthetic";

    const R18A_LIST: Operation = Operation::new(
        Service::R18a,
        "ctiVyjadrovatele",
        "CtiVyjadrovateleDti",
        "CtiVyjadrovateleDtiOdpoved",
    );
    const R18B_SUBJECT: Operation = Operation::new(
        Service::R18b,
        "ctiSubjekt",
        "CtiSubjekt",
        "CtiSubjektOdpoved",
    );
    const R18B_ORGANIZATION_NUMBER: Operation = Operation::new(
        Service::R18b,
        "ctiSubjektDleIco",
        "CtiSubjektDleIco",
        "CtiSubjektDleIcoOdpoved",
    );
    const R18B_SEARCH: Operation = Operation::new(
        Service::R18b,
        "ctiSubjektyDleIdentifikace",
        "CtiSubjektyDleIdentifikace",
        "CtiSubjektyDleIdentifikaceOdpoved",
    );
    const R18B_PART: Operation = Operation::new(
        Service::R18b,
        "ctiSubjektyDleCasti",
        "CtiSubjektyDleCasti",
        "CtiSubjektyDleCastiOdpoved",
    );

    fn limits() -> soap::XmlLimits {
        soap::XmlLimits {
            max_nodes: 65_536,
            max_depth: 128,
        }
    }

    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 request_data(operation: Operation, write: impl FnOnce(&mut Writer) -> XmlResult) -> String {
        let xml = soap::request(operation, REQUEST_UUID.parse().unwrap(), write).unwrap();
        let xml = String::from_utf8(xml).unwrap();
        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 operation_response(operation: Operation, data: Option<&str>) -> String {
        let data = data
            .map(|data| format!("<r:Data>{data}</r:Data>"))
            .unwrap_or_default();
        format!(
            "<soap:Envelope xmlns:soap=\"{}\" xmlns:r=\"{}\" xmlns:m=\"{}\" xmlns:p=\"{COMMON_NS}\" xmlns:cd=\"{COMMON_DTI_NS}\" xmlns:d=\"{IS_DTI_NS}\" xmlns:cs=\"{COMMON_SUBJECTS_NS}\" xmlns:s=\"{IS_SUBJECTS_NS}\" xmlns:o=\"{PERSONS_NS}\" xmlns:a=\"{ADDRESSES_NS}\" xmlns:cl=\"{CODELISTS_NS}\" xmlns:f=\"{}\" xmlns:g=\"{}\"><soap:Body><r:{}><m:Hlavicka><m:UidOdpovedi>{RESPONSE_UUID}</m:UidOdpovedi><m:Vysledek stav=\"OK\"><m:UidZadosti>{REQUEST_UUID}</m:UidZadosti><m:Hlaseni><m:Hlaseni kod=\"1000\" typ=\"Informace\"><m:Zprava>Synthetic success</m:Zprava></m:Hlaseni></m:Hlaseni></m:Vysledek></m:Hlavicka>{data}</r:{}></soap:Body></soap:Envelope>",
            soap::SOAP_11_NS,
            operation.service.namespace(),
            soap::MESSAGES_NS,
            files::FILES_NS,
            gml::GML_NS,
            operation.response,
            operation.response,
        )
    }

    fn decode_without_files<T>(
        operation: Operation,
        xml: &str,
        decode: impl FnOnce(Option<Node<'_, '_>>) -> Result<T>,
    ) -> Response<T> {
        decode_without_files_result(operation, xml, decode).unwrap()
    }

    fn decode_without_files_result<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 decode_with_files<T>(
        operation: Operation,
        bytes: &[u8],
        content_type: Option<&str>,
        decode: impl FnOnce(Option<Node<'_, '_>>, &Attachments<'_>) -> Result<T>,
    ) -> Result<Response<T>> {
        let body = SoapBody::parse(
            bytes,
            content_type,
            MimeLimits {
                max_parts: 4,
                max_decoded_bytes: 1024,
                max_total_decoded_bytes: 2048,
            },
        )?;
        soap::decode_with_attachments(
            body.xml,
            &body.attachments,
            operation,
            REQUEST_UUID.parse().unwrap(),
            limits(),
            decode,
        )
    }

    fn legal_person_xml(id: &str, contacts: bool) -> String {
        let contacts = if contacts {
            "<s:Email></s:Email><s:Telefon>+420 000</s:Telefon>"
        } else {
            ""
        };
        format!(
            "<cs:Id>{id}</cs:Id><s:Osoba><o:PravnickaOsoba><o:Adresa><a:AdresaRuian><a:AdresniMisto><a:Kod>123456</a:Kod></a:AdresniMisto><a:Ulice></a:Ulice><a:Obec></a:Obec><a:CisloDomovni>12</a:CisloDomovni><a:CisloOrientacni>4</a:CisloOrientacni><a:CisloOrientacniPismeno>b</a:CisloOrientacniPismeno><a:Psc>11000</a:Psc></a:AdresaRuian></o:Adresa><o:Nazev></o:Nazev><o:DatovaSchranka></o:DatovaSchranka><o:Ico>0012raw</o:Ico></o:PravnickaOsoba></s:Osoba>{contacts}"
        )
    }

    fn physical_person_xml(id: &str) -> String {
        format!(
            "<cs:Id>{id}</cs:Id><s:Osoba><o:FyzickaOsoba><o:Adresa><a:AdresaVolna><a:AdresaTextem/><a:KodZeme>CZ</a:KodZeme></a:AdresaVolna></o:Adresa><o:Nazev>Example person</o:Nazev><o:Jmeno></o:Jmeno><o:Prijmeni>Example</o:Prijmeni></o:FyzickaOsoba></s:Osoba>"
        )
    }

    fn file_xml(content: &str) -> String {
        format!(
            "<f:Obsah>{content}</f:Obsah><f:Nazev>support.txt</f:Nazev><f:Velikost>{}</f:Velikost><f:KontrolniSoucet>algorithm-unspecified</f:KontrolniSoucet><f:ZnakovaSada>UTF-8</f:ZnakovaSada>",
            FILE_BYTES.len()
        )
    }

    fn minimal_cast_info(id: &str) -> String {
        format!(
            "<cd:Id>{id}</cd:Id><d:Nazev>{id}</d:Nazev><d:SkupinaPrvku><cl:Kod>future-group</cl:Kod></d:SkupinaPrvku><d:Administrator><cs:Id>administrator-1</cs:Id></d:Administrator>"
        )
    }

    fn assert_legal_person(subject: &SubjectInfo) {
        assert_eq!(subject.id.as_str(), "subject-1");
        let Person::Legal(person) = &subject.person else {
            panic!("expected legal person");
        };
        assert_eq!(person.name, "");
        assert_eq!(person.data_box.as_deref(), Some(""));
        assert_eq!(person.organization_number.as_deref(), Some("0012raw"));
        let Address::Ruian(address) = &person.address else {
            panic!("expected RUIAN address");
        };
        assert_eq!(address.address_point_code, 123456);
        assert_eq!(address.street.as_deref(), Some(""));
        assert_eq!(address.municipality, "");
        assert_eq!(address.house_number, 12);
        assert_eq!(address.orientation_number, Some(4));
        assert_eq!(address.orientation_number_letter.as_deref(), Some("b"));
        assert_eq!(address.postal_code, 11000);
    }

    #[test]
    fn writes_exact_business_data_for_all_five_operations() {
        let page = PageRequest {
            offset: 7,
            limit: 25,
            include_total: false,
        };
        assert_eq!(
            request_data(R18A_LIST, |writer| {
                write_infrastructure_respondents_request(writer, &area(), PageRequest::default())
            }),
            "<Data xmlns:commonCommon=\"urn:cz:isvs:dmvs:common:schemas:Common:v1\"><commonCommon:ZaznamyOd>0</commonCommon:ZaznamyOd><commonCommon:MaximalniPocetZaznamu>250</commonCommon:MaximalniPocetZaznamu><commonCommon:VratCelkovyPocetZaznamu>true</commonCommon:VratCelkovyPocetZaznamu><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></Data>"
        );
        assert_eq!(
            request_data(R18B_SUBJECT, |writer| {
                write_subject_request(writer, &SubjectId::new("subject-1").unwrap())
            }),
            "<Data xmlns:commonSubjekty=\"urn:cz:isvs:dmvs:common:schemas:Subjekty:v1\"><Subjekt><commonSubjekty:Id>subject-1</commonSubjekty:Id></Subjekt></Data>"
        );
        assert_eq!(
            request_data(R18B_ORGANIZATION_NUMBER, |writer| {
                write_subject_by_organization_number_request(writer, "raw<&ico")
            }),
            "<Data><Ico>raw&lt;&amp;ico</Ico></Data>"
        );
        assert_eq!(
            request_data(R18B_SEARCH, |writer| {
                write_subjects_by_identification_request(
                    writer,
                    "",
                    Some(&InfrastructureSubjectRole::Editor),
                    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><Nazev></Nazev><TypSubjektu>Editor</TypSubjektu></Data>"
        );
        assert_eq!(
            request_data(R18B_PART, |writer| {
                write_subjects_by_part_request(
                    writer,
                    &InfrastructurePartId::new("part-1").unwrap(),
                    Some(&InfrastructureSubjectRole::Other("FutureRole".into())),
                )
            }),
            "<Data xmlns:commonDti=\"urn:cz:isvs:dmvs:common:schemas:Dti:v1\"><Cast><commonDti:Id>part-1</commonDti:Id></Cast><TypSubjektu>FutureRole</TypSubjektu></Data>"
        );
    }

    #[test]
    fn decodes_r18a_respondent_and_supporting_file() {
        let data = format!(
            "<p:ZaznamyOd>4</p:ZaznamyOd><p:PocetZaznamu>1</p:PocetZaznamu><p:CelkovyPocetZaznamu>1</p:CelkovyPocetZaznamu><r:Casti><r:Cast><r:Id>part-1</r:Id><r:Nazev></r:Nazev><r:Vyjadrovatel>{}</r:Vyjadrovatel><r:PodkladyProVyjadrovatele>{}</r:PodkladyProVyjadrovatele></r:Cast></r:Casti>",
            legal_person_xml("subject-1", false),
            file_xml(&BASE64_STANDARD.encode(FILE_BYTES)),
        );
        let xml = operation_response(R18A_LIST, Some(&data));
        let response = decode_with_files(
            R18A_LIST,
            xml.as_bytes(),
            Some("text/xml"),
            |data, attachments| decode_infrastructure_respondents(data, 4, attachments),
        )
        .unwrap();
        let item = &response.value.items[0];
        assert_eq!(item.id.as_str(), "part-1");
        assert_eq!(item.name, "");
        assert_legal_person(&item.respondent);
        assert_eq!(
            item.supporting_file.as_ref().unwrap().bytes().as_ref(),
            FILE_BYTES
        );
    }

    #[test]
    fn decodes_all_r18b_response_shapes_as_subject_info() {
        let subject = format!(
            "<r:Subjekt>{}</r:Subjekt>",
            legal_person_xml("subject-1", false)
        );
        for operation in [R18B_SUBJECT, R18B_ORGANIZATION_NUMBER] {
            let xml = operation_response(operation, Some(&subject));
            let response = decode_without_files(operation, &xml, decode_subject_response);
            let subject = response.value.unwrap();
            assert_eq!(format!("{subject:?}"), "SubjectInfo([REDACTED])");
            assert_legal_person(&subject);
        }

        let page_data = format!(
            "<p:ZaznamyOd>2</p:ZaznamyOd><p:PocetZaznamu>1</p:PocetZaznamu><r:Subjekty>{subject}</r:Subjekty>"
        );
        let response = decode_without_files(
            R18B_SEARCH,
            &operation_response(R18B_SEARCH, Some(&page_data)),
            |data| decode_subjects_by_identification(data, 2),
        );
        assert_eq!(response.value.offset, 2);
        assert_legal_person(&response.value.items[0]);

        let list_data = format!("<r:Subjekty>{subject}{subject}</r:Subjekty>");
        let response = decode_without_files(
            R18B_PART,
            &operation_response(R18B_PART, Some(&list_data)),
            decode_subjects_by_part,
        );
        assert_eq!(response.value.len(), 2);
        assert_legal_person(&response.value[1]);
    }

    #[test]
    fn decodes_shared_cast_info_with_contacts_and_physical_person() {
        let xml = format!(
            "<r:Cast xmlns:r=\"{}\" xmlns:cd=\"{COMMON_DTI_NS}\" xmlns:d=\"{IS_DTI_NS}\" xmlns:cs=\"{COMMON_SUBJECTS_NS}\" xmlns:s=\"{IS_SUBJECTS_NS}\" xmlns:o=\"{PERSONS_NS}\" xmlns:a=\"{ADDRESSES_NS}\" xmlns:cl=\"{CODELISTS_NS}\">{}<d:Vlastnik>{}</d:Vlastnik><d:Vyjadrovatel>{}</d:Vyjadrovatel></r:Cast>",
            Service::R18a.namespace(),
            minimal_cast_info("part-1"),
            legal_person_xml("subject-1", true),
            physical_person_xml("person-1"),
        );
        let document = roxmltree::Document::parse(&xml).unwrap();
        let cast = decode_infrastructure_part_info(document.root_element()).unwrap();
        assert_eq!(cast.id.as_str(), "part-1");
        assert_eq!(cast.element_group.code, "future-group");
        assert_eq!(cast.administrator.as_str(), "administrator-1");
        assert_eq!(cast.owner.unwrap().email.as_deref(), Some(""));
        let Some(Person::Physical(person)) = cast.respondent.map(|subject| subject.info.person)
        else {
            panic!("expected physical respondent");
        };
        assert_eq!(person.surname.as_deref(), Some("Example"));
        let Address::Free(address) = person.address else {
            panic!("expected free-form address");
        };
        assert_eq!(address.country_code.as_deref(), Some("CZ"));
    }

    #[test]
    fn absent_data_has_operation_specific_empty_shapes() {
        for (operation, offset) in [(R18A_LIST, 13), (R18B_SEARCH, 14)] {
            let xml = operation_response(operation, None);
            let body = SoapBody::parse(
                xml.as_bytes(),
                Some("text/xml"),
                MimeLimits {
                    max_parts: 1,
                    max_decoded_bytes: 1024,
                    max_total_decoded_bytes: 1024,
                },
            )
            .unwrap();
            let response = match operation.service {
                Service::R18a => {
                    soap::decode_with_attachments(
                        body.xml,
                        &body.attachments,
                        operation,
                        REQUEST_UUID.parse().unwrap(),
                        limits(),
                        |data, attachments| {
                            decode_infrastructure_respondents(data, offset, attachments)
                                .map(|page| (page.offset, page.count))
                        },
                    )
                    .unwrap()
                    .value
                }
                Service::R18b => {
                    soap::decode_with_attachments(
                        body.xml,
                        &body.attachments,
                        operation,
                        REQUEST_UUID.parse().unwrap(),
                        limits(),
                        |data, _| {
                            decode_subjects_by_identification(data, offset)
                                .map(|page| (page.offset, page.count))
                        },
                    )
                    .unwrap()
                    .value
                }
                _ => unreachable!(),
            };
            assert_eq!(response, (offset, 0));
        }

        assert!(decode_subject_response(None).unwrap().is_none());
        assert!(decode_subjects_by_part(None).unwrap().is_empty());
    }

    #[test]
    fn rejects_malformed_choices_counts_and_preserves_unknown_roles() {
        let mismatch = "<p:ZaznamyOd>0</p:ZaznamyOd><p:PocetZaznamu>1</p:PocetZaznamu><r:Casti/>";
        let xml = operation_response(R18A_LIST, Some(mismatch));
        assert!(
            decode_without_files_result(R18A_LIST, &xml, |data| {
                decode_infrastructure_respondents(
                    data,
                    0,
                    &Attachments::inline(MimeLimits {
                        max_parts: 1,
                        max_decoded_bytes: 16,
                        max_total_decoded_bytes: 16,
                    }),
                )
            })
            .is_err()
        );

        let both_people = "<r:Subjekt><cs:Id>subject-1</cs:Id><s:Osoba><o:FyzickaOsoba/><o:PravnickaOsoba/></s:Osoba></r:Subjekt>";
        let xml = operation_response(R18B_SUBJECT, Some(both_people));
        assert!(decode_without_files_result(R18B_SUBJECT, &xml, decode_subject_response).is_err());

        let malformed = operation_response(R18B_SUBJECT, Some("<r:Subjekt>"));
        assert!(
            decode_without_files_result(R18B_SUBJECT, &malformed, decode_subject_response).is_err()
        );

        let unknown = InfrastructureSubjectRole::from_raw("FutureRole");
        assert_eq!(
            unknown,
            InfrastructureSubjectRole::Other("FutureRole".into())
        );
        assert_eq!(unknown.as_str(), "FutureRole");
        assert_eq!(
            InfrastructureSubjectRole::from_raw("Editor").as_str(),
            "Editor"
        );
    }
}