zenodo-rs 0.1.2

Rust client for Zenodo deposition workflows, record retrieval, and artifact downloads.
Documentation
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Core data models for depositions, records, and files.
//!
//! These types are primarily returned by the client rather than constructed by
//! callers. They represent the stable, typed parts of Zenodo payloads while
//! still preserving unknown fields for forward compatibility.
//!
//! In practice, most callers touch:
//!
//! - [`Deposition`] for draft and publish state
//! - [`Record`] for published metadata and links
//! - [`RecordFile`] for downloadable files
//! - [`ArtifactInfo`] and [`PublishedRecord`] for higher-level summaries

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use url::Url;

use crate::ids::{BucketUrl, ConceptRecId, DepositionFileId, DepositionId, Doi, RecordId};
use crate::metadata::RecordMetadata;
use crate::serde_util::{deserialize_option_u64ish, deserialize_stringish, deserialize_u64ish};

macro_rules! string_enum {
    ($(#[$enum_meta:meta])* $name:ident { $($(#[$variant_meta:meta])* $variant:ident => $value:literal),+ $(,)? }) => {
        $(#[$enum_meta])*
        #[derive(Clone, Debug, PartialEq, Eq)]
        #[non_exhaustive]
        pub enum $name {
            $($(#[$variant_meta])* $variant,)+
            /// A server value unknown to this crate version.
            Unknown(
                /// Raw server value.
                String
            ),
        }

        impl Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                serializer.serialize_str(match self {
                    $(Self::$variant => $value,)+
                    Self::Unknown(value) => value.as_str(),
                })
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Ok(match value.as_str() {
                    $($value => Self::$variant,)+
                    _ => Self::Unknown(value),
                })
            }
        }
    };
}

string_enum!(
    #[derive(Default)]
    /// High-level Zenodo deposition workflow state.
    DepositState {
        /// Draft work is still in progress.
        #[default]
        InProgress => "inprogress",
        /// Unpublished draft state returned by Zenodo's live API and examples.
        Unsubmitted => "unsubmitted",
        /// Processing completed successfully.
        Done => "done",
        /// Processing failed.
        Error => "error"
    }
);

string_enum!(
    #[derive(Default)]
    /// Publication status for a record payload.
    RecordPublicationStatus {
        /// The record is published and publicly visible.
        #[default]
        Published => "published",
        /// The record is still a draft.
        Draft => "draft"
    }
);

/// Combined publication and processing status for a deposition.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct DepositionStatus {
    /// Whether the deposition has been published.
    #[serde(default)]
    pub submitted: bool,
    /// Zenodo's processing state for the deposition.
    #[serde(default)]
    pub state: DepositState,
}

/// File attached to a draft deposition.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DepositionFile {
    /// Deposition file identifier.
    pub id: DepositionFileId,
    /// Original filename.
    pub filename: String,
    /// File size in bytes.
    #[serde(default, deserialize_with = "deserialize_u64ish")]
    pub filesize: u64,
    /// Reported checksum, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Link relations returned on a deposition resource.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct DepositionLinks {
    /// Canonical API URL for the deposition.
    #[serde(rename = "self", default, skip_serializing_if = "Option::is_none")]
    pub self_: Option<Url>,
    /// Bucket URL used for draft file uploads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bucket: Option<BucketUrl>,
    /// URL for the draft file listing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub files: Option<Url>,
    /// URL for the publish action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publish: Option<Url>,
    /// URL for the edit action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edit: Option<Url>,
    /// URL for the discard action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discard: Option<Url>,
    /// URL for the latest editable draft after `newversion`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_draft: Option<Url>,
    /// URL for the latest published record in the family.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest: Option<Url>,
    /// URL for the versions listing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub versions: Option<Url>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Zenodo deposition resource, including draft and published depositions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Deposition {
    /// Deposition identifier.
    pub id: DepositionId,
    /// Concept record identifier shared across versions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conceptrecid: Option<ConceptRecId>,
    /// Published record identifier, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record_id: Option<RecordId>,
    /// Version-specific DOI, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<Doi>,
    /// Concept DOI shared across versions, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conceptdoi: Option<Doi>,
    /// Publication and processing status fields.
    #[serde(flatten)]
    pub status: DepositionStatus,
    /// Raw deposition metadata.
    #[serde(default)]
    pub metadata: Value,
    /// Files currently visible on the deposition.
    #[serde(default)]
    pub files: Vec<DepositionFile>,
    /// Known deposition link relations.
    #[serde(default)]
    pub links: DepositionLinks,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

impl Deposition {
    /// Returns `true` when the deposition has been published.
    #[must_use]
    pub fn is_published(&self) -> bool {
        self.status.submitted
    }

    /// Returns `true` when Zenodo reports that metadata edits are allowed.
    #[must_use]
    pub fn allows_metadata_edits(&self) -> bool {
        matches!(
            self.status.state,
            DepositState::InProgress | DepositState::Unsubmitted
        )
    }

    /// Returns the `latest_draft` link, when present.
    #[must_use]
    pub fn latest_draft_url(&self) -> Option<&Url> {
        self.links.latest_draft.as_ref()
    }

    /// Returns the bucket upload URL, when present.
    #[must_use]
    pub fn bucket_url(&self) -> Option<&BucketUrl> {
        self.links.bucket.as_ref()
    }
}

/// Result of a successful bucket upload.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct BucketObject {
    /// Server-side object identifier, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Uploaded object key.
    pub key: String,
    /// Object size in bytes.
    #[serde(default, deserialize_with = "deserialize_u64ish")]
    pub size: u64,
    /// Reported checksum, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Per-file links returned on a record file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordFileLinks {
    /// Canonical API URL for the file.
    #[serde(rename = "self", default, skip_serializing_if = "Option::is_none")]
    pub self_: Option<Url>,
    /// Direct content download URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<Url>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// File attached to a published record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordFile {
    /// Server-side file identifier.
    pub id: String,
    /// File key used for downloads.
    pub key: String,
    /// File size in bytes.
    #[serde(default, deserialize_with = "deserialize_u64ish")]
    pub size: u64,
    /// Reported checksum, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    /// Known file link relations.
    #[serde(default)]
    pub links: RecordFileLinks,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

impl RecordFile {
    /// Returns the best download URL for the file.
    #[must_use]
    pub fn download_url(&self) -> Option<&Url> {
        self.links.content.as_ref().or(self.links.self_.as_ref())
    }
}

/// Link relations returned on a record resource.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordLinks {
    /// Canonical API URL for the record.
    #[serde(rename = "self", default, skip_serializing_if = "Option::is_none")]
    pub self_: Option<Url>,
    /// Canonical HTML page for the record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub self_html: Option<Url>,
    /// Alternate HTML page link, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub html: Option<Url>,
    /// URL for the latest record version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest: Option<Url>,
    /// URL for the versions listing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub versions: Option<Url>,
    /// URL for the record's files listing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub files: Option<Url>,
    /// URL for downloading the record archive.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub archive: Option<Url>,
    /// DOI URL, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<Url>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Basic record usage statistics.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordStats {
    /// Number of downloads, when Zenodo reports it.
    #[serde(
        default,
        deserialize_with = "deserialize_option_u64ish",
        skip_serializing_if = "Option::is_none"
    )]
    pub downloads: Option<u64>,
    /// Number of views, when Zenodo reports it.
    #[serde(
        default,
        deserialize_with = "deserialize_option_u64ish",
        skip_serializing_if = "Option::is_none"
    )]
    pub views: Option<u64>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Persistent identifier entry attached to a record or parent record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PersistentIdentifier {
    /// Identifier value.
    pub identifier: String,
    /// PID provider identifier, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// PID client identifier, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client: Option<String>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Persistent identifier block attached to a record or parent record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordPids {
    /// DOI PID entry, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<PersistentIdentifier>,
    /// Concept DOI PID entry, when present.
    #[serde(
        rename = "concept-doi",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub concept_doi: Option<PersistentIdentifier>,
    /// Record ID PID entry, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recid: Option<PersistentIdentifier>,
    /// OAI PID entry, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oai: Option<PersistentIdentifier>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Parent-community block attached to a published record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordParentCommunities {
    /// Default community identifier, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Community identifiers attached to the parent record.
    #[serde(default)]
    pub ids: Vec<String>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Parent-record block attached to a published record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RecordParent {
    /// Parent identifier, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Parent communities block, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub communities: Option<RecordParentCommunities>,
    /// Parent persistent identifiers block, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pids: Option<RecordPids>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

/// Published record resource returned by Zenodo's records API.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Record {
    /// Record creation timestamp, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created: Option<DateTime<Utc>>,
    /// Record modification timestamp, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modified: Option<DateTime<Utc>>,
    /// Record identifier.
    pub id: RecordId,
    /// String-form record identifier as returned by Zenodo.
    #[serde(deserialize_with = "deserialize_stringish")]
    pub recid: String,
    /// Concept record identifier shared across versions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conceptrecid: Option<ConceptRecId>,
    /// Version-specific DOI, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<Doi>,
    /// Concept DOI shared across versions, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conceptdoi: Option<Doi>,
    /// Typed record metadata.
    #[serde(default)]
    pub metadata: RecordMetadata,
    /// Files exposed on the record.
    #[serde(default)]
    pub files: Vec<RecordFile>,
    /// Known record link relations.
    #[serde(default)]
    pub links: RecordLinks,
    /// Parent record block, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<RecordParent>,
    /// Persistent identifiers block, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pids: Option<RecordPids>,
    /// Record usage statistics, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stats: Option<RecordStats>,
    /// Publication status reported by Zenodo.
    #[serde(default)]
    pub status: RecordPublicationStatus,
    /// Revision number, when present.
    #[serde(
        default,
        deserialize_with = "deserialize_option_u64ish",
        skip_serializing_if = "Option::is_none"
    )]
    pub revision: Option<u64>,
    /// Additional untyped fields preserved for forward compatibility.
    #[serde(flatten, default)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Deserialize)]
