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
use crate::model::{
    Area, CorrelationId, InfrastructurePartId, InfrastructureRespondentPart,
    InfrastructureSubjectRole, Page, PageRequest, Response, SubjectId, SubjectInfo,
};
use crate::wire::registry;
use crate::wire::soap::{Operation, Service};
use crate::{Client, Result};

const LIST_INFRASTRUCTURE_RESPONDENTS: Operation = Operation::new(
    Service::R18a,
    "ctiVyjadrovatele",
    "CtiVyjadrovateleDti",
    "CtiVyjadrovateleDtiOdpoved",
);
const READ_SUBJECT: Operation = Operation::new(
    Service::R18b,
    "ctiSubjekt",
    "CtiSubjekt",
    "CtiSubjektOdpoved",
);
const READ_SUBJECT_BY_ORGANIZATION_NUMBER: Operation = Operation::new(
    Service::R18b,
    "ctiSubjektDleIco",
    "CtiSubjektDleIco",
    "CtiSubjektDleIcoOdpoved",
);
const SEARCH_SUBJECTS: Operation = Operation::new(
    Service::R18b,
    "ctiSubjektyDleIdentifikace",
    "CtiSubjektyDleIdentifikace",
    "CtiSubjektyDleIdentifikaceOdpoved",
);
const LIST_INFRASTRUCTURE_PART_SUBJECTS: Operation = Operation::new(
    Service::R18b,
    "ctiSubjektyDleCasti",
    "CtiSubjektyDleCasti",
    "CtiSubjektyDleCastiOdpoved",
);

fn checked_page(page: PageRequest) -> Result<PageRequest> {
    Ok(PageRequest::new(page.offset, page.limit)?.with_total(page.include_total))
}

impl Client {
    /// Lists one page of infrastructure parts and respondents for an area through R18a
    /// `ctiVyjadrovatele`.
    ///
    /// Optional supporting files may be inline or MTOM encoded. This method
    /// performs exactly one request without hidden pagination. No subject ID is
    /// serialized; transport authentication uses the client's TLS identity.
    pub async fn list_infrastructure_respondents(
        &self,
        area: &Area,
        page: PageRequest,
    ) -> Result<Response<Page<InfrastructureRespondentPart>>> {
        self.list_infrastructure_respondents_at(CorrelationId::new(), area, page)
            .await
    }

    async fn list_infrastructure_respondents_at(
        &self,
        correlation_id: CorrelationId,
        area: &Area,
        page: PageRequest,
    ) -> Result<Response<Page<InfrastructureRespondentPart>>> {
        let page = checked_page(page)?;
        self.execute_with_files(
            LIST_INFRASTRUCTURE_RESPONDENTS,
            correlation_id,
            |writer| registry::write_infrastructure_respondents_request(writer, area, page),
            |data, attachments| {
                registry::decode_infrastructure_respondents(data, page.offset, attachments)
            },
        )
        .await
    }

    /// Reads one subject by IS DMVS identifier through R18b `ctiSubjekt`.
    ///
    /// The argument identifies the lookup target, not the authenticated subject
    /// configured on the client. The result contains subject information only,
    /// not e-mail or telephone contacts. Missing `Data` is returned as `None`.
    pub async fn read_subject(&self, id: &SubjectId) -> Result<Response<Option<SubjectInfo>>> {
        self.read_subject_at(CorrelationId::new(), id).await
    }

    async fn read_subject_at(
        &self,
        correlation_id: CorrelationId,
        id: &SubjectId,
    ) -> Result<Response<Option<SubjectInfo>>> {
        self.execute(
            READ_SUBJECT,
            correlation_id,
            |writer| registry::write_subject_request(writer, id),
            registry::decode_subject_response,
        )
        .await
    }

    /// Reads one subject by IČO through R18b `ctiSubjektDleIco`.
    ///
    /// The XSD declares a plain string, so this method deliberately applies no
    /// eight-digit or other local IČO validation. Missing `Data` returns `None`.
    pub async fn read_subject_by_organization_number(
        &self,
        organization_number: &str,
    ) -> Result<Response<Option<SubjectInfo>>> {
        self.read_subject_by_organization_number_at(CorrelationId::new(), organization_number)
            .await
    }

    async fn read_subject_by_organization_number_at(
        &self,
        correlation_id: CorrelationId,
        organization_number: &str,
    ) -> Result<Response<Option<SubjectInfo>>> {
        self.execute(
            READ_SUBJECT_BY_ORGANIZATION_NUMBER,
            correlation_id,
            |writer| {
                registry::write_subject_by_organization_number_request(writer, organization_number)
            },
            registry::decode_subject_response,
        )
        .await
    }

