prelude-xml-parser 0.10.0

Deserialize Prelude EDC native XML files into Rust stucts.
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
use std::collections::HashMap;

use chrono::{DateTime, Utc};

#[cfg(feature = "python")]
use pyo3::{
    exceptions::PyValueError,
    prelude::*,
    types::{PyDateTime, PyDict},
};

use serde::{Deserialize, Serialize};

pub use crate::native::common::{Category, Comment, Entry, Field, Form, Reason, State, Value};

#[cfg(feature = "python")]
use crate::native::deserializers::to_py_datetime;

#[cfg(not(feature = "python"))]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Site {
    #[serde(alias = "@name")]
    #[serde(alias = "name")]
    pub name: String,
    #[serde(rename = "uniqueId")]
    #[serde(alias = "@uniqueId")]
    #[serde(alias = "uniqueId")]
    pub unique_id: String,
    #[serde(rename = "numberOfPatients")]
    #[serde(alias = "@numberOfPatients")]
    #[serde(alias = "numberOfPatients")]
    pub number_of_patients: usize,
    #[serde(rename = "countOfRandomizedPatients")]
    #[serde(alias = "@countOfRandomizedPatients")]
    #[serde(alias = "countOfRandomizedPatients")]
    pub count_of_randomized_patients: usize,
    #[serde(rename = "whenCreated")]
    #[serde(alias = "@whenCreated")]
    #[serde(alias = "whenCreated")]
    pub when_created: Option<DateTime<Utc>>,
    #[serde(alias = "@creator")]
    #[serde(alias = "creator")]
    pub creator: String,
    #[serde(rename = "numberOfForms")]
    #[serde(alias = "@numberOfForms")]
    #[serde(alias = "numberOfForms")]
    pub number_of_forms: usize,

    #[serde(rename = "form")]
    #[serde(alias = "form")]
    pub forms: Option<Vec<Form>>,
}

#[cfg(not(feature = "python"))]
impl Site {
    pub fn from_attributes(attrs: HashMap<String, String>) -> Result<Self, crate::errors::Error> {
        let name = attrs.get("name").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing name".to_string(),
            ))
        })?;

        let unique_id = attrs.get("uniqueId").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing uniqueId".to_string(),
            ))
        })?;

        let number_of_patients = attrs
            .get("numberOfPatients")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let count_of_randomized_patients = attrs
            .get("countOfRandomizedPatients")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let when_created = if let Some(wc_str) = attrs.get("whenCreated") {
            if wc_str.is_empty() {
                None
            } else {
                Some(parse_datetime(wc_str)?)
            }
        } else {
            None
        };

        let creator = attrs.get("creator").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing creator".to_string(),
            ))
        })?;

        let number_of_forms = attrs
            .get("numberOfForms")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        Ok(Site {
            name,
            unique_id,
            number_of_patients,
            count_of_randomized_patients,
            when_created,
            creator,
            number_of_forms,
            forms: None,
        })
    }

    pub fn set_forms(&mut self, forms: Vec<Form>) {
        self.forms = if forms.is_empty() { None } else { Some(forms) };
    }
}

fn parse_datetime(s: &str) -> Result<DateTime<Utc>, crate::errors::Error> {
    if let Ok(dt) = chrono::DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S %z") {
        Ok(dt.with_timezone(&Utc))
    } else if let Ok(dt) = chrono::DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%z") {
        Ok(dt.with_timezone(&Utc))
    } else if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
        Ok(dt.with_timezone(&Utc))
    } else {
        Err(crate::errors::Error::ParsingError(
            quick_xml::de::DeError::Custom(format!("Invalid datetime format: {}", s)),
        ))
    }
}