struct RecordWire {
    #[serde(default)]
    created: Option<DateTime<Utc>>,
    #[serde(default)]
    modified: Option<DateTime<Utc>>,
    #[serde(default)]
    updated: Option<DateTime<Utc>>,
    id: RecordId,
    #[serde(deserialize_with = "deserialize_stringish")]
    recid: String,
    #[serde(default)]
    conceptrecid: Option<ConceptRecId>,
    #[serde(default)]
    doi: Option<Doi>,
    #[serde(default)]
    conceptdoi: Option<Doi>,
    #[serde(default)]
    metadata: RecordMetadata,
    #[serde(default)]
    files: Vec<RecordFile>,
    #[serde(default)]
    links: RecordLinks,
    #[serde(default)]
    parent: Option<RecordParent>,
    #[serde(default)]
    pids: Option<RecordPids>,
    #[serde(default)]
    stats: Option<RecordStats>,
    #[serde(default)]
    status: RecordPublicationStatus,
    #[serde(default, deserialize_with = "deserialize_option_u64ish")]
    revision: Option<u64>,
    #[serde(flatten, default)]
    extra: BTreeMap<String, Value>,
}

impl<'de> Deserialize<'de> for Record {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = RecordWire::deserialize(deserializer)?;
        Ok(Self {
            created: wire.created,
            modified: wire.modified.or(wire.updated),
            id: wire.id,
            recid: wire.recid,
            conceptrecid: wire.conceptrecid,
            doi: wire.doi,
            conceptdoi: wire.conceptdoi,
            metadata: wire.metadata,
            files: wire.files,
            links: wire.links,
            parent: wire.parent,
            pids: wire.pids,
            stats: wire.stats,
            status: wire.status,
            revision: wire.revision,
            extra: wire.extra,
        })
    }
}

