1use crate::date::{PartialDate, Timespan};
8use crate::id::{Identifier, Oci};
9use serde::{Deserialize, Deserializer, Serialize};
10use std::fmt;
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Citation {
19 pub oci: Oci,
21 #[serde(deserialize_with = "bag")]
23 pub citing: Vec<Identifier>,
24 #[serde(deserialize_with = "bag")]
26 pub cited: Vec<Identifier>,
27 #[serde(default, deserialize_with = "blank_is_none")]
29 pub creation: Option<PartialDate>,
30 #[serde(default, deserialize_with = "blank_is_none")]
33 pub timespan: Option<Timespan>,
34 #[serde(rename = "journal_sc", deserialize_with = "yes_or_no")]
36 pub journal_self_citation: bool,
37 #[serde(rename = "author_sc", deserialize_with = "yes_or_no")]
39 pub author_self_citation: bool,
40}
41
42impl Citation {
43 pub fn citing_doi(&self) -> Option<&str> {
45 self.citing.iter().find_map(Identifier::as_doi)
46 }
47
48 pub fn cited_doi(&self) -> Option<&str> {
50 self.cited.iter().find_map(Identifier::as_doi)
51 }
52}
53
54fn bag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Identifier>, D::Error> {
56 let raw = String::deserialize(deserializer)?;
57 Identifier::parse_bag(&raw).map_err(serde::de::Error::custom)
58}
59
60fn blank_is_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
63where
64 D: Deserializer<'de>,
65 T: std::str::FromStr,
66 T::Err: fmt::Display,
67{
68 let raw = String::deserialize(deserializer)?;
69 if raw.trim().is_empty() {
70 return Ok(None);
71 }
72 raw.trim()
73 .parse()
74 .map(Some)
75 .map_err(serde::de::Error::custom)
76}
77
78fn yes_or_no<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
80 let raw = String::deserialize(deserializer)?;
81 match raw.trim().to_ascii_lowercase().as_str() {
82 "yes" | "true" | "1" => Ok(true),
83 "no" | "false" | "0" | "" => Ok(false),
84 other => Err(serde::de::Error::custom(format!(
85 "`{other}` is neither `yes` nor `no`"
86 ))),
87 }
88}
89
90#[derive(Debug, Deserialize)]
92pub(crate) struct Count {
93 pub(crate) count: String,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub enum Field {
103 Oci,
105 Citing,
107 Cited,
109 Creation,
111 Timespan,
113 JournalSelfCitation,
115 AuthorSelfCitation,
117}
118
119impl Field {
120 pub fn name(&self) -> &'static str {
122 match self {
123 Field::Oci => "oci",
124 Field::Citing => "citing",
125 Field::Cited => "cited",
126 Field::Creation => "creation",
127 Field::Timespan => "timespan",
128 Field::JournalSelfCitation => "journal_sc",
129 Field::AuthorSelfCitation => "author_sc",
130 }
131 }
132}
133
134impl fmt::Display for Field {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.write_str(self.name())
137 }
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
142pub enum Comparison {
143 #[default]
145 Is,
146 GreaterThan,
148 LessThan,
150}
151
152impl Comparison {
153 fn prefix(&self) -> &'static str {
154 match self {
155 Comparison::Is => "",
156 Comparison::GreaterThan => ">",
157 Comparison::LessThan => "<",
158 }
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct Filter {
168 field: Field,
169 comparison: Comparison,
170 value: String,
171}
172
173impl Filter {
174 pub fn is(field: Field, value: impl Into<String>) -> Self {
176 Filter {
177 field,
178 comparison: Comparison::Is,
179 value: value.into(),
180 }
181 }
182
183 pub fn greater_than(field: Field, value: impl Into<String>) -> Self {
186 Filter {
187 field,
188 comparison: Comparison::GreaterThan,
189 value: value.into(),
190 }
191 }
192
193 pub fn less_than(field: Field, value: impl Into<String>) -> Self {
195 Filter {
196 field,
197 comparison: Comparison::LessThan,
198 value: value.into(),
199 }
200 }
201}
202
203impl fmt::Display for Filter {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 write!(
206 f,
207 "{}:{}{}",
208 self.field,
209 self.comparison.prefix(),
210 self.value
211 )
212 }
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
217pub enum Order {
218 #[default]
220 Ascending,
221 Descending,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct Sort {
228 field: Field,
229 order: Order,
230}
231
232impl Sort {
233 pub fn ascending(field: Field) -> Self {
235 Sort {
236 field,
237 order: Order::Ascending,
238 }
239 }
240
241 pub fn descending(field: Field) -> Self {
243 Sort {
244 field,
245 order: Order::Descending,
246 }
247 }
248}
249
250impl fmt::Display for Sort {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 let order = match self.order {
253 Order::Ascending => "asc",
254 Order::Descending => "desc",
255 };
256 write!(f, "{order}({})", self.field)
257 }
258}
259
260#[derive(Debug, Clone, Default, PartialEq, Eq)]
274pub struct Refine {
275 filters: Vec<Filter>,
276 sort: Option<Sort>,
277}
278
279impl Refine {
280 pub fn new() -> Self {
282 Refine::default()
283 }
284
285 pub fn filter(mut self, filter: Filter) -> Self {
287 self.filters.push(filter);
288 self
289 }
290
291 pub fn sort(mut self, sort: Sort) -> Self {
293 self.sort = Some(sort);
294 self
295 }
296
297 pub fn is_empty(&self) -> bool {
299 self.filters.is_empty() && self.sort.is_none()
300 }
301
302 pub(crate) fn params(&self) -> Vec<(&'static str, String)> {
304 let filters = self
305 .filters
306 .iter()
307 .map(|filter| ("filter", filter.to_string()));
308 let sort = self.sort.map(|sort| ("sort", sort.to_string()));
309 filters.chain(sort).collect()
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 const WIRE: &str = r#"{
320 "oci": "06024047477-06220256775",
321 "citing": "omid:br/06024047477 doi:10.22533/at.ed.9662430046",
322 "cited": "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
323 "creation": "2024",
324 "timespan": "P2Y",
325 "journal_sc": "no",
326 "author_sc": "no"
327 }"#;
328
329 #[test]
330 fn a_citation_reads_every_stringly_typed_field() {
331 let citation: Citation = serde_json::from_str(WIRE).unwrap();
332
333 assert_eq!(citation.oci.to_string(), "06024047477-06220256775");
334 assert_eq!(citation.citing_doi(), Some("10.22533/at.ed.9662430046"));
335 assert_eq!(citation.cited_doi(), Some("10.1016/j.marpol.2021.104855"));
336 assert_eq!(citation.creation.unwrap().year(), 2024);
337 assert_eq!(citation.timespan.unwrap().as_months(), 24);
338 assert!(!citation.journal_self_citation);
339 assert!(!citation.author_self_citation);
340 assert_eq!(citation.cited.len(), 3);
342 }
343
344 #[test]
345 fn an_unknown_creation_or_timespan_is_none_rather_than_an_error() {
346 let wire = WIRE.replace(r#""creation": "2024""#, r#""creation": """#);
347 let wire = wire.replace(r#""timespan": "P2Y""#, r#""timespan": """#);
348
349 let citation: Citation = serde_json::from_str(&wire).unwrap();
350 assert_eq!(citation.creation, None);
351 assert_eq!(citation.timespan, None);
352 }
353
354 #[test]
355 fn a_self_citation_reads_as_the_boolean_it_is() {
356 let wire = WIRE.replace(r#""author_sc": "no""#, r#""author_sc": "yes""#);
357 let citation: Citation = serde_json::from_str(&wire).unwrap();
358 assert!(citation.author_self_citation);
359 }
360
361 #[test]
362 fn a_refinement_renders_the_parameters_the_api_reads() {
363 let refine = Refine::new()
364 .filter(Filter::greater_than(Field::Creation, "2023"))
365 .filter(Filter::is(Field::AuthorSelfCitation, "no"))
366 .sort(Sort::descending(Field::Timespan));
367
368 assert_eq!(
369 refine.params(),
370 vec![
371 ("filter", "creation:>2023".to_string()),
372 ("filter", "author_sc:no".to_string()),
373 ("sort", "desc(timespan)".to_string()),
374 ]
375 );
376 }
377
378 #[test]
379 fn an_empty_refinement_asks_for_nothing() {
380 assert!(Refine::new().is_empty());
381 assert!(Refine::new().params().is_empty());
382 }
383}