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
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use yaserde_derive::{YaDeserialize, YaSerialize};

use crate::{
    Attribution, ConfidenceLevel, EnumAsString, Id, Lang, Note, ResourceReference, SourceReference,
    Uri,
};

/// The base conceptual model for genealogical data that are managed as textual
/// documents.
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, YaSerialize, YaDeserialize, PartialEq, Default, Clone)]
#[yaserde(
    prefix = "gx",
    default_namespace = "gx",
    namespace = "gx: http://gedcomx.org/v1/"
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Document {
    /// An identifier for the conclusion data. The id is to be used as a "fragment identifier" as defined by [RFC 3986, Section 3.5](https://tools.ietf.org/html/rfc3986#section-3.5).
    #[yaserde(attribute)]
    pub id: Option<Id>,

    /// The locale identifier for the conclusion.
    #[yaserde(attribute, prefix = "xml")]
    pub lang: Option<Lang>,

    /// The list of references to the sources of related to this conclusion.
    /// Note that the sources referenced from conclusions are also considered
    /// to be sources of the entities that contain them. For example, a source
    /// associated with the `Name` of a `Person` is also source for the
    /// `Person`.
    #[yaserde(rename = "source", prefix = "gx")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub sources: Vec<SourceReference>,

    /// A reference to the analysis document explaining the analysis that went
    /// into this conclusion. If provided, MUST resolve to an instance of
    /// [Document](crate::Document) of type
    /// [Analysis](crate::DocumentType::Analysis).
    #[yaserde(prefix = "gx")]
    pub analysis: Option<ResourceReference>,

    /// A list of notes about this conclusion.
    #[yaserde(rename = "note", prefix = "gx")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub notes: Vec<Note>,

    /// The level of confidence the contributor has about the data.
    #[yaserde(attribute)]
    pub confidence: Option<ConfidenceLevel>,

    /// The attribution of this conclusion.
    /// If not provided, the attribution of the containing data set (e.g. file)
    /// of the conclusion is assumed.
    #[yaserde(prefix = "gx")]
    pub attribution: Option<Attribution>,

    /// Enumerated value identifying the type of the document.
    #[yaserde(rename = "type", attribute)]
    #[serde(rename = "type")]
    pub document_type: Option<DocumentType>,

    /// Whether this document is to be constrained as an extracted conclusion,
    /// meaning it captures information extracted from a single source.
    #[yaserde(attribute)]
    pub extracted: Option<bool>,

    /// The type of text in the `text` property.
    ///
    /// If no value is provided, "plain" is assumed.
    #[yaserde(rename = "textType", attribute)]
    pub text_type: Option<TextType>,

    /// The text of the document.
    #[yaserde(prefix = "gx")]
    pub text: String,
}

impl Document {
    pub fn new(
        id: Option<Id>,
        lang: Option<Lang>,
        sources: Vec<SourceReference>,
        analysis: Option<ResourceReference>,
        notes: Vec<Note>,
        confidence: Option<ConfidenceLevel>,
        attribution: Option<Attribution>,
        document_type: Option<DocumentType>,
        extracted: Option<bool>,
        text_type: Option<TextType>,
        text: String,
    ) -> Self {
        Self {
            id,
            lang,
            sources,
            analysis,
            notes,
            confidence,
            attribution,
            document_type,
            extracted,
            text_type,
            text,
        }
    }

    pub fn builder<I: Into<String>>(text: I) -> DocumentBuilder {
        DocumentBuilder::new(text)
    }
}

pub struct DocumentBuilder(Document);

impl DocumentBuilder {
    conclusion_builder_functions!(Document);

    pub(crate) fn new<I: Into<String>>(text: I) -> Self {
        Self(Document {
            text: text.into(),
            ..Document::default()
        })
    }

    pub fn document_type(&mut self, document_type: DocumentType) -> &mut Self {
        self.0.document_type = Some(document_type);
        self
    }

    pub fn extracted(&mut self, extracted: bool) -> &mut Self {
        self.0.extracted = Some(extracted);
        self
    }

    pub fn text_type(&mut self, text_type: TextType) -> &mut Self {
        self.0.text_type = Some(text_type);
        self
    }

    pub fn build(&self) -> Document {
        Document::new(
            self.0.id.clone(),
            self.0.lang.clone(),
            self.0.sources.clone(),
            self.0.analysis.clone(),
            self.0.notes.clone(),
            self.0.confidence.clone(),
            self.0.attribution.clone(),
            self.0.document_type.clone(),
            self.0.extracted,
            self.0.text_type.clone(),
            self.0.text.clone(),
        )
    }
}