impl Record {
    /// Returns the link to the latest record version, when present.
    #[must_use]
    pub fn latest_url(&self) -> Option<&Url> {
        self.links.latest.as_ref()
    }

    /// Returns the record archive link, when present.
    #[must_use]
    pub fn archive_url(&self) -> Option<&Url> {
        self.links.archive.as_ref()
    }

    /// Finds a file by exact key.
    #[must_use]
    pub fn file_by_key(&self, key: &str) -> Option<&RecordFile> {
        self.files.iter().find(|file| file.key == key)
    }
}

/// Aggregated record details used by higher-level artifact helpers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactInfo {
    /// The originally requested record.
    pub record: Record,
    /// The latest resolved record in the same family.
    pub latest: Record,
    /// Latest record files indexed by key.
    pub files_by_key: BTreeMap<String, RecordFile>,
}

/// Result of a complete publish workflow.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PublishedRecord {
    /// Final deposition payload after publishing.
    pub deposition: Deposition,
    /// Published record fetched from the records API.
    pub record: Record,
}

#[cfg(test)]
mod tests {
    use super::{
        BucketObject, DepositState, Deposition, DepositionFile, Record, RecordFile, RecordLinks,
        RecordPublicationStatus,
    };
    use serde_json::json;

    #[test]
    fn preserves_unknown_record_fields() {
        let record: Record = serde_json::from_value(json!({
            "created": "2026-04-03T12:00:00+00:00",
            "updated": "2026-04-03T13:00:00+00:00",
            "id": 42,
            "recid": "42",
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {},
            "parent": {
                "id": "parent-1",
                "communities": {
                    "default": "zenodo",
                    "ids": ["zenodo", "sandbox"]
                },
                "pids": {
                    "doi": {
                        "identifier": "10.5281/zenodo.42"
                    }
                }
            },
            "pids": {
                "doi": {
                    "identifier": "10.5281/zenodo.42"
                },
                "concept-doi": {
                    "identifier": "10.5281/zenodo.41"
                }
            },
            "mystery": "value"
        }))
        .unwrap();

        assert!(record.created.is_some());
        assert!(record.modified.is_some());
        assert_eq!(
            record
                .parent
                .as_ref()
                .and_then(|parent| parent.id.as_deref()),
            Some("parent-1")
        );
        assert_eq!(
            record
                .pids
                .as_ref()
                .and_then(|pids| pids.doi.as_ref())
                .map(|pid| pid.identifier.as_str()),
            Some("10.5281/zenodo.42")
        );
        assert_eq!(record.extra.get("mystery"), Some(&json!("value")));
    }