    /// Searches subjects by name and optional role through R18b
    /// `ctiSubjektyDleIdentifikace`.
    ///
    /// `Editor` is permitted for this operation. Unknown roles are serialized
    /// unchanged. This method performs exactly one request without pagination.
    pub async fn search_subjects(
        &self,
        name: &str,
        role: Option<InfrastructureSubjectRole>,
        page: PageRequest,
    ) -> Result<Response<Page<SubjectInfo>>> {
        self.search_subjects_at(CorrelationId::new(), name, role.as_ref(), page)
            .await
    }

    async fn search_subjects_at(
        &self,
        correlation_id: CorrelationId,
        name: &str,
        role: Option<&InfrastructureSubjectRole>,
        page: PageRequest,
    ) -> Result<Response<Page<SubjectInfo>>> {
        let page = checked_page(page)?;
        self.execute(
            SEARCH_SUBJECTS,
            correlation_id,
            |writer| registry::write_subjects_by_identification_request(writer, name, role, page),
            |data| registry::decode_subjects_by_identification(data, page.offset),
        )
        .await
    }

    /// Lists subjects associated with an infrastructure part through R18b
    /// `ctiSubjektyDleCasti`.
    ///
    /// `Editor` is rejected before any network request because it is not valid
    /// for this method. Missing `Data` maps to an empty vector.
    pub async fn list_infrastructure_part_subjects(
        &self,
        id: &InfrastructurePartId,
        role: Option<InfrastructureSubjectRole>,
    ) -> Result<Response<Vec<SubjectInfo>>> {
        self.list_infrastructure_part_subjects_at(CorrelationId::new(), id, role.as_ref())
            .await
    }

    async fn list_infrastructure_part_subjects_at(
        &self,
        correlation_id: CorrelationId,
        id: &InfrastructurePartId,
        role: Option<&InfrastructureSubjectRole>,
    ) -> Result<Response<Vec<SubjectInfo>>> {
        if role.is_some_and(|role| role.as_str() == "Editor") {
            return Err(crate::Error::invalid_input(
                "role",
                "Editor is not supported by ctiSubjektyDleCasti",
            ));
        }
        self.execute(
            LIST_INFRASTRUCTURE_PART_SUBJECTS,
            correlation_id,
            |writer| registry::write_subjects_by_part_request(writer, id, role),
            registry::decode_subjects_by_part,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use geo_types::{LineString, Polygon, coord};
    use wiremock::matchers::{body_string, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;
    use crate::wire::registry::COMMON_NS;
    use crate::wire::soap;

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

    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 operation_response(
        operation: Operation,
        request_id: CorrelationId,
        data: Option<&str>,
    ) -> String {
        let request_id = request_id.as_uuid();
        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}\"><soap:Body><r:{}><m:Hlavicka><m:UidOdpovedi>{RESPONSE_UUID}</m:UidOdpovedi><m:Vysledek stav=\"OK\"><m:UidZadosti>{request_id}</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,
            operation.response,
            operation.response,
        )
    }

    async fn expect_exchange(
        server: &MockServer,
        operation: Operation,
        request: Vec<u8>,
        response: String,
    ) {
        Mock::given(method("POST"))
            .and(path(format!("/{}", operation.service.path())))
            .and(header("SOAPAction", format!("\"{}\"", operation.action)))
            .and(header("Content-Type", "text/xml; charset=utf-8"))
            .and(body_string(String::from_utf8(request).unwrap()))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(response, "text/xml; charset=utf-8"),
            )
            .expect(1)
            .mount(server)
            .await;
    }