/// Document types
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[non_exhaustive]
#[serde(from = "EnumAsString", into = "EnumAsString")]
pub enum DocumentType {
    /// The document is an analysis done by a researcher; a genealogical proof
    /// statement is an example of one kind of analysis document.
    Analysis,

    /// The document is an abstract of a record or document.
    Abstract,

    /// The document is a transcription of a record or document.
    Transcription,

    /// The document is a translation of a record or document.
    Translation,
    Custom(Uri),
}

impl_enumasstring_yaserialize_yadeserialize!(DocumentType, "DocumentType");

impl From<EnumAsString> for DocumentType {
    fn from(f: EnumAsString) -> Self {
        match f.0.as_ref() {
            "http://gedcomx.org/Analysis" => Self::Analysis,
            "http://gedcomx.org/Abstract" => Self::Abstract,
            "http://gedcomx.org/Transcription" => Self::Transcription,
            "http://gedcomx.org/Translation" => Self::Translation,
            _ => Self::Custom(f.0.into()),
        }
    }
}

impl fmt::Display for DocumentType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Analysis => write!(f, "http://gedcomx.org/Analysis"),
            Self::Abstract => write!(f, "http://gedcomx.org/Abstract"),
            Self::Transcription => write!(f, "http://gedcomx.org/Transcription"),
            Self::Translation => write!(f, "http://gedcomx.org/Translation"),
            Self::Custom(c) => write!(f, "{}", c),
        }
    }
}

impl Default for DocumentType {
    fn default() -> Self {
        Self::Custom(Uri::default())
    }
}

/// In some cases, a text value must include styling or layout to fully convey
/// its intended meaning. Where such a requirement has been identified,
/// implementers can designate that a text value may include such styling or
/// layout by specifying an alternate text type.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[non_exhaustive]
#[serde(from = "EnumAsString", into = "EnumAsString")]
pub enum TextType {
    /// The `Plain` text type identifies plain text. `Plain` is the default text
    /// type for text without an explicitly specified type.
    Plain,

    /// The `Xhtml` text type identifies XHTML text complying with the [XHTML 1.0 W3C Recommendation](http://www.w3.org/TR/xhtml1/).
    Xhtml,
}

impl_enumasstring_yaserialize_yadeserialize!(TextType, "TextType");

impl From<EnumAsString> for TextType {
    fn from(f: EnumAsString) -> Self {
        match f.0.as_ref() {
            "xhtml" => Self::Xhtml,
            "plain" => Self::Plain,
            _ => Self::default(),
        }
    }
}

impl fmt::Display for TextType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Plain => write!(f, "plain"),
            Self::Xhtml => write!(f, "xhtml"),
        }
    }
}

impl Default for TextType {
    fn default() -> Self {
        Self::Plain
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn json_deserialize() {
        let json = r#"{          
            "extracted" : false,
            "type" : "http://gedcomx.org/Analysis",
            "textType" : "plain",
            "text" : "...text of the document..."
          }"#;

        let document: Document = serde_json::from_str(json).unwrap();

        assert_eq!(
            document,
            Document::builder("...text of the document...")
                .document_type(DocumentType::Analysis)
                .extracted(false)
                .text_type(TextType::Plain)
                .build()
        )
    }

    #[test]
    fn json_serialize() {
        let document = Document::builder("...text of the document...")
            .document_type(DocumentType::Analysis)
            .extracted(false)
            .text_type(TextType::Plain)
            .build();

        let json = serde_json::to_string(&document).unwrap();

        assert_eq!(
            json,
            r#"{"type":"http://gedcomx.org/Analysis","extracted":false,"textType":"plain","text":"...text of the document..."}"#
        )
    }

    #[test]
    fn xml_deserialize() {
        let xml = r#"
        <Document xmlns="http://gedcomx.org/v1/" type="http://gedcomx.org/Analysis" extracted="false" textType="plain">    
        <text>...text of the document...</text>
        </Document>"#;

        let document: Document = yaserde::de::from_str(xml).unwrap();

        assert_eq!(
            document,
            Document::builder("...text of the document...")
                .document_type(DocumentType::Analysis)
                .extracted(false)
                .text_type(TextType::Plain)
                .build()
        )
    }

    #[test]
    fn xml_serialize() {
        let document = Document::builder("...text of the document...")
            .document_type(DocumentType::Analysis)
            .extracted(false)
            .text_type(TextType::Plain)
            .build();

        let mut config = yaserde::ser::Config::default();
        config.write_document_declaration = false;
        let xml = yaserde::ser::to_string_with_config(&document, &config).unwrap();

        assert_eq!(
            xml,
            r#"<Document xmlns="http://gedcomx.org/v1/" type="http://gedcomx.org/Analysis" extracted="false" textType="plain"><text>...text of the document...</text></Document>"#
        )
    }
}