1use crate::response::{FacetMap, QueryResponse};
4use chrono::{Datelike, NaiveDate};
5use serde::de::Deserializer;
6use serde::{Deserialize, Serialize};
7
8pub type Relations = std::collections::HashMap<String, RelatedItems>;
14
15#[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#[derive(Debug, Clone, Deserialize, Serialize)]
70#[serde(rename_all = "kebab-case")]
71pub struct WorkList {
72 #[serde(default)]
74 pub facets: FacetMap,
75 pub total_results: usize,
77 pub items_per_page: Option<usize>,
79 pub query: Option<QueryResponse>,
81 pub items: Vec<Work>,
83 pub next_cursor: Option<String>,
85}
86
87#[derive(Debug, Clone, Deserialize, Serialize)]
92#[serde(rename_all = "kebab-case")]
93pub struct Work {
94 pub publisher: Option<String>,
99 #[serde(default)]
105 pub title: Vec<String>,
106 pub original_title: Option<Vec<String>>,
108 pub language: Option<String>,
110 pub short_title: Option<Vec<String>>,
112 #[serde(rename = "abstract")]
114 pub abstract_: Option<String>,
115 pub references_count: Option<i32>,
117 pub is_referenced_by_count: Option<i32>,
119 pub source: Option<String>,
121 pub journal_issue: Option<Issue>,
123 pub prefix: Option<String>,
125 #[serde(rename = "DOI")]
127 pub doi: String,
128 #[serde(rename = "URL")]
130 pub url: Option<String>,
131 pub member: Option<String>,
135 #[serde(rename = "type")]
142 pub type_: Option<String>,
143 pub created: Option<Date>,
148 pub date: Option<Date>,
150 pub deposited: Option<Date>,
152 pub score: Option<f32>,
155 pub indexed: Option<Date>,
161 pub issued: Option<PartialDate>,
163 pub posted: Option<PartialDate>,
165 pub accepted: Option<PartialDate>,
167 pub subtitle: Option<Vec<String>>,
169 pub container_title: Option<Vec<String>>,
171 pub short_container_title: Option<Vec<String>>,
173 pub group_title: Option<String>,
175 pub issue: Option<String>,
177 pub volume: Option<String>,
179 pub page: Option<String>,
181 pub article_number: Option<String>,
183 pub published_print: Option<PartialDate>,
185 pub published_online: Option<PartialDate>,
187 pub subject: Option<Vec<String>>,
190 #[serde(rename = "ISSN")]
192 pub issn: Option<Vec<String>>,
193 pub issn_type: Option<Vec<ISSN>>,
195 #[serde(rename = "ISBN")]
197 pub isbn: Option<Vec<String>>,
198 pub archive: Option<Vec<String>>,
200 pub license: Option<Vec<License>>,
202 pub funder: Option<Vec<FundingBody>>,
204 pub assertion: Option<Vec<Assertion>>,
206 pub author: Option<Vec<Contributor>>,
208 pub editor: Option<Vec<Contributor>>,
210 pub chair: Option<Vec<Contributor>>,
212 pub translator: Option<Vec<Contributor>>,
214 pub update_to: Option<Vec<Update>>,
216 pub update_policy: Option<String>,
218 pub link: Option<Vec<ResourceLink>>,
220 pub clinical_trial_number: Option<Vec<ClinicalTrialNumber>>,
222 pub alternative_id: Option<Vec<String>>,
224 pub reference: Option<Vec<Reference>>,
226 pub content_domain: Option<ContentDomain>,
228 pub relation: Option<Relations>,
230 pub review: Option<Review>,
232}
233
234impl Work {
235 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
261pub struct DateParts(pub Vec<Vec<Option<u32>>>);
262
263impl DateParts {
264 pub fn as_date(&self) -> Option<DateField> {
268 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
305pub struct FundingBody {
306 pub name: Option<String>,
310 #[serde(rename = "DOI")]
312 pub doi: Option<String>,
313 pub award: Option<Vec<String>>,
315 #[serde(rename = "doi-asserted-by")]
317 pub doi_asserted_by: Option<String>,
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
322pub struct ClinicalTrialNumber {
323 #[serde(rename = "clinical-trial-number")]
325 pub clinical_trial_number: String,
326 pub registry: String,
328 #[serde(rename = "type")]
330 pub type_: Option<String>,
331}
332
333#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
338pub struct Contributor {
339 pub prefix: Option<String>,
341 pub suffix: Option<String>,
343 pub family: Option<String>,
345 pub given: Option<String>,
347 pub name: Option<String>,
349 #[serde(rename = "ORCID")]
351 pub orcid: Option<String>,
352 #[serde(rename = "authenticated-orcid")]
354 pub authenticated_orcid: Option<bool>,
355 pub affiliation: Vec<Affiliation>,
357 pub sequence: String,
359}
360
361#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
363pub struct Affiliation {
364 pub name: Option<String>,
368 #[serde(default)]
373 pub id: Vec<InstitutionId>,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
378#[serde(rename_all = "kebab-case")]
379pub struct InstitutionId {
380 pub id: String,
382 pub id_type: Option<String>,
384 pub asserted_by: Option<String>,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
390#[serde(rename_all = "kebab-case")]
391pub struct Date {
392 pub date_parts: DateParts,
396 pub timestamp: usize,
398 pub date_time: String,
400}
401
402impl Date {
403 pub fn as_date_field(&self) -> Option<DateField> {
405 self.date_parts.as_date()
406 }
407}
408
409impl std::fmt::Display for Date {
410 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
433pub struct PartialDate {
434 #[serde(rename = "date-parts")]
438 pub date_parts: DateParts,
439}
440
441impl PartialDate {
442 pub fn as_date_field(&self) -> Option<DateField> {
444 self.date_parts.as_date()
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
450pub enum DateField {
451 Single(NaiveDate),
453 Range {
455 from: NaiveDate,
457 to: NaiveDate,
459 },
460 Multi(Vec<NaiveDate>),
462}
463
464impl DateField {
465 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
478pub struct Update {
479 pub updated: PartialDate,
481 #[serde(rename = "DOI")]
483 pub doi: String,
484 #[serde(rename = "type")]
486 pub type_: String,
487 pub label: Option<String>,
489}
490
491#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
494pub struct Assertion {
495 pub name: String,
497 pub value: Option<String>,
499 #[serde(rename = "URL")]
501 pub url: Option<String>,
502 pub explanation: Option<Explanation>,
504 pub label: Option<String>,
506 pub order: Option<i32>,
508 pub group: Option<AssertionGroup>,
510}
511
512#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
519pub struct Explanation {
520 #[serde(rename = "URL")]
522 pub url: String,
523}
524
525#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
527#[serde(rename_all = "kebab-case")]
528pub struct Issue {
529 pub published_print: Option<PartialDate>,
531 pub published_online: Option<PartialDate>,
533 pub issue: Option<String>,
535}
536
537#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
539pub struct AssertionGroup {
540 pub name: String,
542 pub label: Option<String>,
544}
545
546#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
548pub struct Agency {
549 pub id: String,
551 pub label: Option<String>,
553}
554
555#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
557#[serde(rename_all = "kebab-case")]
558pub struct License {
559 pub content_version: String,
561 pub delay_in_days: i32,
563 pub start: Option<PartialDate>,
567 #[serde(rename = "URL")]
569 pub url: String,
570}
571
572#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
574#[serde(rename_all = "kebab-case")]
575pub struct ResourceLink {
576 pub intended_application: String,
578 pub content_version: String,
580 #[serde(rename = "URL")]
582 pub url: String,
583 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 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 pub issn_type: Option<String>,
614 #[serde(rename = "ISBN")]
615 pub isbn: Option<String>,
616 pub isbn_type: Option<String>,
617}
618
619#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
621#[serde(rename_all = "kebab-case")]
622pub struct ISSN {
623 pub value: String,
625 #[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 #[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 pub stage: Option<String>,
660 pub recommendation: Option<String>,
662 #[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 #[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 assert_eq!(
715 None,
716 DateParts(vec![vec![Some(2022), Some(5), Some(19), Some(12)]]).as_date()
717 );
718 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}