acorn-lib 0.1.59

ACORN library
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
//! ## Research activity identifier (RAiD) metadata schema
//!
//! See <https://metadata.raid.org/en/v1.6/index.html> for official documentation on reference schema.
//!
//! Use ACORN to generate JSON schema for RAiD metadata with `acorn schema raid`
#[cfg(feature = "std")]
use crate::io::current_date;
#[cfg(feature = "std")]
use crate::io::{read_file, License};
use crate::prelude::*;
#[cfg(feature = "std")]
use crate::prelude::{Error, PathBuf};
#[cfg(feature = "std")]
use crate::schema::namespaces::{DEFAULT_ORCID_SCHEMA_URI, DEFAULT_ROR_SCHEMA_URI};
#[cfg(feature = "std")]
use crate::schema::research_activity::ResearchActivity;
use crate::schema::validate::{has_at_least_one_truthy, is_date, is_orcid, is_raid, is_ror, is_unix_epoch, is_year};
use crate::schema::Date;
#[cfg(feature = "std")]
use crate::util::Label;
#[cfg(not(feature = "std"))]
use crate::util::License;
use bon::Builder;
use derive_more::Display;
#[cfg(feature = "std")]
use schemars::schema_for;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
#[cfg(feature = "std")]
use tracing::error;
use validator::{Validate, ValidationError};