    #[test]
    fn record_accepts_both_modified_and_updated_timestamps() {
        let record: Record = serde_json::from_value(json!({
            "created": "2026-04-03T12:00:00+00:00",
            "modified": "2026-04-03T14:00:00+00:00",
            "updated": "2026-04-03T13:00:00+00:00",
            "id": 42,
            "recid": 42.0,
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {}
        }))
        .unwrap();

        assert!(record.created.is_some());
        assert_eq!(
            record.modified.unwrap().to_rfc3339(),
            "2026-04-03T14:00:00+00:00"
        );
    }

    #[test]
    fn model_string_enums_preserve_unknown_values() {
        let state: DepositState = serde_json::from_value(json!("queued")).unwrap();
        let status: RecordPublicationStatus = serde_json::from_value(json!("embargoed")).unwrap();
        let unsubmitted: DepositState = serde_json::from_value(json!("unsubmitted")).unwrap();

        assert_eq!(serde_json::to_value(&state).unwrap(), json!("queued"));
        assert_eq!(serde_json::to_value(&status).unwrap(), json!("embargoed"));
        assert_eq!(
            serde_json::to_value(&unsubmitted).unwrap(),
            json!("unsubmitted")
        );
        assert!(matches!(state, DepositState::Unknown(value) if value == "queued"));
        assert_eq!(unsubmitted, DepositState::Unsubmitted);
        assert!(matches!(status, RecordPublicationStatus::Unknown(value) if value == "embargoed"));
    }

    #[test]
    fn follows_latest_draft_link() {
        let deposition: Deposition = serde_json::from_value(serde_json::json!({
            "id": 7,
            "submitted": true,
            "state": "done",
            "metadata": {},
            "files": [],
            "links": {
                "latest_draft": "https://zenodo.org/api/deposit/depositions/8"
            }
        }))
        .unwrap();

        assert_eq!(
            deposition.latest_draft_url().unwrap().as_str(),
            "https://zenodo.org/api/deposit/depositions/8"
        );
    }

