Skip to main content

crossref_client/response/
work.rs

1// see https://github.com/Crossref/rest-api-doc/blob/master/api_format.md
2
3use crate::response::{FacetMap, QueryResponse};
4use chrono::{Datelike, NaiveDate};
5use serde::de::Deserializer;
6use serde::{Deserialize, Serialize};
7
8/// The relations a work asserts or is the object of, keyed by relation name.
9///
10/// The names come from the
11/// [crossref relations schema](https://github.com/CrossRef/rest-api-doc/blob/master/api_format.md#relations)
12/// -- `is-review-of`, `is-preprint-of`, `is-identical-to` and so on.
13pub type Relations = std::collections::HashMap<String, RelatedItems>;
14
15/// The related items of one relation kind.
16///
17/// Crossref deposits these as an array, which is why the field used to be typed
18/// as a bare `serde_json::Value`: it had been modelled as a single [`Relation`]
19/// and an array is what actually arrives. A lone object is still accepted and
20/// read as a list of one, so neither shape can cost a page of a crawl.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22#[serde(transparent)]
23pub struct RelatedItems(pub Vec<Relation>);
24
25impl<'de> Deserialize<'de> for RelatedItems {
26    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
27        #[derive(Deserialize)]
28        #[serde(untagged)]
29        enum OneOrMany {
30            Many(Vec<Relation>),
31            One(Relation),
32        }
33
34        Ok(match OneOrMany::deserialize(deserializer)? {
35            OneOrMany::Many(items) => RelatedItems(items),
36            OneOrMany::One(item) => RelatedItems(vec![item]),
37        })
38    }
39}
40
41impl std::ops::Deref for RelatedItems {
42    type Target = [Relation];
43
44    fn deref(&self) -> &Self::Target {
45        &self.0
46    }
47}
48
49impl IntoIterator for RelatedItems {
50    type Item = Relation;
51    type IntoIter = std::vec::IntoIter<Relation>;
52
53    fn into_iter(self) -> Self::IntoIter {
54        self.0.into_iter()
55    }
56}
57
58impl<'a> IntoIterator for &'a RelatedItems {
59    type Item = &'a Relation;
60    type IntoIter = std::slice::Iter<'a, Relation>;
61
62    fn into_iter(self) -> Self::IntoIter {
63        self.0.iter()
64    }
65}
66
67/// the payload of a `/works` response, and of the `works` route of any other
68/// component
69#[derive(Debug, Clone, Deserialize, Serialize)]
70#[serde(rename_all = "kebab-case")]
71pub struct WorkList {
72    /// if facets were part of the request they are also included in the response
73    #[serde(default)]
74    pub facets: FacetMap,
75    /// the number of items that match the response
76    pub total_results: usize,
77    /// crossref responses for large number of items are divided in pages, number of elements to expect in `items`
78    pub items_per_page: Option<usize>,
79    /// if a query was set in the request, this will also be part in the response
80    pub query: Option<QueryResponse>,
81    /// all work items that are returned
82    pub items: Vec<Work>,
83    /// deep page through `/works` result sets
84    pub next_cursor: Option<String>,
85}
86
87/// the main return type of the crossref api
88/// represents a publication
89/// based on the [crossref rest-api-doc](https://github.com/CrossRef/rest-api-doc/blob/master/api_format.md#work)
90/// with minor adjustments
91#[derive(Debug, Clone, Deserialize, Serialize)]
92#[serde(rename_all = "kebab-case")]
93pub struct Work {
94    /// Name of work's publisher
95    ///
96    /// Optional for the same reason as [`Work::type_`]: it is deposited by the
97    /// member, not assigned by crossref.
98    pub publisher: Option<String>,
99    /// Work titles, including translated titles
100    ///
101    /// Absent for roughly 5% of works -- most `component` records and a
102    /// scattering of datasets carry no title at all -- so an untitled work
103    /// deserializes to an empty list rather than failing the whole page.
104    #[serde(default)]
105    pub title: Vec<String>,
106    /// Work titles in the work's original publication language
107    pub original_title: Option<Vec<String>>,
108    /// the language of this work
109    pub language: Option<String>,
110    /// Abstract as a JSON string or a JATS XML snippet encoded into a JSON string
111    pub short_title: Option<Vec<String>>,
112    /// Abstract as a JSON string or a JATS XML snippet encoded into a JSON string
113    #[serde(rename = "abstract")]
114    pub abstract_: Option<String>,
115    /// Count of outbound references deposited with Crossref
116    pub references_count: Option<i32>,
117    /// Count of inbound references deposited with Crossref
118    pub is_referenced_by_count: Option<i32>,
119    /// Currently always `Crossref`
120    pub source: Option<String>,
121    /// which issue of the containing journal this work appeared in
122    pub journal_issue: Option<Issue>,
123    /// DOI prefix identifier of the form `http://id.crossref.org/prefix/DOI_PREFIX`
124    pub prefix: Option<String>,
125    /// DOI of the work
126    #[serde(rename = "DOI")]
127    pub doi: String,
128    /// URL form of the work's DOI
129    #[serde(rename = "URL")]
130    pub url: Option<String>,
131    /// Member identifier of the form `http://id.crossref.org/member/MEMBER_ID`
132    ///
133    /// Absent from a handful of records whose depositing member no longer exists.
134    pub member: Option<String>,
135    /// Enumeration, one of the type ids from `https://api.crossref.org/v1/types`
136    ///
137    /// Crossref validates member deposits loosely, so nearly every field can be
138    /// absent from a record -- roughly one work in 20 000 has no type. Only
139    /// [`Work::doi`] is required, and even that assumes the query did not drop
140    /// it with [`WorksQuery::elements`](crate::WorksQuery::elements).
141    #[serde(rename = "type")]
142    pub type_: Option<String>,
143    /// the day this work entry was created
144    ///
145    /// Absent when the query narrowed the response with
146    /// [`WorksQuery::elements`](crate::WorksQuery::elements).
147    pub created: Option<Date>,
148    /// Date on which the DOI was first registered
149    pub date: Option<Date>,
150    /// Date on which the work metadata was most recently updated
151    pub deposited: Option<Date>,
152    /// the score of the publication if any
153    /// not included in the crossrif api spec
154    pub score: Option<f32>,
155    /// Date on which the work metadata was most recently indexed.
156    /// Re-indexing does not imply a metadata change, see `deposited` for the most recent metadata change date
157    ///
158    /// Absent when the query narrowed the response with
159    /// [`WorksQuery::elements`](crate::WorksQuery::elements).
160    pub indexed: Option<Date>,
161    /// Earliest of `published-print` and `published-online`
162    pub issued: Option<PartialDate>,
163    /// ate on which posted content was made available online
164    pub posted: Option<PartialDate>,
165    /// Date on which a work was accepted, after being submitted, during a submission process
166    pub accepted: Option<PartialDate>,
167    /// Work subtitles, including original language and translated
168    pub subtitle: Option<Vec<String>>,
169    /// Full titles of the containing work (usually a book or journal)
170    pub container_title: Option<Vec<String>>,
171    /// Abbreviated titles of the containing work
172    pub short_container_title: Option<Vec<String>>,
173    /// Group title for posted content
174    pub group_title: Option<String>,
175    /// Issue number of an article's journal
176    pub issue: Option<String>,
177    /// Volume number of an article's journal
178    pub volume: Option<String>,
179    /// Pages numbers of an article within its journal
180    pub page: Option<String>,
181    /// the number of the corresponding article
182    pub article_number: Option<String>,
183    /// Date on which the work was published in print
184    pub published_print: Option<PartialDate>,
185    /// Date on which the work was published online
186    pub published_online: Option<PartialDate>,
187    /// Subject category names, a controlled vocabulary from Sci-Val.
188    /// Available for most journal articles
189    pub subject: Option<Vec<String>>,
190    /// ISSNs of the containing journal, print and electronic
191    #[serde(rename = "ISSN")]
192    pub issn: Option<Vec<String>>,
193    /// List of ISSNs with ISSN type information
194    pub issn_type: Option<Vec<ISSN>>,
195    /// ISBNs of the containing book
196    #[serde(rename = "ISBN")]
197    pub isbn: Option<Vec<String>>,
198    /// names of the archives that preserve this work
199    pub archive: Option<Vec<String>>,
200    /// the licenses this work is published under
201    pub license: Option<Vec<License>>,
202    /// the bodies that funded the work, and the awards they made
203    pub funder: Option<Vec<FundingBody>>,
204    /// Crossmark assertions the publisher made about the work
205    pub assertion: Option<Vec<Assertion>>,
206    /// the work's authors, in the order they were deposited
207    pub author: Option<Vec<Contributor>>,
208    /// the editors of the containing work
209    pub editor: Option<Vec<Contributor>>,
210    /// the chairs of the containing proceedings
211    pub chair: Option<Vec<Contributor>>,
212    /// the work's translators
213    pub translator: Option<Vec<Contributor>>,
214    /// works this one is an editorial update to, e.g. a retraction or correction
215    pub update_to: Option<Vec<Update>>,
216    /// Link to an update policy covering Crossmark updates for this work
217    pub update_policy: Option<String>,
218    /// URLs to full-text locations
219    pub link: Option<Vec<ResourceLink>>,
220    /// the clinical trials the work reports on
221    pub clinical_trial_number: Option<Vec<ClinicalTrialNumber>>,
222    /// Other identifiers for the work provided by the depositing member
223    pub alternative_id: Option<Vec<String>>,
224    /// List of references made by the work
225    pub reference: Option<Vec<Reference>>,
226    /// Information on domains that support Crossmark for this work
227    pub content_domain: Option<ContentDomain>,
228    /// Relations to other works
229    pub relation: Option<Relations>,
230    /// Peer review metadata, on works of type `peer-review`
231    pub review: Option<Review>,
232}
233
234impl Work {
235    /// A short citation key for this work, in the common `AuthorYear` style.
236    ///
237    /// Built from the family names of the authors and the issued year:
238    /// `Smith2019` for a single author, `Smith&Jones2019` for two, and
239    /// `SmithEtAl2019` for three or more.
240    ///
241    /// Returns [`None`] if the work carries no author with a family name, or
242    /// no issued date to take a year from.
243    pub fn citekey(&self) -> Option<String> {
244        let authors = self.author.as_deref()?;
245        let family = |c: &Contributor| c.family.clone().unwrap_or_default();
246
247        let names = match authors {
248            [] => return None,
249            [single] => single.family.clone()?,
250            [first, second] => format!("{}&{}", family(first), family(second)),
251            [first, ..] => format!("{}EtAl", family(first)),
252        };
253
254        let year = self.issued.as_ref()?.as_date_field()?.year();
255        Some(format!("{}{}", names, year))
256    }
257}
258
259/// Helper struct to represent dates in the cross ref api as nested arrays of numbers
260#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
261pub struct DateParts(pub Vec<Vec<Option<u32>>>);
262
263impl DateParts {
264    /// converts the nested array of numbers into the corresponding [DateField]
265    /// standalone years are allowed.
266    /// if an array is empty, [None] will be returned
267    pub fn as_date(&self) -> Option<DateField> {
268        /// Converts one array of numbers into a chrono [`NaiveDate`].
269        ///
270        /// Crossref deposits a date to whatever precision the member gave it,
271        /// so `[2022]` is a whole year and `[2022, 5]` a whole month. A
272        /// [`NaiveDate`] cannot be partial, so what is missing reads as the
273        /// first of what contains it -- the day a work published "in 2022" is
274        /// sorted and cited by. Asking chrono for a zeroth month instead, as
275        /// this once did, is not a date at all: it answered [`None`] for every
276        /// year-only date crossref sent, which is most of them.
277        fn naive(parts: &[Option<u32>]) -> Option<NaiveDate> {
278            match parts {
279                [year] => NaiveDate::from_ymd_opt((*year)? as i32, 1, 1),
280                [year, month] => NaiveDate::from_ymd_opt((*year)? as i32, (*month)?, 1),
281                [year, month, day] => NaiveDate::from_ymd_opt((*year)? as i32, (*month)?, (*day)?),
282                _ => None,
283            }
284        }
285
286        match self.0.len() {
287            0 => None,
288            1 => Some(DateField::Single(naive(&self.0[0])?)),
289            2 => Some(DateField::Range {
290                from: naive(&self.0[0])?,
291                to: naive(&self.0[1])?,
292            }),
293            _ => Some(DateField::Multi(
294                self.0
295                    .iter()
296                    .map(|x| naive(x))
297                    .collect::<Option<Vec<_>>>()?,
298            )),
299        }
300    }
301}
302
303/// a body that funded the work, and the awards it made
304#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
305pub struct FundingBody {
306    /// Funding body primary name
307    ///
308    /// Members occasionally deposit a funder entry carrying only an award list.
309    pub name: Option<String>,
310    /// Optional [Open Funder Registry](http://www.crossref.org/fundingdata/registry.html) DOI uniquely identifing the funding body
311    #[serde(rename = "DOI")]
312    pub doi: Option<String>,
313    /// Award number(s) for awards given by the funding body
314    pub award: Option<Vec<String>>,
315    /// Either `crossref` or `publisher`
316    #[serde(rename = "doi-asserted-by")]
317    pub doi_asserted_by: Option<String>,
318}
319
320/// a clinical trial the work reports on
321#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
322pub struct ClinicalTrialNumber {
323    /// Identifier of the clinical trial
324    #[serde(rename = "clinical-trial-number")]
325    pub clinical_trial_number: String,
326    /// DOI of the clinical trial regsitry that assigned the trial number
327    pub registry: String,
328    /// One of `preResults`, `results` or `postResults`
329    #[serde(rename = "type")]
330    pub type_: Option<String>,
331}
332
333/// someone credited on the work: an author, editor, chair or translator
334///
335/// A contributor is either a person, with `family` and usually `given`, or an
336/// organisation, with `name`. Members deposit both, so neither is guaranteed.
337#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
338pub struct Contributor {
339    /// an honorific before the name, e.g. `Prof.`
340    pub prefix: Option<String>,
341    /// a suffix after the name, e.g. `Jr.`
342    pub suffix: Option<String>,
343    /// the family name, for a person
344    pub family: Option<String>,
345    /// the given names, for a person
346    pub given: Option<String>,
347    /// the full name, for an organisation
348    pub name: Option<String>,
349    /// URL-form of an [ORCID](http://orcid.org) identifier
350    #[serde(rename = "ORCID")]
351    pub orcid: Option<String>,
352    /// If true, record owner asserts that the ORCID user completed ORCID OAuth authentication
353    #[serde(rename = "authenticated-orcid")]
354    pub authenticated_orcid: Option<bool>,
355    /// the institutions this contributor is affiliated with
356    pub affiliation: Vec<Affiliation>,
357    /// `first` for the first contributor listed, `additional` for the rest
358    pub sequence: String,
359}
360
361/// an institution a contributor is affiliated with
362#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
363pub struct Affiliation {
364    /// the affiliation's name
365    ///
366    /// Members occasionally deposit a bare `{}` affiliation.
367    pub name: Option<String>,
368    /// identifiers for the institution, in practice [ROR](https://ror.org) ids
369    ///
370    /// How crossref now models affiliations; select works that carry one with
371    /// [`WorksFilter::HasAffiliationRorId`](crate::WorksFilter::HasAffiliationRorId).
372    #[serde(default)]
373    pub id: Vec<InstitutionId>,
374}
375
376/// an identifier for an institution, as deposited on an [`Affiliation`]
377#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
378#[serde(rename_all = "kebab-case")]
379pub struct InstitutionId {
380    /// the identifier itself, e.g. `https://ror.org/00hx57361`
381    pub id: String,
382    /// what kind of identifier it is, in practice always `ROR`
383    pub id_type: Option<String>,
384    /// either `crossref` or `publisher`
385    pub asserted_by: Option<String>,
386}
387
388/// represents full date information for an item
389#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
390#[serde(rename_all = "kebab-case")]
391pub struct Date {
392    /// Contains an ordered array of year, month, day of month.
393    /// Only year is required. Note that the field contains a nested array,
394    /// e.g. [ [ 2006, 5, 19 ] ] to conform to citeproc JSON dates
395    pub date_parts: DateParts,
396    /// Seconds since UNIX epoch
397    pub timestamp: usize,
398    /// ISO 8601 date time
399    pub date_time: String,
400}
401
402impl Date {
403    /// converts the nested array of numbers into the correct representation of chrono [NaiveDate]
404    pub fn as_date_field(&self) -> Option<DateField> {
405        self.date_parts.as_date()
406    }
407}
408
409impl std::fmt::Display for Date {
410    /// Renders the date as `%Y-%m-%d`; ranges as `from-to` and multi dates as a
411    /// comma separated list. An unparsable date renders as the empty string.
412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413        match self.as_date_field() {
414            Some(DateField::Single(date)) => write!(f, "{}", date.format("%Y-%m-%d")),
415            Some(DateField::Range { from, to }) => {
416                write!(f, "{}-{}", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
417            }
418            Some(DateField::Multi(dates)) => {
419                let joined = dates
420                    .iter()
421                    .map(|date| date.format("%Y-%m-%d").to_string())
422                    .collect::<Vec<_>>()
423                    .join(",");
424                f.write_str(&joined)
425            }
426            None => Ok(()),
427        }
428    }
429}
430
431/// represents an incomplete date only consisting of year or year and month
432#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
433pub struct PartialDate {
434    /// Contains an ordered array of year, month, day of month.
435    /// Only year is required
436    /// e.g. `[ [`2006`] ]` to conform to citeproc JSON dates
437    #[serde(rename = "date-parts")]
438    pub date_parts: DateParts,
439}
440
441impl PartialDate {
442    /// converts the nested array of numbers into the correct representation of chrono [NaiveDate]
443    pub fn as_date_field(&self) -> Option<DateField> {
444        self.date_parts.as_date()
445    }
446}
447
448/// Helper struct to capture all possible occurrences of dates in the crossref api, a nested Vec of numbers
449#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
450pub enum DateField {
451    /// only a single date vector
452    Single(NaiveDate),
453    /// two date vectors represent a range
454    Range {
455        /// start date of the range
456        from: NaiveDate,
457        /// end date of the range
458        to: NaiveDate,
459    },
460    /// more than two date vectors are present
461    Multi(Vec<NaiveDate>),
462}
463
464impl DateField {
465    /// The year to cite the work by: the only year for a single date, and the
466    /// first for a range or a list.
467    pub fn year(&self) -> i32 {
468        match self {
469            DateField::Single(date) => date.year(),
470            DateField::Range { from, to: _ } => from.year(),
471            DateField::Multi(dates) => dates[0].year(),
472        }
473    }
474}
475
476/// metadata about when the `Work` entry was updated
477#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
478pub struct Update {
479    /// Date on which the update was published
480    pub updated: PartialDate,
481    /// DOI of the updated work
482    #[serde(rename = "DOI")]
483    pub doi: String,
484    /// The type of update, for example retraction or correction
485    #[serde(rename = "type")]
486    pub type_: String,
487    /// A display-friendly label for the update type
488    pub label: Option<String>,
489}
490
491/// a [Crossmark](https://www.crossref.org/services/crossmark/) claim the
492/// publisher made about the work, e.g. its peer review status or funding
493#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
494pub struct Assertion {
495    /// what is being asserted, as a machine-readable name
496    pub name: String,
497    /// the asserted value
498    pub value: Option<String>,
499    /// a link backing the assertion up
500    #[serde(rename = "URL")]
501    pub url: Option<String>,
502    /// where the assertion is explained
503    pub explanation: Option<Explanation>,
504    /// a display-friendly form of `name`
505    pub label: Option<String>,
506    /// where to place this assertion when displaying the group
507    pub order: Option<i32>,
508    /// the group of assertions this one is displayed under
509    pub group: Option<AssertionGroup>,
510}
511
512/// where a Crossmark assertion is explained
513///
514/// Always a link. The free-text variant this used to carry alongside it was
515/// inferred from the field's original `Option<String>` type rather than
516/// observed, and no free-text explanation turned up in the 38 800 works sampled
517/// from the live api since.
518#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
519pub struct Explanation {
520    /// link to a page describing the assertion
521    #[serde(rename = "URL")]
522    pub url: String,
523}
524
525/// the issue of a journal a work appeared in
526#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
527#[serde(rename_all = "kebab-case")]
528pub struct Issue {
529    /// Date on which the work was published in print
530    pub published_print: Option<PartialDate>,
531    /// Date on which the work was published online
532    pub published_online: Option<PartialDate>,
533    /// Issue number of an article's journal
534    pub issue: Option<String>,
535}
536
537/// the heading a set of [`Assertion`]s is displayed under
538#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
539pub struct AssertionGroup {
540    /// the group's machine-readable name
541    pub name: String,
542    /// a display-friendly form of `name`
543    pub label: Option<String>,
544}
545
546/// the registration agency that minted a DOI, e.g. `crossref` or `datacite`
547#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
548pub struct Agency {
549    /// the agency's identifier
550    pub id: String,
551    /// a display-friendly form of `id`
552    pub label: Option<String>,
553}
554
555/// how the `Work` is licensed
556#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
557#[serde(rename_all = "kebab-case")]
558pub struct License {
559    /// Either `vor` (version of record,) `am` (accepted manuscript) or `unspecified`
560    pub content_version: String,
561    /// Number of days between the publication date of the work and the start date of this license
562    pub delay_in_days: i32,
563    /// Date on which this license begins to take effect
564    ///
565    /// A few members deposit a license with a url and delay but no start date.
566    pub start: Option<PartialDate>,
567    /// Link to a web page describing this license
568    #[serde(rename = "URL")]
569    pub url: String,
570}
571
572/// metadata about a related resource
573#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
574#[serde(rename_all = "kebab-case")]
575pub struct ResourceLink {
576    /// Either `text-mining`, `similarity-checking` or `unspecified`
577    pub intended_application: String,
578    /// Either `vor` (version of record,) `am` (accepted manuscript) or `unspecified`
579    pub content_version: String,
580    /// Direct link to a full-text download location
581    #[serde(rename = "URL")]
582    pub url: String,
583    /// Content type (or MIME type) of the full-text object
584    pub content_type: Option<String>,
585}
586
587#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
588#[serde(rename_all = "kebab-case")]
589#[allow(missing_docs)]
590pub struct Reference {
591    pub key: String,
592    #[serde(rename = "DOI")]
593    pub doi: Option<String>,
594    /// One of `crossref` or `publisher`
595    pub doi_asserted_by: Option<String>,
596    pub issue: Option<String>,
597    pub first_page: Option<String>,
598    pub volume: Option<String>,
599    pub edition: Option<String>,
600    pub component: Option<String>,
601    pub standard_designator: Option<String>,
602    pub standards_body: Option<String>,
603    pub author: Option<String>,
604    pub year: Option<String>,
605    pub unstructured: Option<String>,
606    pub journal_title: Option<String>,
607    pub article_title: Option<String>,
608    pub series_title: Option<String>,
609    pub volume_title: Option<String>,
610    #[serde(rename = "ISSN")]
611    pub issn: Option<String>,
612    /// One of `pissn` or `eissn`
613    pub issn_type: Option<String>,
614    #[serde(rename = "ISBN")]
615    pub isbn: Option<String>,
616    pub isbn_type: Option<String>,
617}
618
619/// ISSN info for the `Work`
620#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
621#[serde(rename_all = "kebab-case")]
622pub struct ISSN {
623    /// identifier
624    pub value: String,
625    /// One of `eissn`, `pissn` or `lissn`
626    #[serde(rename = "type")]
627    pub type_: String,
628}
629
630#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
631#[serde(rename_all = "kebab-case")]
632#[allow(missing_docs)]
633pub struct ContentDomain {
634    pub domain: Vec<String>,
635    /// whether the publisher restricts Crossmark usage to `domain`
636    ///
637    /// Omitted alongside an empty `domain` on a large share of works, where it
638    /// carries no meaning; treated as `false`.
639    #[serde(default)]
640    pub crossmark_restriction: bool,
641}
642
643#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
644#[serde(rename_all = "kebab-case")]
645#[allow(missing_docs)]
646pub struct Relation {
647    pub id_type: Option<String>,
648    pub id: Option<String>,
649    pub asserted_by: Option<String>,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
653#[serde(rename_all = "kebab-case")]
654#[allow(missing_docs)]
655pub struct Review {
656    pub running_number: Option<String>,
657    pub revision_round: Option<String>,
658    /// One of `pre-publication` or `post-publication`
659    pub stage: Option<String>,
660    /// One of `major-revision` or `minor-revision` or `reject` or `reject-with-resubmit` or `accept`
661    pub recommendation: Option<String>,
662    /// One of `referee-report` or `editor-report` or `author-comment` or `community-comment` or `aggregate`
663    #[serde(rename = "type")]
664    pub type_: String,
665    pub competing_interest_statement: Option<String>,
666    pub language: Option<String>,
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672    use serde_json::*;
673    #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
674    struct Demo {
675        pub date_parts: DateParts,
676    }
677    /// Crossref sends `issued` as a bare year far more often than as a full
678    /// date, so a partial date that reads as no date at all takes
679    /// [`Work::citekey`] and every year comparison down with it.
680    #[test]
681    fn a_date_deposited_to_the_year_or_the_month_is_still_a_date() {
682        let year = DateParts(vec![vec![Some(2022)]]);
683        assert_eq!(
684            Some(DateField::Single(
685                NaiveDate::from_ymd_opt(2022, 1, 1).unwrap()
686            )),
687            year.as_date()
688        );
689        assert_eq!(2022, year.as_date().unwrap().year());
690
691        let month = DateParts(vec![vec![Some(2022), Some(5)]]);
692        assert_eq!(
693            Some(DateField::Single(
694                NaiveDate::from_ymd_opt(2022, 5, 1).unwrap()
695            )),
696            month.as_date()
697        );
698
699        let day = DateParts(vec![vec![Some(2022), Some(5), Some(19)]]);
700        assert_eq!(
701            Some(DateField::Single(
702                NaiveDate::from_ymd_opt(2022, 5, 19).unwrap()
703            )),
704            day.as_date()
705        );
706    }
707
708    #[test]
709    fn a_date_that_is_no_date_reads_as_none() {
710        assert_eq!(None, DateParts(vec![]).as_date());
711        assert_eq!(None, DateParts(vec![vec![]]).as_date());
712        assert_eq!(None, DateParts(vec![vec![None]]).as_date());
713        // a fifth number is not a date crossref has any way of meaning
714        assert_eq!(
715            None,
716            DateParts(vec![vec![Some(2022), Some(5), Some(19), Some(12)]]).as_date()
717        );
718        // and an impossible one stays impossible
719        assert_eq!(None, DateParts(vec![vec![Some(2022), Some(13)]]).as_date());
720    }
721
722    #[test]
723    fn a_range_and_a_list_of_dates_keep_the_year_they_start_at() {
724        let range = DateParts(vec![vec![Some(2021), Some(5)], vec![Some(2022), Some(6)]]);
725        assert_eq!(2021, range.as_date().unwrap().year());
726
727        let multi = DateParts(vec![
728            vec![Some(2021)],
729            vec![Some(2022)],
730            vec![Some(2023), Some(1), Some(9)],
731        ]);
732        assert_eq!(2021, multi.as_date().unwrap().year());
733    }
734
735    #[test]
736    fn date_parts_serde() {
737        let demo = Demo {
738            date_parts: DateParts(vec![vec![Some(2017), Some(10), Some(11)]]),
739        };
740        let expected = r##"{"date_parts":[[2017,10,11]]}"##;
741        assert_eq!(expected, &to_string(&demo).unwrap());
742        assert_eq!(demo, from_str::<Demo>(expected).unwrap());
743    }
744
745    #[test]
746    fn serialize_work() {
747        let work_str = r##"{
748    "indexed": {
749      "date-parts": [
750        [
751          2019,
752          2,
753          26
754        ]
755      ],
756      "date-time": "2019-02-26T10:43:14Z",
757      "timestamp": 1551177794515
758    },
759    "reference-count": 105,
760    "publisher": "American Psychological Association (APA)",
761    "issue": "1",
762    "content-domain": {
763      "domain": [],
764      "crossmark-restriction": false
765    },
766    "short-container-title": [
767      "American Psychologist"
768    ],
769    "DOI": "10.1037/0003-066x.59.1.29",
770    "type": "journal-article",
771    "created": {
772      "date-parts": [
773        [
774          2004,
775          1,
776          21
777        ]
778      ],
779      "date-time": "2004-01-21T14:31:19Z",
780      "timestamp": 1074695479000
781    },
782    "page": "29-40",
783    "source": "Crossref",
784    "is-referenced-by-count": 84,
785    "title": [
786      "How the Mind Hurts and Heals the Body."
787    ],
788    "prefix": "10.1037",
789    "volume": "59",
790    "author": [
791      {
792        "given": "Oakley",
793        "family": "Ray",
794        "sequence": "first",
795        "affiliation": []
796      }
797    ],
798    "member": "15",
799    "published-online": {
800      "date-parts": [
801        [
802          2004
803        ]
804      ]
805    },
806    "container-title": [
807      "American Psychologist"
808    ],
809    "original-title": [],
810    "language": "en",
811    "link": [
812      {
813        "URL": "http://psycnet.apa.org/journals/amp/59/1/29.pdf",
814        "content-type": "unspecified",
815        "content-version": "vor",
816        "intended-application": "similarity-checking"
817      }
818    ],
819    "deposited": {
820      "date-parts": [
821        [
822          2018,
823          4,
824          8
825        ]
826      ],
827      "date-time": "2018-04-08T18:56:17Z",
828      "timestamp": 1523213777000
829    },
830    "score": 1,
831    "subtitle": [],
832    "short-title": [],
833    "issued": {
834      "date-parts": [
835        [
836          null
837        ]
838      ]
839    },
840    "references-count": 105,
841    "journal-issue": {
842      "published-online": {
843        "date-parts": [
844          [
845            2004
846          ]
847        ]
848      },
849      "issue": "1"
850    },
851    "alternative-id": [
852      "2004-10043-004",
853      "14736318"
854    ],
855    "URL": "http://dx.doi.org/10.1037/0003-066x.59.1.29",
856    "relation": {},
857    "ISSN": [
858      "1935-990X",
859      "0003-066X"
860    ],
861    "issn-type": [
862      {
863        "value": "0003-066X",
864        "type": "print"
865      },
866      {
867        "value": "1935-990X",
868        "type": "electronic"
869      }
870    ]
871  }
872"##;
873
874        let _work: Work = from_str(work_str).unwrap();
875    }
876}