#[cfg(feature = "python")]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[pyclass(skip_from_py_object)]
pub struct Site {
    #[serde(alias = "@name")]
    #[serde(alias = "name")]
    pub name: String,
    #[serde(rename = "uniqueId")]
    #[serde(alias = "@uniqueId")]
    #[serde(alias = "uniqueId")]
    pub unique_id: String,
    #[serde(rename = "numberOfPatients")]
    #[serde(alias = "@numberOfPatients")]
    #[serde(alias = "numberOfPatients")]
    pub number_of_patients: usize,
    #[serde(rename = "countOfRandomizedPatients")]
    #[serde(alias = "@countOfRandomizedPatients")]
    #[serde(alias = "countOfRandomizedPatients")]
    pub count_of_randomized_patients: usize,
    #[serde(rename = "whenCreated")]
    #[serde(alias = "@whenCreated")]
    #[serde(alias = "whenCreated")]
    pub when_created: Option<DateTime<Utc>>,
    #[serde(alias = "@creator")]
    #[serde(alias = "creator")]
    pub creator: String,
    #[serde(rename = "numberOfForms")]
    #[serde(alias = "@numberOfForms")]
    #[serde(alias = "numberOfForms")]
    pub number_of_forms: usize,

    #[serde(rename = "form")]
    #[serde(alias = "form")]
    pub forms: Option<Vec<Form>>,
}

#[cfg(feature = "python")]
impl Site {
    pub fn from_attributes(attrs: HashMap<String, String>) -> Result<Self, crate::errors::Error> {
        let name = attrs.get("name").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing name".to_string(),
            ))
        })?;

        let unique_id = attrs.get("uniqueId").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing uniqueId".to_string(),
            ))
        })?;

        let number_of_patients = attrs
            .get("numberOfPatients")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let count_of_randomized_patients = attrs
            .get("countOfRandomizedPatients")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let when_created = if let Some(wc_str) = attrs.get("whenCreated") {
            if wc_str.is_empty() {
                None
            } else {
                Some(parse_datetime(wc_str)?)
            }
        } else {
            None
        };

        let creator = attrs.get("creator").cloned().ok_or_else(|| {
            crate::errors::Error::ParsingError(quick_xml::de::DeError::Custom(
                "Missing creator".to_string(),
            ))
        })?;

        let number_of_forms = attrs
            .get("numberOfForms")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        Ok(Site {
            name,
            unique_id,
            number_of_patients,
            count_of_randomized_patients,
            when_created,
            creator,
            number_of_forms,
            forms: None,
        })
    }

    pub fn set_forms(&mut self, forms: Vec<Form>) {
        self.forms = if forms.is_empty() { None } else { Some(forms) };
    }
}

#[cfg(feature = "python")]
#[pymethods]
impl Site {
    #[getter]
    fn name(&self) -> PyResult<String> {
        Ok(self.name.clone())
    }

    #[getter]
    fn unique_id(&self) -> PyResult<String> {
        Ok(self.unique_id.clone())
    }

    #[getter]
    fn number_of_patients(&self) -> PyResult<usize> {
        Ok(self.number_of_patients)
    }

    #[getter]
    fn count_of_randomized_patients(&self) -> PyResult<usize> {
        Ok(self.count_of_randomized_patients)
    }

    #[getter]
    fn when_created<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyDateTime>>> {
        self.when_created
            .as_ref()
            .map(|dt| to_py_datetime(py, dt))
            .transpose()
    }

    #[getter]
    fn creator(&self) -> PyResult<String> {
        Ok(self.creator.clone())
    }

    #[getter]
    fn number_of_forms(&self) -> PyResult<usize> {
        Ok(self.number_of_forms)
    }

    #[getter]
    fn forms(&self) -> PyResult<Option<Vec<Form>>> {
        Ok(self.forms.clone())
    }

    pub fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        dict.set_item("name", &self.name)?;
        dict.set_item("unique_id", &self.unique_id)?;
        dict.set_item("number_of_patients", self.number_of_patients)?;
        dict.set_item(
            "count_of_randomized_patients",
            self.count_of_randomized_patients,
        )?;
        dict.set_item(
            "when_created",
            self.when_created
                .as_ref()
                .map(|dt| to_py_datetime(py, dt))
                .transpose()?,
        )?;
        dict.set_item("creator", &self.creator)?;
        dict.set_item("number_of_forms", self.number_of_forms)?;

