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

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

use crate::{Agent, ResourceReference, Result, Timestamp};

/// The data structure used to attribute who, when, and why to genealogical
/// data.
///
/// Data is attributed to the agent who made the latest significant change to
/// the nature of the data being attributed.
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, YaSerialize, YaDeserialize, PartialEq, Clone, Default)]
#[yaserde(
    rename = "attribution",
    prefix = "gx",
    default_namespace = "gx",
    namespace = "gx: http://gedcomx.org/v1/"
)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Attribution {
    /// Reference to the agent to whom the attributed data is attributed. If
    /// provided, MUST resolve to an instance of [`Agent`](crate::Agent).
    #[yaserde(prefix = "gx")]
    pub contributor: Option<ResourceReference>,

    /// Timestamp of when the attributed data was modified.
    #[yaserde(prefix = "gx")]
    pub modified: Option<Timestamp>,

    /// A statement of why the attributed data is being provided by the
    /// contributor.
    #[yaserde(rename = "changeMessage", prefix = "gx")]
    pub change_message: Option<String>,

    /// Reference to the agent that created the attributed data. The creator MAY
    /// be different from the contributor if changes were made to the
    /// attributed data. If provided, MUST resolve to an instance of
    /// [`Agent`](crate::Agent).
    #[yaserde(prefix = "gx")]
    pub creator: Option<ResourceReference>,

    /// Timestamp of when the attributed data was contributed.
    #[yaserde(prefix = "gx")]
    pub created: Option<Timestamp>,
}

impl Attribution {
    pub fn new(
        contributor: Option<ResourceReference>,
        modified: Option<Timestamp>,
        change_message: Option<String>,
        creator: Option<ResourceReference>,
        created: Option<Timestamp>,
    ) -> Self {
        Self {
            contributor,
            modified,
            change_message,
            creator,
            created,
        }
    }

    pub fn builder() -> AttributionBuilder {
        AttributionBuilder::new()
    }
}

pub struct AttributionBuilder(Attribution);

impl AttributionBuilder {
    pub(crate) fn new() -> Self {
        Self(Attribution::default())
    }

    /// # Errors
    ///
    /// Will return [`GedcomxError::NoId`](crate::GedcomxError::NoId) if a
    /// conversion into [`ResourceReference`](crate::ResourceReference) fails.
    /// This happens if `agent` has no `id` set.
    pub fn contributor(&mut self, agent: &Agent) -> Result<&mut Self> {
        self.0.contributor = Some(agent.try_into()?);
        Ok(self)
    }

    pub fn modified<I: Into<Timestamp>>(&mut self, timestamp: I) -> &mut Self {
        self.0.modified = Some(timestamp.into());
        self
    }

    pub fn change_message<I: Into<String>>(&mut self, change_message: I) -> &mut Self {
        self.0.change_message = Some(change_message.into());
        self
    }

    /// # Errors
    ///
    /// Will return [`GedcomxError::NoId`](crate::GedcomxError::NoId) if a
    /// conversion into [`ResourceReference`](crate::ResourceReference) fails.
    /// This happens if `agent` has no `id` set.
    pub fn creator(&mut self, agent: &Agent) -> Result<&mut Self> {
        self.0.creator = Some(agent.try_into()?);
        Ok(self)
    }

    pub fn created<I: Into<Timestamp>>(&mut self, timestamp: I) -> &mut Self {
        self.0.created = Some(timestamp.into());
        self
    }