/// Allowed values for access types
#[derive(Clone, Debug, Default, Deserialize, Display, JsonSchema, Serialize)]
pub enum AccessType {
    /// Open access
    #[default]
    #[display("open-access")]
    #[serde(rename = "https://vocabularies.coar-repositories.org/access_rights/c_abf2/")]
    OpenAccess,
    /// Embargoed access
    #[display("embargoed-access")]
    #[serde(rename = "https://vocabularies.coar-repositories.org/access_rights/c_f1cf/")]
    EmbargoedAccess,
}
/// CRediT role
///
/// Taxonomy of 14 roles that can be used to describe the key types of contributions typically made to the production and publication of research output such as research articles.
///
/// See <https://www.niso.org/publications/z39104-2022-credit>
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CreditRole {
    /// Ideas; formulation or evolution of overarching research goals and aims.
    #[display("conceptualization")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/conceptualization/")]
    Conceptualization,
    /// Management activities to annotate (produce metadata), scrub data and maintain research data (including software code, where it is necessary for interpreting the data itself) for initial use and later re-use.
    #[display("data-curation")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/data-curation/")]
    DataCuration,
    /// Application of statistical, mathematical, computational, or other formal techniques to analyze or synthesize study data.
    #[display("formal-analysis")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/formal-analysis/")]
    FormalAnalysis,
    /// Acquisition of the financial support for the project leading to this publication.
    #[display("funding-acquisition")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/funding-acquisition/")]
    FundingAcquisition,
    /// Conducting a research and investigation process, specifically performing the experiments, or data/evidence collection.
    #[display("investigation")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/investigation/")]
    Investigation,
    /// Development or design of methodology; creation of models.
    #[display("methodology")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/methodology/")]
    Methodology,
    /// Management and coordination responsibility for the research activity planning and execution.
    #[display("project-administration")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/project-administration/")]
    ProjectAdministration,
    /// Provision of study materials, reagents, materials, patients, laboratory samples, animals, instrumentation, computing resources, or other analysis tools.
    #[display("resources")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/resources/")]
    Resources,
    /// Programming, software development; designing computer programs; implementation of the computer code and supporting algorithms; testing of existing code components.
    #[display("software")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/software/")]
    Software,
    /// Oversight and leadership responsibility for the research activity planning and execution, including mentorship external to the core team.
    #[display("supervision")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/supervision/")]
    Supervision,
    /// Verification, whether as a part of the activity or separate, of the overall replication/reproducibility of results/experiments and other research outputs.
    #[display("validation")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/validation/")]
    Validation,
    /// Preparation, creation and/or presentation of the published work, specifically visualization/data presentation.
    #[display("visualization")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/visualization/")]
    Visualization,
    /// Preparation, creation and/or presentation of the published work, specifically writing the initial draft (including substantive translation).
    #[display("writing-original-draft")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/writing-original-draft/")]
    WritingOriginalDraft,
    /// Preparation, creation and/or presentation of the published work by those from the original research group, specifically critical review, commentary or revision - including pre- or post-publication stages
    #[display("writing-review-editing")]
    #[serde(rename = "https://credit.niso.org/contributor-roles/writing-review-editing/")]
    WritingReviewEditing,
}
/// Description types
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DescriptionType {
    /// Primary description (i.e., a preferred full description or abstract)
    #[display("primary")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/318")]
    Primary,
    /// An alternative description (i.e., an additional or supplementary full description or abstract)
    #[display("alternative")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/319")]
    Alternative,
    /// Brief description (i.e., a shorter version of the primary description)
    #[display("brief")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/3")]
    Brief,
    /// Significance statement
    #[display("significance-statement")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/9")]
    SignificanceStatement,
    /// Methods
    #[display("methods")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/8")]
    Methods,
    /// Objectives
    #[display("objectives")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/7")]
    Objectives,
    /// Acknowledgements (i.e., for recognition of people not listed as Contributors or organizations not listed as organizations)
    #[display("acknowledgements")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/392")]
    Acknowledgements,
    /// Other (i.e., any other descriptive information such as a note)
    #[display("other")]
    #[serde(rename = "https://vocabulary.raid.org/description.type.schema/6")]
    Other,
}
/// Category of input, output, or process document
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ObjectCategoryType {
    /// Output
    #[display("output")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.category.id/190")]
    Output,
    /// Input
    #[display("input")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.category.id/191")]
    Input,
    /// Internal process document or artifact
    #[display("internal-process-document")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.category.id/192")]
    InternalProcessDocument,
}
/// Type of input, output, or process document
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ObjectType {
    /// Output management plan
    #[display("output-management-plan")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/247")]
    OutputManagementPlan,
    /// Conference poster
    #[display("conference-poster")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/248")]
    ConferencePoster,
    /// Workflow
    #[display("workflow")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/249")]
    Workflow,
    /// Journal article
    #[display("journal-article")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/250")]
    JournalArticle,
    /// Standard
    #[display("standard")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/251")]
    Standard,
    /// Report
    #[display("report")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/252")]
    Report,
    /// Dissertation
    #[display("dissertation")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/253")]
    Dissertation,
    /// Preprint
    #[display("preprint")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/254")]
    Preprint,
    /// Data paper
    #[display("data-paper")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/255")]
    DataPaper,
    /// Computational notebook (e.g., Jupyter notebook)
    #[display("computational-notebook")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/256")]
    ComputationalNotebook,
    /// Image
    #[display("image")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/257")]
    Image,
    /// Book
    #[display("book")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/258")]
    Book,
    /// Software
    #[display("software")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/259")]
    Software,
    /// Event
    #[display("event")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/260")]
    Event,
    /// Sound
    #[display("sound")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/261")]
    Sound,
    /// Conference proceeding
    #[display("conference-proceeding")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/262")]
    ConferenceProceeding,
    /// Model
    #[display("model")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/263")]
    Model,
    /// Conference paper
    #[display("conference-paper")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/264")]
    ConferencePaper,
    /// Text
    #[display("text")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/265")]
    Text,
    /// Instrument
    #[display("instrument")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/266")]
    Instrument,
    /// Learning object
    #[display("learning-object")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/267")]
    LearningObject,
    /// Prize (excluding funded awards)
    #[display("prize")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/268")]
    Prize,
    /// Dataset
    #[display("dataset")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/269")]
    Dataset,
    /// Physical object
    #[display("physical-object")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/270")]
    PhysicalObject,
    /// Book chapter
    #[display("book-chapter")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/271")]
    BookChapter,
    /// Funding
    /// ### Note
    /// > Includes grants or other cash or in-kind awards, but not prizes
    #[display("funding")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/272")]
    Funding,
    /// Audiovisual
    #[display("audiovisual")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/273")]
    Audiovisual,
    /// Service
    #[display("service")]
    #[serde(rename = "https://vocabulary.raid.org/relatedObject.type.schema/274")]
    Service,
}
/// Organization role identifier
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum OrganizationRoleType {
    /// Lead research organization
    #[display("lead-research-organization")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/182")]
    LeadResearchOrganization,
    /// Other research organization
    #[display("other-research-organization")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/183")]
    OtherResearchOrganization,
    /// Partner organization (i.e., a non-research organization, such as an industry, government, or community partner that is collaborating on the project or activity, as a research partner rather than a hired consultant or contractor)
    #[display("partner-organization")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/184")]
    PartnerOrganization,
    /// Contractor (i.e., a consulting organization hired by the project)
    #[display("contractor")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/185")]
    Contractor,
    /// Funder (i.e., an organization underwriting the research via a cash or in-kind grant, prize, or investment, but not otherwise listed as a research organization, partner organization or contractor)
    #[display("funder")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/186")]
    Funder,
    /// Facility (i.e., an organization providing access to physical or digital infrastructure, but not otherwise listed as a research organization, partner organization or contractor)
    #[display("facility")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/187")]
    Facility,
    /// Other Organiation not covered by the roles above
    #[display("other-organization")]
    #[serde(rename = "https://vocabulary.raid.org/organisation.role.schema/188")]
    OtherOrganization,
}
/// Represents a contributor's administrative position on a project (such as their position on a grant application)
///
/// <div class="warning">Use contributor role to define scientific or scholarly contributions</div>
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PositionType {
    /// Principal Investigator
    #[display("principal-investigator")]
    #[serde(rename = "https://vocabulary.raid.org/contributor.position.schema/307")]
    PrincipalInvestigator,
    /// Co-Investigator
    #[display("co-investigator")]
    #[serde(rename = "https://vocabulary.raid.org/contributor.position.schema/308")]
    CoInvestigator,
    /// Partner Investigator (e.g., industry, government, or community collaborator)
    #[display("partner-investigator")]
    #[serde(rename = "https://vocabulary.raid.org/contributor.position.schema/309")]
    PartnerInvestigator,
    /// Consultant (e.g., someone hired as a contract researcher by the project)
    #[display("consultant")]
    #[serde(rename = "https://vocabulary.raid.org/contributor.position.schema/310")]
    Consultant,
    /// Other Participant not covered by one of the positions above, e.g., "member" or "other significant contributor"
    #[display("other")]
    #[serde(rename = "https://vocabulary.raid.org/contributor.position.schema/311")]
    Other,
}
/// RAiD Relation Type
///
/// Describes the relationship being one activity and another
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum RelatedRaidType {
    /// Obsoletes
    /// > For resolving duplicate RAiDs
    #[display("obsoletes")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/198")]
    Obsoletes,
    /// Is source of
    #[display("is-source-of")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/199")]
    IsSourceOf,
    /// Is derived from
    #[display("is-derived-from")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/200")]
    IsDerivedFrom,
    /// Has part
    #[display("has-part")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/201")]
    HasPart,
    /// Is part of
    #[display("is-part-of")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/202")]
    IsPartOf,
    /// Is continued by
    #[display("is-continued-by")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/203")]
    IsContinuedBy,
    /// Continues
    #[display("continues")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/204")]
    Continues,
    /// Is obsoleted by
    /// > For resolving duplicate RAiDs
    #[display("is-obsoleted-by")]
    #[serde(rename = "https://vocabulary.raid.org/relatedRaid.type.schema/205")]
    IsObsoletedBy,
}
/// Allowed values for title identifiers
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, Serialize)]
pub enum TitleType {
    /// Title acronym
    #[display("acronym")]
    #[serde(rename = "https://vocabulary.raid.org/title.type.schema/156")]
    Acronym,
    /// Alternative title, including subtitle or other supplemental title
    #[display("alternative")]
    #[serde(rename = "https://vocabulary.raid.org/title.type.schema/4")]
    Alternative,
    /// Preferred full or long title
    #[display("primary")]
    #[serde(rename = "https://vocabulary.raid.org/title.type.schema/5")]
    Primary,
    /// Abreviated title
    #[display("short")]
    #[serde(rename = "https://vocabulary.raid.org/title.type.schema/157")]
    Short,
}
/// Metadata schema block containing RAiD access information
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Access {
    /// Access type
    #[validate(required, nested)]
    #[serde(rename = "type")]
    pub access_type: Option<AccessIdentifier>,
    /// Date an embargo on access to the RAiD metadata ends
    /// ### Format
    /// > [ISO 8601] standard date (e.g., `YYYY-MM-DD`)
    ///
    /// <div class="warning">Mandatory if access type is "embargoed"</div>
    ///
    /// <div class="warning">Embargo expiration dates may not lay more than 18 months from the date the RAiD was registered. Year, month, and day mush be specified.</div>
    ///
    /// [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601
    #[validate(custom(function = "is_date"))]
    pub embargo_expiry: Option<String>,
    /// Access statement
    ///
    /// <div class="warning">Mandatory if access type is not "open"</div>
    #[validate(nested)]
    pub statement: Option<AccessStatement>,
}
/// Access type identifier
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AccessIdentifier {
    /// Type of access granted to a RAiD metadata record
    pub id: AccessType,
    /// URI of the access type schema
    #[builder(default = "https://vocabularies.coar-repositories.org/access_rights/".to_string())]
    #[validate(url)]
    pub schema_uri: String,
}
/// Metadata schema block containing an explanation for any access type that is not "open", with the explanation's associated properties
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AccessStatement {
    /// The text of an access statement that explains any restrictions on access
    #[validate(length(min = 1, max = 1000))]
    pub text: Option<String>,
    /// The language of the access statement
    #[validate(nested)]
    pub language: Option<Language>,
}
/// Metadata schema block containing alternative local or global identifiers for the project or activity associated with the RAiD
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AlternateIdentifier {
    /// Identifier other than the RAiD applied to the project or activity
    /// ### Example
    /// > ACORN research activity data (RAD) [identifier]
    ///
    /// [identifier]: ./struct.Metadata.html#structfield.identifier
    pub id: String,
    /// Free text description of the type of alternate identifier supplied
    #[serde(rename = "type")]
    pub alternate_identifier_type: String,
}
/// Link to another website related to the project or activity
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AlternateUrl {
    #[validate(url)]
    url: String,
}
/// Metadata schema block containing a contributor to a RAiD and their associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/contributors.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Contributor {
    /// Contributor (person) associated with a project or activity identified by a persistent identifier (PID)
    ///
    /// Should be a valid *full* ORCiD
    /// ### Example
    /// > "<https://orcid.org/0000-0000-0000-0000>"
    #[validate(required, custom(function = "is_orcid"))]
    pub id: Option<String>,
    /// URI of the contributor identifier schema
    ///
    /// <div class="warning">PID is required and (currently) only [ORCID] and [ISNI] are allowed</div>
    ///
    /// [ISNI]: https://isni.org/
    /// [ORCID]: https://orcid.org/
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Contibutor status
    // TODO: Not in schema docs
    pub status: Option<String>,
    /// Text describing status
    pub status_message: Option<String>,
    /// Contributor's administrative position on a project or activity
    // TODO: Schema docs list position as singular
    #[validate(nested)]
    pub position: Vec<ContributorPosition>,
    /// Flag indicating that the contributor as a project leader
    #[builder(default = false)]
    pub leader: bool,
    /// Flag indicating that the contributor as a project contact
    #[builder(default = false)]
    pub contact: bool,
    /// Contributor email
    // TODO: Not in schema docs
    #[validate(email)]
    pub email: Option<String>,
    /// Contributor's role(s) on a project or activity
    #[validate(nested)]
    pub role: Option<Vec<Role>>,
    /// Contributor UUID
    // TODO: Not in schema docs
    pub uuid: Option<String>,
}
/// Metadata schema sub-block describing a contributor's administrative position on a project or activity
///
/// See <https://metadata.raid.org/en/v1.6/core/contributors.html#contributor-position>
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ContributorPosition {
    /// Contributor's administrative position in the project
    /// ### Example
    /// > "Principal Investigator"
    pub id: PositionType,
    /// URI of the position schema used
    ///
    /// <div class="warning">Controlled list of schemas is informed by Simon Cox's [Project Ontology], [OpenAIRE] "Project" guidelines, NIH definitions, ARC definitions, and DataCite Metadata Schema 4.4 Appendix 1 Table 5 "Description of contributorType".</div>
    ///
    /// [OpenAIRE]: https://guidelines.openaire.eu/en/latest/
    /// [Project Ontology]: http://linked.data.gov.au/def/project
    #[builder(default = "https://vocabulary.raid.org/contributor.position.schema/305".to_string())]
    #[validate(url)]
    pub schema_uri: String,
    /// Dates associated with contributor's involvement in a project or activity
    #[validate(custom(function = "has_start_date"), nested)]
    #[serde(flatten)]
    pub date: Date,
}
/// Metadata schema block containing the description of the RAiD and associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/descriptions.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Description {
    /// Description text
    #[validate(required, length(min = 3, max = 1000))]
    pub text: Option<String>,
    /// Description type information
    #[validate(required, nested)]
    #[serde(rename = "type")]
    pub description_type: Option<DescriptionIdentifier>,
    /// Language of the description text
    #[validate(nested)]
    pub language: Option<Language>,
}
/// Metadata schema block declaring the type of description
#[derive(Builder, Clone, Debug, Deserialize, JsonSchema, Serialize, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct DescriptionIdentifier {
    /// Description identifier
    pub id: DescriptionType,
    /// URI of the associated description schema
    #[builder(default = "https://vocabulary.raid.org/description.type.schema/320".to_string())]
    #[validate(url)]
    pub schema_uri: String,
}
/// Metadata schema block containing information about the associated type
#[derive(Builder, Clone, Debug, Deserialize, Serialize, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Identifier {
    /// Type identifier
    pub id: String,
    /// URI of the associated type schema
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Metadata schema sub-block containing free-text keyword describing a project plus associated properties
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Keyword {
    /// Unconstrained keyword or key phrase describing the project or activity
    pub text: String,
    /// Language of the keyword
    #[validate(nested)]
    pub language: Option<Language>,
}
/// Metadata schema block declaring the language of the associated text
#[derive(Builder, Clone, Debug, Deserialize, Serialize, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Language {
    /// Language used for the associated text, identified by a code or another identifier
    /// ### Examples
    /// - "eng"
    /// - "fra"
    /// - "jpn"
    ///
    /// <div class="warning">Limited to <a href="https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes">ISO 639:2023 (Set 3)</a></div>
    #[validate(length(equal = 3))]
    pub id: String,
    /// URI of the associated type schema
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Research Activity Identifier (RAiD) Metadata
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Display, eserde::Deserialize, Serialize, JsonSchema, Validate)]
#[builder(start_fn = init)]
#[display("({identifier:?})")]
#[validate(schema(function = "validate_metadata", skip_on_field_errors = false))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Metadata {
    /// Access for the RAiD metadata
    #[validate(required, nested)]
    #[eserde(compat)]
    pub access: Option<Access>,
    /// Contributors to the RAiD
    #[validate(required, nested, length(min = 1))]
    #[eserde(compat)]
    pub contributor: Option<Vec<Contributor>>,
    /// Dates associated with the RAiD metadata
    #[validate(required, custom(function = "has_start_date"), nested)]
    #[eserde(compat)]
    pub date: Option<Date>,
    /// Metadata schema block containing the RAiD name and associated properties
    #[validate(nested)]
    #[eserde(compat)]
    pub identifier: Option<MetadataIdentifier>,
    /// Title metadata of the RAiD
    ///
    /// <div class="warning">One and only one title should be identified as "primary"</div>
    #[validate(required, nested, length(min = 1))]
    #[eserde(compat)]
    pub title: Option<Vec<Title>>,
    /// Alternate identifiers associated with the RAiD
    #[validate(nested)]
    #[eserde(compat)]
    pub alternate_identifier: Option<Vec<AlternateIdentifier>>,
    /// Alternate URLs associated with the RAiD
    #[validate(nested)]
    #[eserde(compat)]
    pub alternate_url: Option<Vec<AlternateUrl>>,
    /// Description metadata of the RAiD
    #[validate(nested)]
    #[eserde(compat)]
    pub description: Option<Vec<Description>>,
    /// RAiD metadata metadata
    #[validate(nested)]
    #[eserde(compat)]
    pub metadata: Option<MetadataMetadata>,
    /// Organizations associated with the RAiD
    ///
    /// <div class="warning">If only one organization is listed, it's role defaults to "Lead Research Organization"</div>
    ///
    /// <div class="warning">One and only one organization should be identified as "Lead Research Organization"</div>
    #[validate(nested)]
    #[serde(alias = "organisation")]
    #[eserde(compat)]
    pub organization: Option<Vec<Organization>>,
    /// Related objects associated with the RAiD
    #[validate(nested)]
    #[eserde(compat)]
    pub related_object: Option<Vec<RelatedObject>>,
    /// Related RAiD(s) associated with the RAiD
    #[validate(nested)]
    #[eserde(compat)]
    pub related_raid: Option<Vec<RelatedRaid>>,
    /// Spatial coverage
    #[validate(nested)]
    #[eserde(compat)]
    pub spatial_coverage: Option<Vec<SpatialCoverage>>,
    /// Subjects
    #[validate(nested)]
    #[eserde(compat)]
    pub subject: Option<Vec<Subject>>,
    /// Traditional knowledge information
    #[validate(nested)]
    #[eserde(compat)]
    pub traditional_knowledge_label: Option<Vec<TraditionalKnowledgeLabel>>,
}
/// Metadata schema block containing the RAiD name and associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/identifier.html#identifier>
#[derive(Builder, Clone, Debug, Serialize, Deserialize, Display, JsonSchema, Validate)]
#[display("{id:?}")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MetadataIdentifier {
    /// Unique alphanumeric character string that identifies a Research Activity Identifier (RAiD) name
    /// ### Format
    /// > `https://raid.org/prefix/suffix`
    #[validate(required, custom(function = "is_raid"))]
    pub id: Option<String>,
    /// URI of the identifier scheme used to identify RAiDs
    /// ### Example
    /// > `https://raid.org/`
    #[validate(required, url)]
    pub schema_uri: Option<String>,
    /// RAiD owner
    #[validate(required, nested)]
    pub owner: Option<Owner>,
    /// RAiD agency URL
    #[validate(required, url)]
    pub raid_agency_url: Option<String>,
    /// Mtadata schema sub-block declaring the Registration Agency that minted the RAiD
    #[validate(required, nested)]
    pub registration_agency: Option<RegistrationAgency>,
    /// The licence, or licence waiver, under which the RAiD metadata record associated with this Identifier has been issued
    ///
    /// <div class="warning">Only supports CC-0 (?)</div>
    #[validate(required, nested)]
    pub license: Option<License>,
    /// Version number of the RAiD
    #[validate(required, range(min = 0))]
    pub version: Option<u32>,
}
/// Information about edit history of associated RAiD
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MetadataMetadata {
    /// Date and time the RAiD metadata record was created
    ///
    /// Should be Unix epoch timestamp
    #[validate(custom(function = "is_unix_epoch"))]
    pub created: usize,
    /// Date and time the RAiD metadata record was last updated
    ///
    /// Should be Unix epoch timestamp
    #[validate(custom(function = "is_unix_epoch"))]
    pub updated: usize,
}
/// Metadata schema block containing the organization associated with a RAiD and its associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/organisations.html#organisation>
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Organization {
    /// Organization identifier
    /// ### Example
    /// > `https://ror.org/01qz5mb56`
    ///
    /// <div class="warning">Should be <a href="https://ror.org">ROR</a>, if available</div>
    #[validate(custom(function = "is_ror"))]
    pub id: String,
    /// URI of the organization identifier schema
    ///
    /// Only allowed value: `https://ror.org/`
    #[validate(url, contains(pattern = "https://ror.org"))]
    pub schema_uri: Option<String>,
    /// Organization role
    #[validate(nested)]
    pub role: Vec<OrganizationRole>,
}
/// Organization role
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct OrganizationRole {
    /// Organization role identifier
    pub id: OrganizationRoleType,
    /// URI of the organization role identifier schema
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Date information associated with the organization role
    #[validate(custom(function = "has_start_date"), nested)]
    #[serde(flatten)]
    pub date: Date,
}
/// Metadata schema sub-block that declares the owner of the RAiD (i.e. the organization requesting the RAiD)
///
/// See <https://metadata.raid.org/en/v1.6/core/identifier.html#identifier-owner>
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Owner {
    /// Persistent identifier of the legal entity responsible for the RAiD
    ///
    /// *Default* ROR of the organization requesting the RAiD
    /// ### Example
    /// > `https://ror.org/01qz5mb56` (ORNL)
    #[validate(custom(function = "is_ror"))]
    pub id: String,
    /// URI of the identifier scheme used to identify RAiDs
    /// ### Example
    /// > `https://ror.org/`
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Service point (SP) that requested the RAiD
    /// ### Example
    /// > `20000003`
    /// ### Notes
    /// - RAiD owners can have multiple SPs
    /// - SPs do not need to be legal entities
    /// - List of SPs is maintained by each [`RegistrationAgency`]
    pub service_point: usize,
}
/// Metadata schema sub-block containing free-text place names or descriptions plus associated metadata properties
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Place {
    /// Free text description of one or more geographic locations that are the subject or target of the project or activity; use to specify or describe a geographic location in a manner not covered by [`SpatialCoverage`].id
    /// ### Warning
    /// > Do not duplicate information from [`SpatialCoverage`].id above; do not use for organisational locations (which are derived from the organisation's ROR)
    pub text: Option<String>,
    /// Language of the text
    #[validate(nested)]
    pub language: Option<Language>,
}
/// Metadata schema block containing inputs, outputs, and process documents related to a RAiD plus associated properties
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RelatedObject {
    /// Persistent identifier (PID) of related object
    ///
    /// The object can be any combination of
    /// - input or resource used by a project or activity
    /// - output or product created by a project or activity
    /// - internal process documentation used within a project or activity
    pub id: String,
    /// URI of the relatedObject identifier schema
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Type information of related object
    #[validate(nested)]
    #[serde(rename = "type")]
    pub related_object_type: RelatedObjectIdentifier,
    /// Category information of related object
    #[validate(nested, length(min = 1))]
    pub category: Vec<RelatedObjectCategory>,
}
/// Related object category information
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RelatedObjectCategory {
    /// Related object category identifier
    pub id: ObjectCategoryType,
    /// URI of the category schema used
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Related object identifier
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RelatedObjectIdentifier {
    /// Related object type identifier
    pub id: ObjectType,
    /// URI of the related object type identifier schema
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Metadata schema block containing related RAiDs and qualifying the relationship
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RelatedRaid {
    /// Subsidiary or otherwise related RAiD
    pub id: String,
    /// Related RAiD type
    #[validate(nested)]
    #[serde(rename = "type")]
    pub related_raid_type: RelatedRaidIdentifier,
}
/// Related RAiD identifier
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RelatedRaidIdentifier {
    /// Related RAiD type identifier
    pub id: RelatedRaidType,
    /// URI of the related RAiD type identifier schema
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Metadata schema block containing the RAiD name and associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/identifier.html#identifier-registrationagency>
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RegistrationAgency {
    /// Persistent identifier of the RAiD Registration Agency that minted the RAiD
    ///
    /// *Default* ROR of the RAiD Registration Agency
    #[validate(custom(function = "is_ror"))]
    pub id: String,
    /// URI of the identifier scheme used to identify RAiDs
    /// ### Example
    /// > `https://raid.org/`
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Metadata schema sub-block describing a contributor's scientific or scholarly role on a project using the [CRediT] vocabulary
///
/// See <https://metadata.raid.org/en/v1.6/core/contributors.html#contributor-role>
///
/// [CRediT]: https://credit.niso.org/
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Role {
    /// Contributor role on a project or activity
    #[validate(required)]
    pub id: Option<CreditRole>,
    /// URI of the role schema used
    #[builder(default = "https://credit.niso.org/".to_string())]
    #[validate(url)]
    pub schema_uri: String,
}
/// Metadata schema block containing information about any spatial region(s) or named place(s) targeted by the project
/// ### Note
/// > Part of "extended" metadata that allows some customization by Registration Agencies
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpatialCoverage {
    /// Spatial region or named place that is the subject or target of the project or activity. Repeat this property as necessary to indicate different locations. Do not duplicate organisational locations
    pub id: String,
    /// URI of the geolocation schema used for spatial coverage
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Places of associated spatial coverage
    #[validate(nested)]
    pub place: Vec<Place>,
}
/// Metadata schema block containing the subject area of the RAiD plus associated properties
/// ### Note
/// > Part of "extended" metadata that allows some customization by Registration Agencies
#[derive(Builder, Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Subject {
    /// URI for a subject area or classification code describing the project or activity
    pub id: String,
    /// URI of the subject identifier schema
    #[validate(url)]
    pub schema_uri: Option<String>,
    /// Subject keywords
    #[validate(required, nested)]
    pub keyword: Option<Vec<Keyword>>,
}
/// Metadata schema block containing the title of RAiD and associated properties
///
/// See <https://metadata.raid.org/en/v1.6/core/titles.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Display, Serialize, Deserialize, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[display("{text:?} ({title_type:?})")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Title {
    /// Name or title by which the project or activity is known
    #[validate(required, length(min = 3, max = 100))]
    pub text: Option<String>,
    /// Metadata schema block containing information about the title type
    #[validate(required, nested)]
    #[serde(rename = "type")]
    pub title_type: Option<TitleIdentifier>,
    /// Language of the title
    #[validate(nested)]
    pub language: Option<Language>,
    /// Date the project or activity's title began being used
    /// ### Format
    /// > [ISO 8601] standard date (e.g., `YYYY-MM-DD`)
    ///
    /// [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601
    #[validate(required, custom(function = "is_date"))]
    pub start_date: Option<String>,
    /// Date the project or activity title was changed or stopped being used
    /// ### Format
    /// > [ISO 8601] standard date (e.g., `YYYY-MM-DD`)
    ///
    /// <div class="warning">Only the year is required, month and day are optional</div>
    ///
    /// <div class="warning">Listed as "recommended" (optional) and "required"</div>
    ///
    /// [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601
    #[validate(custom(function = "is_year"))]
    pub end_date: Option<String>,
}
/// Metadata schema block containing information about Traditional Knowledge / Biocultural Labels and Notices
/// ### Note
/// > Part of "extended" metadata that allows some customization by Registration Agencies
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Validate)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TraditionalKnowledgeLabel {
    /// Identifier (URI) linking to a verified source for Traditional Knowledge (TK) or Biocultural (BC) Labels or Notices pertaining to a project or activity
    /// ### Note
    /// > Currently only Local Contexts Hub Projects are allowed as a source for validated TK/BC Labels and Notices.
    pub id: String,
    /// URI of the Traditional Knowledge or Biocultural label identifier schema
    /// ### Note
    /// > Currently only Local Contexts Hub is supported for validated TK/BC Labels and Notices.
    #[validate(url)]
    pub schema_uri: Option<String>,
}
/// Metadata schema block containing information about the title type
#[derive(Builder, Clone, Debug, Serialize, Deserialize, Display, JsonSchema, Validate)]
#[builder(start_fn = init, on(String, into))]
#[display("{id}")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TitleIdentifier {
    /// Title type
    ///
    /// <div class="warning">Only one title should be identified as "Primary"</div>
    pub id: TitleType,
    /// URI of the title type schema
    #[builder(default = "https://vocabulary.raid.org/title.type.schema/376".to_string())]
    #[validate(url)]
    pub schema_uri: String,
}
impl Metadata {
    /// Print research activity identifier (RAiD) metadata schema as JSON schema
    #[cfg(feature = "std")]
    pub fn to_schema() {
        let schema = schema_for!(Metadata);
        match serde_json::to_string_pretty(&schema) {
            | Ok(json) => println!("{}", json),
            | Err(why) => eprintln!("Failed to serialize schema: {}", why),
        }
    }
    /// Read RAiD metadata from a file
    #[cfg(feature = "std")]
    pub fn read(path: PathBuf) -> Result<Metadata, Error> {
        match read_file(path) {
            | Ok(data) => match eserde::json::from_str::<Metadata>(&data) {
                | Ok(value) => Ok(value),
                | Err(errors) => {
                    let details: Vec<String> = errors
                        .iter()
                        .map(|e| format!("{}: {}", e.path().map_or("root".into(), |p| p.to_string()), e.message()))
                        .collect();
                    Err(Error::other(details.join("\n")))
                }
            },
            | Err(why) => {
                let msg = format!("Read RAiD metadata file - {why}");
                error!("=> {} {}", Label::fail(), msg);
                Err(Error::other(msg))
            }
        }
    }
}
impl Contributor {
    fn is_contact(&self) -> bool {
        self.contact
    }
    fn is_leader(&self) -> bool {
        self.leader
    }
}
impl Organization {
    fn is_lead_research_organization(&self) -> bool {
        self.role
            .iter()
            .any(|role| matches!(role.id, OrganizationRoleType::LeadResearchOrganization))
    }
}
#[cfg(feature = "std")]
impl From<ResearchActivity> for Metadata {
    fn from(activity: ResearchActivity) -> Self {
        let default_start_date = current_date();
        let default_end_year = default_start_date.chars().take(4).collect::<String>();
        let raid_id = activity.meta.raid.as_ref().and_then(|raid| raid.first()).cloned().unwrap_or_default();
        let ror_id = activity.meta.ror.as_ref().and_then(|rors| rors.first()).cloned().unwrap_or_default();
        let contributor_id = activity.contact.identifier.clone().filter(|id| is_orcid(id).is_ok()).unwrap_or_default();
        let date = Date {
            start_date: Some(default_start_date.clone()),
            end_date: None,
        };
        let contributor_position = ContributorPosition::init()
            .id(PositionType::PrincipalInvestigator)
            .date(date.clone())
            .build();
        let contributor = Contributor {
            id: Some(contributor_id),
            schema_uri: Some(DEFAULT_ORCID_SCHEMA_URI.to_string()),
            status: Some("active".to_string()),
            status_message: None,
            position: vec![contributor_position],
            leader: true,
            contact: true,
            email: Some(activity.contact.email.clone()),
            role: None,
            uuid: None,
        };
        let org_role = OrganizationRole {
            id: OrganizationRoleType::LeadResearchOrganization,
            schema_uri: None,
            date: date.clone(),
        };
        let organization = Organization {
            id: ror_id.clone(),
            schema_uri: Some(DEFAULT_ROR_SCHEMA_URI.to_string()),
            role: vec![org_role],
        };
        let title = Title {
            text: Some(activity.title.clone()),
            title_type: Some(TitleIdentifier::init().id(TitleType::Primary).build()),
            language: None,
            start_date: Some(default_start_date.clone()),
            end_date: Some(default_end_year.clone()),
        };
        let description = Description {
            text: Some(activity.sections.mission.clone()),
            description_type: Some(DescriptionIdentifier {
                id: DescriptionType::Primary,
                schema_uri: "https://vocabulary.raid.org/description.type.schema/318".to_string(),
            }),
            language: None,
        };
        let identifier = MetadataIdentifier {
            id: Some(raid_id),
            schema_uri: Some("https://raid.org/".to_string()),
            owner: Some(Owner {
                id: ror_id.clone(),
                schema_uri: Some(DEFAULT_ROR_SCHEMA_URI.to_string()),
                service_point: 0,
            }),
            raid_agency_url: Some("https://raid.org/".to_string()),
            registration_agency: Some(RegistrationAgency {
                id: ror_id,
                schema_uri: Some(DEFAULT_ROR_SCHEMA_URI.to_string()),
            }),
            license: Some(License::Single("CC0-1.0".to_string())),
            version: Some(1),
        };
        let access = Access {
            access_type: Some(AccessIdentifier {
                id: AccessType::OpenAccess,
                schema_uri: "https://vocabularies.coar-repositories.org/access_rights/".to_string(),
            }),
            embargo_expiry: None,
            statement: None,
        };
        Metadata {
            access: Some(access),
            contributor: Some(vec![contributor]),
            date: None,
            description: Some(vec![description]),
            metadata: None,
            title: Some(vec![title]),
            identifier: Some(identifier),
            alternate_identifier: None,
            alternate_url: None,
            organization: Some(vec![organization]),
            related_object: None,
            related_raid: None,
            spatial_coverage: None,
            subject: None,
            traditional_knowledge_label: None,
        }
    }
}
fn has_contact(value: &Vec<Contributor>) -> Result<(), ValidationError> {
    has_at_least_one_truthy(
        value.as_slice(),
        Contributor::is_contact,
        "contributors",
        "Mark at least one contributor as contact",
    )
}
fn has_leader(value: &Vec<Contributor>) -> Result<(), ValidationError> {
    has_at_least_one_truthy(
        value.as_slice(),
        Contributor::is_leader,
        "contributors",
        "Mark at least one contributor as leader",
    )
}
fn has_start_date(value: &Date) -> Result<(), ValidationError> {
    match value.start_date.as_ref() {
        | Some(start_date) if !start_date.trim().is_empty() => Ok(()),
        | _ => Err(ValidationError::new("date").with_message("Provide valid start date".into())),
    }
}
fn validate_contributors(value: &Metadata) -> Result<(), ValidationError> {
    match &value.contributor {
        | Some(contributors) => {
            let message = [
                has_contact(contributors)
                    .err()
                    .map(|_| "Mark at least one contributor as contact".to_string()),
                has_leader(contributors)
                    .err()
                    .map(|_| "Mark at least one contributor as leader".to_string()),
            ]
            .into_iter()
            .flatten()
            .collect::<Vec<String>>()
            .join("; ");
            match message.is_empty() {
                | true => Ok(()),
                | false => Err(ValidationError::new("contributors").with_message(message.into())),
            }
        }
        | None => Ok(()),
    }
}
fn validate_organization(value: &Metadata) -> Result<(), ValidationError> {
    match &value.organization {
        | Some(organizations) => {
            let lead_count = organizations
                .iter()
                .filter(|organization| organization.is_lead_research_organization())
                .count();
            let message = if organizations.is_empty() {
                None
            } else if lead_count == 0 {
                Some("Mark one organization as lead research organization".to_string())
            } else if lead_count > 1 {
                Some("Only one organization can be lead research organization".to_string())
            } else {
                None
            };
            match message {
                | Some(value) => Err(ValidationError::new("organization").with_message(value.into())),
                | None => Ok(()),
            }
        }
        | None => Ok(()),
    }
}
fn validate_metadata(value: &Metadata) -> Result<(), ValidationError> {
    let message = [
        validate_contributors(value)
            .err()
            .map(|why| why.message.unwrap_or_else(|| "Invalid contributors".into()).to_string()),
        validate_organization(value)
            .err()
            .map(|why| why.message.unwrap_or_else(|| "Invalid organization".into()).to_string()),
    ]
    .into_iter()
    .flatten()
    .collect::<Vec<String>>()
    .join("; ");
    match message.is_empty() {
        | true => Ok(()),
        | false => Err(ValidationError::new("metadata").with_message(message.into())),
    }
}