        let mut form_dicts = Vec::new();
        if let Some(forms) = &self.forms {
            for form in forms {
                let form_dict = form.to_dict(py)?;
                form_dicts.push(form_dict);
            }
            dict.set_item("forms", form_dicts)?;
        } else {
            dict.set_item("forms", py.None())?;
        }

        Ok(dict)
    }
}

#[cfg(not(feature = "python"))]
/// Contains the information from the Prelude native site XML.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SiteNative {
    #[serde(alias = "site")]
    pub sites: Vec<Site>,
}

#[cfg(not(feature = "python"))]
impl SiteNative {
    /// Convert to a JSON string
    ///
    /// # Example
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use prelude_xml_parser::parse_site_native_file;
    ///
    /// let file_path = Path::new("tests/assets/site_native_small.xml");
    /// let native = parse_site_native_file(&file_path).unwrap();
    /// let json = native.to_json().unwrap();
    /// println!("{json}");
    /// // Verify the JSON contains expected site data
    /// assert!(json.contains("Some Site"));
    /// assert!(json.contains("Paul Sanders"));
    /// assert!(json.contains("Some Company"));
    /// ```
    pub fn to_json(&self) -> serde_json::Result<String> {
        let json = serde_json::to_string(&self)?;

        Ok(json)
    }
}

#[cfg(feature = "python")]
/// Contains the information from the Prelude native site XML.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[pyclass(get_all, skip_from_py_object)]
pub struct SiteNative {
    #[serde(alias = "site")]
    pub sites: Vec<Site>,
}

#[cfg(feature = "python")]
#[pymethods]
impl SiteNative {
    #[getter]
    fn sites(&self) -> PyResult<Vec<Site>> {
        Ok(self.sites.clone())
    }