    pub fn build(&self) -> Attribution {
        Attribution::new(
            self.0.contributor.clone(),
            self.0.modified.clone(),
            self.0.change_message.clone(),
            self.0.creator.clone(),
            self.0.created.clone(),
        )
    }
}

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

    use super::*;
    use crate::GedcomxError;

    #[test]
    fn builder() {
        let creator = Agent::builder().id("creator").build();
        let contributor = Agent::builder().id("contributor").build();

        let expected = Attribution {
            contributor: Some((&contributor).try_into().unwrap()),
            modified: Some(Timestamp::default()),
            change_message: Some("change message".to_string()),
            creator: Some((&creator).try_into().unwrap()),
            created: Some(Timestamp::default()),
        };

        let actual = Attribution::builder()
            .contributor(&contributor)
            .unwrap()
            .modified(Timestamp::default())
            .change_message("change message")
            .creator(&creator)
            .unwrap()
            .created(Timestamp::default())
            .build();

        assert_eq!(actual, expected)
    }

    #[test]
    fn builder_fails_correctly() {
        let creator = Agent::default();
        let contributor = Agent::default();
        let expected = GedcomxError::NoId(String::from("Agent")).to_string();

        let actual = Attribution::builder()
            .contributor(&contributor)
            .map(|b| b.build());
        assert_eq!(actual.unwrap_err().to_string(), expected);

        let actual = Attribution::builder().creator(&creator).map(|b| b.build());
        assert_eq!(actual.unwrap_err().to_string(), expected)
    }

    #[test]
    fn json_deserialize() {
        let json = r#"{
            "contributor" : {
                "resource" : "http://identifier/for/contributor"
              },
              "modified" : 1338494969,
              "changeMessage" : "...change message here...",
              "creator" : {
                "resource" : "http://identifier/for/creator"
              },
              "created" : 1338394969
        }"#;

        let attribution: Attribution = serde_json::from_str(json).unwrap();
        assert_eq!(
            attribution,
            Attribution {
                contributor: Some(ResourceReference::from("http://identifier/for/contributor")),
                modified: Some(
                    chrono::DateTime::from_utc(
                        chrono::NaiveDateTime::from_timestamp(1338494, 969000000),
                        chrono::Utc
                    )
                    .into()
                ),
                change_message: Some(String::from("...change message here...")),
                creator: Some(ResourceReference::from("http://identifier/for/creator")),
                created: Some(
                    chrono::DateTime::from_utc(
                        chrono::NaiveDateTime::from_timestamp(1338394, 969000000),
                        chrono::Utc
                    )
                    .into()
                ),
            }
        )
    }

    #[test]
    fn json_deserialize_optional_fields() {
        let json = r#"{}"#;

        let attribution: Attribution = serde_json::from_str(json).unwrap();
        assert_eq!(attribution, Attribution::default())
    }

    #[test]
    fn json_serialize() {
        let attribution = Attribution {
            contributor: Some(ResourceReference::from("http://identifier/for/contributor")),
            modified: Some(
                chrono::DateTime::from_utc(
                    chrono::NaiveDateTime::from_timestamp(1338494, 969000000),
                    chrono::Utc,
                )
                .into(),
            ),
            change_message: Some(String::from("...change message here...")),
            creator: Some(ResourceReference::from("http://identifier/for/creator")),
            created: Some(
                chrono::DateTime::from_utc(
                    chrono::NaiveDateTime::from_timestamp(1338394, 969000000),
                    chrono::Utc,
                )
                .into(),
            ),
        };

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

        assert_eq!(
            json,
            r#"{"contributor":{"resource":"http://identifier/for/contributor"},"modified":1338494969,"changeMessage":"...change message here...","creator":{"resource":"http://identifier/for/creator"},"created":1338394969}"#
        );
    }

    #[test]
    fn json_serialize_optional_fields() {
        let attribution = Attribution::default();

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

        assert_eq!(json, r#"{}"#);
    }

    #[test]
    fn xml_deserialize() {
        let xml = r#"
        <attribution>
            <contributor resource="http://identifier/for/contributor"/>
            <modified>2012-06-29T00:00:00</modified>
            <changeMessage>...change message here...</changeMessage>
            <creator resource="http://identifier/for/creator"/>
            <created>2012-05-29T00:00:00</created>
          </attribution>"#;

        let attribution: Attribution = yaserde::de::from_str(xml).unwrap();

        let expected_attribution = Attribution {
            contributor: Some("http://identifier/for/contributor".into()),
            modified: Some("2012-06-29T00:00:00".parse().unwrap()),
            change_message: Some("...change message here...".to_string()),
            creator: Some("http://identifier/for/creator".into()),
            created: Some("2012-05-29T00:00:00".parse().unwrap()),
        };

        assert_eq!(attribution, expected_attribution)
    }

    #[test]
    fn xml_deserialize_optional_fields() {
        let xml = r#"
        <attribution>
        </attribution>"#;

        let attribution: Attribution = yaserde::de::from_str(xml).unwrap();

        let expected_attribution = Attribution::default();
        assert_eq!(attribution, expected_attribution)
    }

    #[test]
    fn xml_serialize() {
        let attribution = Attribution {
            contributor: Some("http://identifier/for/contributor".into()),
            modified: Some("2012-06-29T00:00:00".parse().unwrap()),
            change_message: Some("...change message here...".to_string()),
            creator: Some("http://identifier/for/creator".into()),
            created: Some("2012-05-29T00:00:00".parse().unwrap()),
        };

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

        let expected_xml = r#"<attribution xmlns="http://gedcomx.org/v1/"><contributor resource="http://identifier/for/contributor" /><modified>2012-06-29T00:00:00</modified><changeMessage>...change message here...</changeMessage><creator resource="http://identifier/for/creator" /><created>2012-05-29T00:00:00</created></attribution>"#;

        assert_eq!(xml, expected_xml)
    }

    #[test]
    fn xml_serialize_optional_fields() {
        let attribution = Attribution::default();

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

        let expected_xml = r#"<attribution xmlns="http://gedcomx.org/v1/" />"#;

        assert_eq!(xml, expected_xml)
    }
}