    #[test]
    fn record_file_prefers_content_link() {
        let file: RecordFile = serde_json::from_value(serde_json::json!({
            "id": "f1",
            "key": "artifact.bin",
            "links": {
                "self": "https://zenodo.org/api/files/self",
                "content": "https://zenodo.org/api/files/content"
            }
        }))
        .unwrap();

        assert_eq!(
            file.download_url().unwrap().as_str(),
            "https://zenodo.org/api/files/content"
        );
    }

    #[test]
    fn deposition_file_accepts_integer_like_numeric_shapes() {
        let float_file: DepositionFile = serde_json::from_value(serde_json::json!({
            "id": "f1",
            "filename": "artifact.bin",
            "filesize": 14.0
        }))
        .unwrap();
        assert_eq!(float_file.filesize, 14);

        let string_file: DepositionFile = serde_json::from_value(serde_json::json!({
            "id": "f2",
            "filename": "artifact.bin",
            "filesize": "18"
        }))
        .unwrap();
        assert_eq!(string_file.filesize, 18);
    }

    #[test]
    fn deposition_file_rejects_non_integral_sizes() {
        let error = serde_json::from_value::<DepositionFile>(serde_json::json!({
            "id": "f1",
            "filename": "artifact.bin",
            "filesize": 14.5
        }))
        .unwrap_err();
        assert!(error.to_string().contains("integer-like"));
    }

    #[test]
    fn other_numeric_response_fields_accept_integer_like_shapes() {
        let uploaded: BucketObject = serde_json::from_value(serde_json::json!({
            "key": "artifact.bin",
            "size": "14"
        }))
        .unwrap();
        let published_file: RecordFile = serde_json::from_value(serde_json::json!({
            "id": "f1",
            "key": "artifact.bin",
            "size": 15.0,
            "links": {}
        }))
        .unwrap();
        let record: Record = serde_json::from_value(serde_json::json!({
            "id": 42.0,
            "recid": 42.0,
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {},
            "stats": {
                "downloads": "16",
                "views": 17.0
            },
            "revision": "18"
        }))
        .unwrap();

        assert_eq!(uploaded.size, 14);
        assert_eq!(published_file.size, 15);
        assert_eq!(record.id.0, 42);
        assert_eq!(
            record.stats.as_ref().and_then(|stats| stats.downloads),
            Some(16)
        );
        assert_eq!(
            record.stats.as_ref().and_then(|stats| stats.views),
            Some(17)
        );
        assert_eq!(record.revision, Some(18));
    }

    #[test]
    fn record_and_deposition_helpers_expose_status_and_links() {
        let deposition: Deposition = serde_json::from_value(serde_json::json!({
            "id": 9,
            "submitted": false,
            "state": "mystery-state",
            "metadata": {},
            "files": [],
            "links": {
                "bucket": "https://zenodo.org/api/files/bucket-9"
            }
        }))
        .unwrap();
        let record = Record {
            created: None,
            modified: None,
            id: crate::RecordId(10),
            recid: "10".into(),
            conceptrecid: None,
            doi: None,
            conceptdoi: None,
            metadata: crate::RecordMetadata::default(),
            files: Vec::new(),
            links: RecordLinks::default(),
            parent: None,
            pids: None,
            stats: None,
            status: RecordPublicationStatus::Draft,
            revision: None,
            extra: std::collections::BTreeMap::new(),
        };

        assert!(!deposition.is_published());
        assert!(deposition.bucket_url().is_some());
        assert!(matches!(deposition.status.state, DepositState::Unknown(_)));
        assert!(record.latest_url().is_none());
        assert!(record.archive_url().is_none());
    }

    #[test]
    fn deposition_helpers_treat_unsubmitted_as_editable() {
        let deposition: Deposition = serde_json::from_value(serde_json::json!({
            "id": 11,
            "submitted": false,
            "state": "unsubmitted",
            "metadata": {},
            "files": [],
            "links": {}
        }))
        .unwrap();

        assert_eq!(deposition.status.state, DepositState::Unsubmitted);
        assert!(deposition.allows_metadata_edits());
    }
}