    #[test]
    fn operation_descriptors_match_the_official_wsdl() {
        let operations = [
            (
                LIST_INFRASTRUCTURE_RESPONDENTS,
                "ctiVyjadrovatele",
                "CtiVyjadrovateleDti",
                "CtiVyjadrovateleDtiOdpoved",
                "R18aCteniVyjadrovateluDti",
                "urn:cz:isvs:dmvs:isdmvs:schemas:R18aCteniVyjadrovateluDti:v1",
            ),
            (
                READ_SUBJECT,
                "ctiSubjekt",
                "CtiSubjekt",
                "CtiSubjektOdpoved",
                "R18bCteniSubjektu",
                "urn:cz:isvs:dmvs:isdmvs:schemas:R18bCteniSubjektu:v1",
            ),
            (
                READ_SUBJECT_BY_ORGANIZATION_NUMBER,
                "ctiSubjektDleIco",
                "CtiSubjektDleIco",
                "CtiSubjektDleIcoOdpoved",
                "R18bCteniSubjektu",
                "urn:cz:isvs:dmvs:isdmvs:schemas:R18bCteniSubjektu:v1",
            ),
            (
                SEARCH_SUBJECTS,
                "ctiSubjektyDleIdentifikace",
                "CtiSubjektyDleIdentifikace",
                "CtiSubjektyDleIdentifikaceOdpoved",
                "R18bCteniSubjektu",
                "urn:cz:isvs:dmvs:isdmvs:schemas:R18bCteniSubjektu:v1",
            ),
            (
                LIST_INFRASTRUCTURE_PART_SUBJECTS,
                "ctiSubjektyDleCasti",
                "CtiSubjektyDleCasti",
                "CtiSubjektyDleCastiOdpoved",
                "R18bCteniSubjektu",
                "urn:cz:isvs:dmvs:isdmvs:schemas:R18bCteniSubjektu:v1",
            ),
        ];
        for (operation, action, request, response, path_name, namespace) in operations {
            assert_eq!(operation.action, action);
            assert_eq!(operation.request, request);
            assert_eq!(operation.response, response);
            assert_eq!(operation.service.path(), path_name);
            assert_eq!(operation.service.namespace(), namespace);
        }
    }

    #[tokio::test]
    async fn wiremock_executes_all_five_operations_with_exact_requests() {
        let server = MockServer::start().await;
        let id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let part_id = InfrastructurePartId::new("part-1").unwrap();
        let subject_id = SubjectId::new("subject-1").unwrap();
        let page = PageRequest {
            offset: 7,
            limit: 25,
            include_total: false,
        };

        let requests = [
            soap::request(LIST_INFRASTRUCTURE_RESPONDENTS, id, |writer| {
                registry::write_infrastructure_respondents_request(writer, &area(), page)
            })
            .unwrap(),
            soap::request(READ_SUBJECT, id, |writer| {
                registry::write_subject_request(writer, &subject_id)
            })
            .unwrap(),
            soap::request(READ_SUBJECT_BY_ORGANIZATION_NUMBER, id, |writer| {
                registry::write_subject_by_organization_number_request(writer, "not-validated")
            })
            .unwrap(),
            soap::request(SEARCH_SUBJECTS, id, |writer| {
                registry::write_subjects_by_identification_request(
                    writer,
                    "Example",
                    Some(&InfrastructureSubjectRole::Editor),
                    page,
                )
            })
            .unwrap(),
            soap::request(LIST_INFRASTRUCTURE_PART_SUBJECTS, id, |writer| {
                registry::write_subjects_by_part_request(
                    writer,
                    &part_id,
                    Some(&InfrastructureSubjectRole::Owner),
                )
            })
            .unwrap(),
        ];
        for (operation, request) in [
            LIST_INFRASTRUCTURE_RESPONDENTS,
            READ_SUBJECT,
            READ_SUBJECT_BY_ORGANIZATION_NUMBER,
            SEARCH_SUBJECTS,
            LIST_INFRASTRUCTURE_PART_SUBJECTS,
        ]
        .into_iter()
        .zip(requests)
        {
            expect_exchange(
                &server,
                operation,
                request,
                operation_response(operation, id, None),
            )
            .await;
        }

        let client = Client::test_client(server.uri());
        assert_eq!(
            client
                .list_infrastructure_respondents_at(id, &area(), page)
                .await
                .unwrap()
                .value
                .offset,
            7
        );
        assert!(
            client
                .read_subject_at(id, &subject_id)
                .await
                .unwrap()
                .value
                .is_none()
        );
        assert!(
            client
                .read_subject_by_organization_number_at(id, "not-validated")
                .await
                .unwrap()
                .value
                .is_none()
        );
        assert_eq!(
            client
                .search_subjects_at(
                    id,
                    "Example",
                    Some(&InfrastructureSubjectRole::Editor),
                    page
                )
                .await
                .unwrap()
                .value
                .offset,
            7
        );
        let response = client
            .list_infrastructure_part_subjects_at(
                id,
                &part_id,
                Some(&InfrastructureSubjectRole::Owner),
            )
            .await
            .unwrap();
        assert!(response.value.is_empty());
        assert_eq!(response.metadata.request_id, id);
        server.verify().await;
    }

    #[tokio::test]
    async fn editor_is_rejected_for_part_search_before_transport() {
        let server = MockServer::start().await;
        let client = Client::test_client(server.uri());
        let id = InfrastructurePartId::new("part-1").unwrap();
        let error = client
            .list_infrastructure_part_subjects(&id, Some(InfrastructureSubjectRole::Editor))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            crate::Error::InvalidInput { field: "role", .. }
        ));
        server.verify().await;
    }
}