    /// Convert the class instance to a dictionary
    fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        let mut site_dicts = Vec::new();
        for site in &self.sites {
            let site_dict = site.to_dict(py)?;
            site_dicts.push(site_dict);
        }
        dict.set_item("sites", site_dicts)?;
        Ok(dict)
    }

    /// Convert the class instance to a JSON string
    fn to_json(&self) -> PyResult<String> {
        serde_json::to_string(&self)
            .map_err(|_| PyErr::new::<PyValueError, _>("Error converting to JSON"))
    }
}

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

    #[test]
    fn deserialize_site_native_json() {
        let json_str = r#"{
  "sites": [
    {
      "name": "Some Site",
      "uniqueId": "1681574834910",
      "numberOfPatients": 4,
      "countOfRandomizedPatients": 0,
      "whenCreated": "2023-04-15T16:08:19Z",
      "creator": "Paul Sanders",
      "numberOfForms": 1,
      "forms": [
        {
          "name": "demographic.form.name.site.demographics",
          "lastModified": "2023-04-15T16:08:19Z",
          "whoLastModifiedName": "Paul Sanders",
          "whoLastModifiedRole": "Project Manager",
          "whenCreated": 1681574834930,
          "hasErrors": false,
          "hasWarnings": false,
          "locked": false,
          "user": null,
          "dateTimeChanged": null,
          "formTitle": "Site Demographics",
          "formIndex": 1,
          "formGroup": "Demographic",
          "formState": "In-Work",
          "states": [
            {
              "value": "form.state.in.work",
              "signer": "Paul Sanders - Project Manager",
              "signerUniqueId": "1681162687395",
              "dateSigned": "2023-04-15T16:08:19Z"
            }
          ],
          "categories": [
            {
              "name": "Demographics",
              "categoryType": "normal",
              "highestIndex": 0,
              "fields": [
                {
                  "name": "address",
                  "fieldType": "text",
                  "dataType": "string",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entry": null
                },
                {
                  "name": "company",
                  "fieldType": "text",
                  "dataType": "string",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entries": [
                    {
                      "entryId": "1",
                      "value": {
                        "by": "Paul Sanders",
                        "byUniqueId": "1681162687395",
                        "role": "Project Manager",
                        "when": "2023-04-15T16:08:19Z",
                        "value": "Some Company"
                      },
                      "reason": null
                    }
                  ]
                },
                {
                  "name": "site_code_name",
                  "fieldType": "hidden",
                  "dataType": "string",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entry": [
                    {
                      "entryId": "1",
                      "value": {
                        "by": "set from calculation",
                        "byUniqueId": null,
                        "role": "System",
                        "when": "2023-04-15T16:08:19Z",
                        "value": "ABC-Some Site"
                      },
                      "reason": {
                        "by": "set from calculation",
                        "byUniqueId": null,
                        "role": "System",
                        "when": "2023-04-15T16:08:19Z",
                        "value": "calculated value"
                      }
                    },
                    {
                      "entryId": "2",
                      "value": {
                        "by": "set from calculation",
                        "byUniqueId": null,
                        "role": "System",
                        "when": "2023-04-15T16:07:24Z",
                        "value": "Some Site"
                      },
                      "reason": {
                        "by": "set from calculation",
                        "byUniqueId": null,
                        "role": "System",
                        "when": "2023-04-15T16:07:24Z",
                        "value": "calculated value"
                      }
                    }
                  ]
                }
              ]
            },
            {
              "name": "Enrollment",
              "categoryType": "normal",
              "highestIndex": 0,
              "field": [
                {
                  "name": "enrollment_closed_date",
                  "fieldType": "popUpCalendar",
                  "dataType": "date",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entry": null
                },
                {
                  "name": "enrollment_open",
                  "fieldType": "radio",
                  "dataType": "string",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entry": [
                    {
                      "entryId": "1",
                      "value": {
                        "by": "Paul Sanders",
                        "byUniqueId": "1681162687395",
                        "role": "Project Manager",
                        "when": "2023-04-15T16:08:19Z",
                        "value": "Yes"
                      },
                      "reason": null
                    }
                  ]
                },
                {
                  "name": "enrollment_open_date",
                  "fieldType": "popUpCalendar",
                  "dataType": "date",
                  "errorCode": "valid",
                  "whenCreated": "2023-04-15T16:07:14Z",
                  "keepHistory": true,
                  "entry": null
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "Artemis",
      "uniqueId": "1691420994591",
      "numberOfPatients": 0,
      "countOfRandomizedPatients": 0,
      "whenCreated": "2023-08-07T15:14:23Z",
      "creator": "Paul Sanders",
      "numberOfForms": 1,
      "forms": [
        {
          "name": "demographic.form.name.site.demographics",
          "lastModified": "2023-08-07T15:14:23Z",
          "whoLastModifiedName": "Paul Sanders",
          "whoLastModifiedRole": "Project Manager",
          "whenCreated": 1691420994611,
          "hasErrors": false,
          "hasWarnings": false,
          "locked": false,
          "user": null,
          "dateTimeChanged": null,
          "formTitle": "Site Demographics",
          "formIndex": 1,
          "formGroup": "Demographic",
          "formState": "In-Work",
          "states": [
            {
              "value": "form.state.in.work",
              "signer": "Paul Sanders - Project Manager",
              "signerUniqueId": "1681162687395",
              "dateSigned": "2023-08-07T15:14:23Z"
            }
          ],
          "categories": [
            {
              "name": "Demographics",
              "categoryType": "normal",
              "highestIndex": 0,
              "fields": [
                {
                  "name": "address",
                  "fieldType": "text",
                  "dataType": "string",
                  "errorCode": "valid",
                  "whenCreated": "2023-08-07T15:09:54Z",
                  "keepHistory": true,
                  "entries": [
                    {
                      "entryId": "1",
                      "value": {
                        "by": "Paul Sanders",
                        "byUniqueId": "1681162687395",
                        "role": "Project Manager",
                        "when": "2023-08-07T15:14:21Z",
                        "value": "1111 Moon Drive"
                      },
                      "reason": null
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
        "#;

        let result: SiteNative = serde_json::from_str(json_str).unwrap();

        assert_yaml_snapshot!(result);
    }
}