-
Notifications
You must be signed in to change notification settings - Fork 13
/
datarequest.py
2690 lines (2056 loc) · 116 KB
/
datarequest.py
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
"""Functions to handle data requests."""
__copyright__ = 'Copyright (c) 2019-2024, Utrecht University'
__license__ = 'GPLv3, see LICENSE'
__author__ = ('Lazlo Westerhof, Jelmer Zondergeld')
import json
import re
import time
from collections import OrderedDict
from datetime import datetime
from enum import Enum
from typing import Dict, List
import jsonschema
from genquery import AS_DICT, AS_LIST, Query, row_iterator
import mail
from util import *
__all__ = ['api_datarequest_roles_get',
'api_datarequest_action_permitted',
'api_datarequest_browse',
'api_datarequest_schema_get',
'api_datarequest_resubmission_id_get',
'api_datarequest_submit',
'api_datarequest_get',
'api_datarequest_attachment_upload_permission',
'api_datarequest_attachment_post_upload_actions',
'api_datarequest_attachments_get',
'api_datarequest_attachments_submit',
'api_datarequest_preliminary_review_submit',
'api_datarequest_preliminary_review_get',
'api_datarequest_datamanager_review_submit',
'api_datarequest_datamanager_review_get',
'api_datarequest_dac_members_get',
'api_datarequest_assignment_submit',
'api_datarequest_assignment_get',
'api_datarequest_review_submit',
'api_datarequest_reviews_get',
'api_datarequest_evaluation_submit',
'api_datarequest_evaluation_get',
'api_datarequest_approval_conditions_get',
'api_datarequest_preregistration_submit',
'api_datarequest_preregistration_get',
'api_datarequest_preregistration_confirm',
'api_datarequest_feedback_get',
'api_datarequest_dta_upload_permission',
'api_datarequest_dta_post_upload_actions',
'api_datarequest_dta_path_get',
'api_datarequest_signed_dta_upload_permission',
'api_datarequest_signed_dta_post_upload_actions',
'api_datarequest_signed_dta_path_get',
'api_datarequest_data_ready',
'rule_datarequest_review_period_expiration_check']
###################################################
# Constants #
###################################################
DATAREQUESTSTATUSATTRNAME = "status"
YODA_PORTAL_FQDN = config.yoda_portal_fqdn
JSON_EXT = ".json"
SCHEMACOLLECTION = constants.UUSYSTEMCOLLECTION + "/datarequest/schemas"
SCHEMA_URI_PREFIX = "https://yoda.uu.nl/datarequest/schemas/"
SCHEMA_VERSION = "youth-1"
SCHEMA = "schema"
UISCHEMA = "uischema"
GROUP_DM = "datarequests-research-datamanagers"
GROUP_DAC = "datarequests-research-data-access-committee"
GROUP_PM = "datarequests-research-project-managers"
DRCOLLECTION = "home/datarequests-research"
PROVENANCE = "provenance"
DATAREQUEST = "datarequest"
ATTACHMENTS_PATHNAME = "attachments"
PR_REVIEW = "preliminary_review"
DM_REVIEW = "datamanager_review"
REVIEW = "review"
ASSIGNMENT = "assignment"
EVALUATION = "evaluation"
APPROVAL_CONDITIONS = "approval_conditions"
PREREGISTRATION = "preregistration"
FEEDBACK = "feedback"
DTA_PATHNAME = "dta"
SIGDTA_PATHNAME = "signed_dta"
###################################################
# Datarequest info functions #
###################################################
# List of valid datarequest types
class type(Enum):
DRAFT = "DRAFT"
REGULAR = "REGULAR"
DAO = "DAO"
# List of valid datarequest statuses
class status(Enum):
IN_SUBMISSION = 'IN_SUBMISSION'
DRAFT = 'DRAFT'
DAO_SUBMITTED = 'DAO_SUBMITTED'
PENDING_ATTACHMENTS = 'PENDING_ATTACHMENTS'
SUBMITTED = 'SUBMITTED'
PRELIMINARY_ACCEPT = 'PRELIMINARY_ACCEPT'
PRELIMINARY_REJECT = 'PRELIMINARY_REJECT'
PRELIMINARY_RESUBMIT = 'PRELIMINARY_RESUBMIT'
DATAMANAGER_ACCEPT = 'DATAMANAGER_ACCEPT'
DATAMANAGER_REJECT = 'DATAMANAGER_REJECT'
DATAMANAGER_RESUBMIT = 'DATAMANAGER_RESUBMIT'
UNDER_REVIEW = 'UNDER_REVIEW'
REJECTED_AFTER_DATAMANAGER_REVIEW = 'REJECTED_AFTER_DATAMANAGER_REVIEW'
RESUBMIT_AFTER_DATAMANAGER_REVIEW = 'RESUBMIT_AFTER_DATAMANAGER_REVIEW'
REVIEWED = 'REVIEWED'
APPROVED = 'APPROVED'
REJECTED = 'REJECTED'
RESUBMIT = 'RESUBMIT'
RESUBMITTED = 'RESUBMITTED'
PREREGISTRATION_SUBMITTED = 'PREREGISTRATION_SUBMITTED'
PREREGISTRATION_CONFIRMED = 'PREREGISTRATION_CONFIRMED'
DAO_APPROVED = 'DAO_APPROVED'
DTA_READY = 'DTA_READY'
DTA_SIGNED = 'DTA_SIGNED'
DATA_READY = 'DATA_READY'
# List of valid datarequest status transitions (source, destination)
status_transitions = [(status(x),
status(y))
for x, y in [('IN_SUBMISSION', 'DRAFT'),
('IN_SUBMISSION', 'PENDING_ATTACHMENTS'),
('IN_SUBMISSION', 'DAO_SUBMITTED'),
('IN_SUBMISSION', 'SUBMITTED'),
('DRAFT', 'PENDING_ATTACHMENTS'),
('DRAFT', 'DAO_SUBMITTED'),
('DRAFT', 'SUBMITTED'),
('PENDING_ATTACHMENTS', 'SUBMITTED'),
('DAO_SUBMITTED', 'DAO_APPROVED'),
('DAO_SUBMITTED', 'REJECTED'),
('DAO_SUBMITTED', 'RESUBMIT'),
('SUBMITTED', 'PRELIMINARY_ACCEPT'),
('SUBMITTED', 'PRELIMINARY_REJECT'),
('SUBMITTED', 'PRELIMINARY_RESUBMIT'),
('PRELIMINARY_ACCEPT', 'DATAMANAGER_ACCEPT'),
('PRELIMINARY_ACCEPT', 'DATAMANAGER_REJECT'),
('PRELIMINARY_ACCEPT', 'DATAMANAGER_RESUBMIT'),
('DATAMANAGER_ACCEPT', 'UNDER_REVIEW'),
('DATAMANAGER_ACCEPT', 'REJECTED_AFTER_DATAMANAGER_REVIEW'),
('DATAMANAGER_ACCEPT', 'RESUBMIT_AFTER_DATAMANAGER_REVIEW'),
('DATAMANAGER_REJECT', 'UNDER_REVIEW'),
('DATAMANAGER_REJECT', 'REJECTED_AFTER_DATAMANAGER_REVIEW'),
('DATAMANAGER_REJECT', 'RESUBMIT_AFTER_DATAMANAGER_REVIEW'),
('DATAMANAGER_RESUBMIT', 'UNDER_REVIEW'),
('DATAMANAGER_RESUBMIT', 'REJECTED_AFTER_DATAMANAGER_REVIEW'),
('DATAMANAGER_RESUBMIT', 'RESUBMIT_AFTER_DATAMANAGER_REVIEW'),
('UNDER_REVIEW', 'REVIEWED'),
('REVIEWED', 'APPROVED'),
('REVIEWED', 'REJECTED'),
('REVIEWED', 'RESUBMIT'),
('RESUBMIT', 'RESUBMITTED'),
('PRELIMINARY_RESUBMIT', 'RESUBMITTED'),
('RESUBMIT_AFTER_DATAMANAGER_REVIEW', 'RESUBMITTED'),
('APPROVED', 'PREREGISTRATION_SUBMITTED'),
('PREREGISTRATION_SUBMITTED', 'PREREGISTRATION_CONFIRMED'),
('PREREGISTRATION_CONFIRMED', 'DTA_READY'),
('DAO_APPROVED', 'DTA_READY'),
('DTA_READY', 'DTA_SIGNED'),
('DTA_SIGNED', 'DATA_READY')]]
def status_transition_allowed(ctx: rule.Context, current_status: status, new_status: status) -> bool:
transition = (current_status, new_status)
return transition in status_transitions
def status_set(ctx: rule.Context, request_id: str, status: status) -> None:
"""Set the status of a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param status: The status to which the data request should be set
"""
metadata_set(ctx, request_id, "status", status.value)
def status_get_from_path(ctx: rule.Context, path: str) -> status:
"""Get the status of a datarequest from a path.
:param ctx: Combined type of a callback and rei struct
:param path: Path of the datarequest collection
:returns: Status of given data request
"""
temp, _ = pathutil.chop(path)
_, request_id = pathutil.chop(temp)
return status_get(ctx, request_id)
def status_get(ctx: rule.Context, request_id: str) -> status:
"""Get the status of a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:raises UUError: Status could not be retrieved
:returns: Status of given data request
"""
# Construct filename and filepath
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
file_name = DATAREQUEST + JSON_EXT
# Retrieve current status
rows = row_iterator(["META_DATA_ATTR_VALUE"],
("COLL_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'status'").format(coll_path, file_name),
AS_DICT, ctx)
if rows.total_rows() == 1:
return status[list(rows)[0]['META_DATA_ATTR_VALUE']]
# If no status is set, set status to IN_SUBMISSION (this is the case for newly submitted data
# requests)
elif rows.total_rows() == 0:
return status.IN_SUBMISSION
else:
raise error.UUError("Could not unambiguously determine the current status for datarequest <{}>".format(request_id))
def type_get(ctx: rule.Context, request_id: str) -> type:
"""Get the type of a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:returns: Type of given data request
"""
# Get datarequest
datarequest = json.loads(datarequest_get(ctx, request_id))
# Determine if draft
if datarequest['draft']:
return type.DRAFT
# Determine type
if datarequest['datarequest']['purpose'] == "Analyses for data assessment only (results will not be published)":
datarequest_type = type.DAO
else:
datarequest_type = type.REGULAR
# Return datarequest type
return datarequest_type
def available_documents_get(ctx: rule.Context, request_id: str, datarequest_type: str, datarequest_status: str) -> List:
# Construct list of existing documents
available_documents = []
if datarequest_type == type.REGULAR.value:
if datarequest_status == status.DRAFT.value:
available_documents = []
elif datarequest_status in [status.SUBMITTED.value, status.PENDING_ATTACHMENTS.value]:
available_documents = [DATAREQUEST]
elif datarequest_status in [status.PRELIMINARY_ACCEPT.value, status.PRELIMINARY_REJECT.value, status.PRELIMINARY_RESUBMIT.value]:
available_documents = [DATAREQUEST, PR_REVIEW]
elif datarequest_status in [status.DATAMANAGER_ACCEPT.value, status.DATAMANAGER_REJECT.value, status.DATAMANAGER_RESUBMIT.value]:
available_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW]
elif datarequest_status in [status.UNDER_REVIEW.value, status.REJECTED_AFTER_DATAMANAGER_REVIEW.value, status.RESUBMIT_AFTER_DATAMANAGER_REVIEW.value]:
available_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT]
elif datarequest_status == status.REVIEWED.value:
available_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT, REVIEW]
elif datarequest_status in [status.APPROVED.value, status.REJECTED.value, status.RESUBMIT.value, status.RESUBMITTED.value]:
available_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT, REVIEW, EVALUATION]
elif datarequest_status in [status.PREREGISTRATION_SUBMITTED.value, status.PREREGISTRATION_CONFIRMED.value, status.DTA_READY.value, status.DTA_SIGNED.value, status.DATA_READY.value]:
available_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT, REVIEW, EVALUATION, PREREGISTRATION]
elif datarequest_type == type.DAO.value:
if datarequest_status == status.DAO_SUBMITTED.value:
available_documents = [DATAREQUEST]
elif datarequest_status in [status.DAO_APPROVED.value, status.DTA_READY.value, status.DTA_SIGNED.value, status.DATA_READY.value]:
available_documents = [DATAREQUEST, EVALUATION]
# Filter out documents which the user is not permitted to read
roles = datarequest_roles_get(ctx, request_id)
if "OWN" in roles:
allowed_documents = [DATAREQUEST, PREREGISTRATION]
elif "PM" in roles:
allowed_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT, REVIEW, EVALUATION, PREREGISTRATION]
elif "DM" in roles:
allowed_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW]
elif "REV" in roles:
allowed_documents = [DATAREQUEST, PR_REVIEW, DM_REVIEW, ASSIGNMENT, REVIEW, EVALUATION]
available_documents = [value for value in available_documents if value in allowed_documents]
return available_documents
###################################################
# Helper functions #
###################################################
def metadata_set(ctx: rule.Context, request_id: str, key: str, value: str) -> None:
"""Set an arbitrary metadata field on a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param key: Key of the metadata field
:param value: Value of the metadata field
"""
# Construct path to the collection of the data request
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
# Add delayed rule to update data request status
response_status = ""
response_status_info = ""
ctx.requestDatarequestMetadataChange(coll_path, key, value, "0", response_status,
response_status_info)
# Trigger the processing of delayed rules
ctx.adminDatarequestActions()
def generate_request_id(ctx: rule.Context) -> int:
coll = "/{}/{}".format(user.zone(ctx), DRCOLLECTION)
max_request_id = 0
# Find highest request ID currently in use
for current_collection in collection.subcollections(ctx, coll, recursive=False):
if str.isdigit(pathutil.basename(current_collection)) and int(pathutil.basename(current_collection)) > max_request_id:
max_request_id = int(pathutil.basename(current_collection))
return max_request_id + 1
@api.make()
def api_datarequest_action_permitted(ctx: rule.Context, request_id: str, roles: List, statuses: List) -> api.Result:
"""Wrapper around datarequest_action_permitted.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param roles: List of permitted roles (possible values: PM, ED, DM, DAC, OWN, REV)
:param statuses: List of permitted current data request statuses or None (check skipped)
:returns: True if permitted, False if not
"""
# Convert statuses to list of status enumeration elements
if statuses is not None:
def get_status(stat: str) -> status:
return status[stat]
statuses = list(map(get_status, statuses))
return datarequest_action_permitted(ctx, request_id, roles, statuses)
def datarequest_action_permitted(ctx: rule.Context, request_id: str, roles: List, statuses: List | None) -> bool:
"""Check if current user and data request status meet specified restrictions.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param roles: List of permitted roles (possible values: PM, ED, DM, DAC, OWN, REV)
:param statuses: List of permitted current data request statuses or None (check skipped)
:returns: True if permitted, False if not
"""
try:
# Force conversion of request_id to string
request_id = str(request_id)
# Check status
if ((statuses is not None) and (status_get(ctx, request_id) not in statuses)):
return api.Error("permission_error", "Action not permitted: illegal status transition.")
# Get current user roles
current_user_roles = []
if user.is_member_of(ctx, GROUP_PM):
current_user_roles.append("PM")
if user.is_member_of(ctx, GROUP_DM):
current_user_roles.append("DM")
if user.is_member_of(ctx, GROUP_DAC):
current_user_roles.append("DAC")
if datarequest_is_owner(ctx, request_id):
current_user_roles.append("OWN")
if datarequest_is_reviewer(ctx, request_id):
current_user_roles.append("REV")
# Check user permissions (i.e. if at least 1 of the user's roles is on the permitted roles
# list)
if len(set(current_user_roles) & set(roles)) < 1:
return api.Error("permission_error", "Action not permitted: insufficient user permissions.")
# If both checks pass, user is permitted to perform action
return True
except error.UUError:
return api.Error("internal_error", "Something went wrong during permission checking.")
@api.make()
def api_datarequest_roles_get(ctx: rule.Context, request_id: str | None = None) -> api.Result:
"""Get roles of invoking user.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request (OWN and REV roles will not be checked
if this parameter is missing)
:returns: List of user roles
"""
return datarequest_roles_get(ctx, request_id)
def datarequest_roles_get(ctx: rule.Context, request_id: str | None = None) -> List:
"""Get roles of invoking user.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request (OWN and REV roles will not be checked
if this parameter is missing)
:returns: List of user roles
"""
roles = []
if user.is_member_of(ctx, GROUP_PM):
roles.append("PM")
if user.is_member_of(ctx, GROUP_DM):
roles.append("DM")
if user.is_member_of(ctx, GROUP_DAC):
roles.append("DAC")
if request_id is not None and datarequest_is_owner(ctx, request_id):
roles.append("OWN")
if request_id is not None and datarequest_is_reviewer(ctx, request_id):
roles.append("REV")
if request_id is not None and datarequest_is_reviewer(ctx, request_id, pending=True):
roles.append("PENREV")
return roles
def datarequest_is_owner(ctx: rule.Context, request_id: str) -> bool:
"""Check if the invoking user is also the owner of a given data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:return: True if user_name is owner of specified data request else False
"""
return datarequest_owner_get(ctx, request_id) == user.name(ctx)
def datarequest_owner_get(ctx: rule.Context, request_id: str) -> str | None:
"""Get the account name (i.e. email address) of the owner of a data request.
:param ctx: Combined type of a callback and a rei struct
:param request_id: Unique identifier of the data request
:return: Account name of data request owner
"""
# Construct path to the data request
file_path = "/{}/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id, DATAREQUEST
+ JSON_EXT)
# Get and return data request owner
try:
return jsonutil.read(ctx, file_path)['owner']
except Exception:
return None
def datarequest_is_reviewer(ctx: rule.Context, request_id: str, pending: bool = False) -> bool:
"""Check if a user is assigned as reviewer to a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param pending: When true, only return pending reviewers
:returns: Boolean indicating if the user is assigned as reviewer
"""
# Force conversion of request_id to string
request_id = str(request_id)
# Get username
username = user.name(ctx)
# Get reviewers
reviewers = datarequest_reviewers_get(ctx, request_id, pending)
# Check if the reviewers list contains the current user
is_reviewer = username in reviewers
# Return the is_reviewer boolean
return is_reviewer
def datarequest_reviewers_get(ctx: rule.Context, request_id: str, pending: bool = False) -> List[str]:
"""Return a list of users assigned as reviewers to a data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param pending: When true, only return pending reviewers
:returns: List of reviewers
"""
# Declare variables needed for retrieving the list of reviewers
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
reviewers = []
# Retrieve list of reviewers (review pending)
rows = row_iterator(["META_DATA_ATTR_VALUE"],
"COLL_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'assignedForReview'".format(coll_path, DATAREQUEST + JSON_EXT),
AS_DICT, ctx)
for row in rows:
reviewers.append(row['META_DATA_ATTR_VALUE'])
# Retrieve list of reviewers (review given)
if not pending:
rows = row_iterator(["META_DATA_ATTR_VALUE"],
"COLL_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'reviewedBy'".format(coll_path, DATAREQUEST + JSON_EXT),
AS_DICT, ctx)
for row in rows:
reviewers.append(row['META_DATA_ATTR_VALUE'])
return reviewers
@api.make()
def api_datarequest_schema_get(ctx: rule.Context, schema_name: str, version: str = SCHEMA_VERSION) -> api.Result:
return datarequest_schema_get(ctx, schema_name, version)
def datarequest_schema_get(ctx: rule.Context, schema_name: str, version: str = SCHEMA_VERSION) -> api.Result:
"""Get schema and UI schema of a datarequest form.
:param ctx: Combined type of a callback and rei struct
:param schema_name: Name of schema
:param version: Version of schema
:returns: Dict with schema and UI schema
"""
# Define paths to schema and uischema
coll_path = "/{}{}/{}".format(user.zone(ctx), SCHEMACOLLECTION, version)
schema_path = "{}/{}/{}".format(coll_path, schema_name, SCHEMA + JSON_EXT)
uischema_path = "{}/{}/{}".format(coll_path, schema_name, UISCHEMA + JSON_EXT)
# Retrieve and read schema and uischema
try:
schema = jsonutil.read(ctx, schema_path)
uischema = jsonutil.read(ctx, uischema_path)
except error.UUFileNotExistError:
return api.Error("file_read_error", "Could not read schema because it doesn't exist.")
# Return JSON with schema and uischema
return {"schema": schema, "uischema": uischema}
@api.make()
def api_datarequest_resubmission_id_get(ctx: rule.Context, request_id: str) -> api.Result:
"""Given a request ID, get the request ID of the associated resubmitted data request.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:returns: String containing the request ID of the resubmitted data request
"""
coll = "/{}/{}".format(user.zone(ctx), DRCOLLECTION)
coll_path = list(Query(ctx, ['COLL_NAME'], "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'previous_request_id' AND META_DATA_ATTR_VALUE in '{}'".format(coll, DATAREQUEST + JSON_EXT, request_id), output=AS_DICT))
if len(coll_path) == 1:
# We're extracting the request ID from the pathname of the collection as that's the most
# straightforward way of getting it, and is also stable.
return coll_path[0]['COLL_NAME'].split("/")[-1]
else:
return api.Error("metadata_read_error", "Not exactly 1 match for when searching for data requests with previous_request_id = {}".format(request_id))
def datarequest_provenance_write(ctx: rule.Context, request_id: str, request_status: status) -> api.Result:
"""Write the timestamp of a status transition to a provenance log.
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:param request_status: Status of which to write a timestamp
:returns: Nothing or API error
"""
# Check if request ID is valid
if re.search(r"^\d+$", request_id) is None:
return api.Error("input_error", "Invalid request ID supplied: {}.".format(request_id))
# Check if status parameter is valid
if request_status not in status:
return api.Error("input_error", "Invalid status parameter supplied: {}.".format(request_status.value))
# Construct path to provenance log
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
provenance_path = "{}/{}".format(coll_path, PROVENANCE + JSON_EXT)
# Get timestamps
timestamps = jsonutil.read(ctx, provenance_path)
# Check if there isn't already a timestamp for the given status
if request_status.value in timestamps:
return api.Error("input_error", "Status ({}) has already been timestamped.".format(request_status.value))
# Add timestamp
current_time = str(datetime.now().strftime('%s'))
timestamps[request_status.value] = current_time
# Write timestamp to provenance log
try:
jsonutil.write(ctx, provenance_path, timestamps)
except error.UUError as e:
return api.Error("write_error", "Could not write timestamp to provenance log: {}.".format(e))
def datarequest_data_valid(ctx: rule.Context, data: Dict, schema_name: str | None = None, schema: str | None = None) -> bool:
"""Check if form data contains no errors
Default mode of operation is to provide schema data and the schema name of the schema against
which to validate the data.
A second mode of operation is available in which no schema name is provided, but in which the
schema is provided directly (as JSON).
This second mode of operation is necessary when the default schema has been altered. E.g. for
the assignment form, a list of DAC members to which a data request can be assigned for review is
fetched dynamically when the form is rendered. To validate schema data generated using this
schema, we need to reconstruct the schema by mutating it exactly like we did when we rendered it
(i.e. also dynamically fetch the list of DAC members and insert them into the schema).
:param ctx: Combined type of a callback and rei struct
:param data: The form data to validate
:param schema_name: Name of JSON schema against which to validate the form data
:param schema: JSON schema against which to validate the form data (in case a default
schema doesn't suffice)
:returns: Boolean indicating if datarequest is valid
"""
# Check if a schema is specified
if not (schema_name or schema):
return api.Error("validation_error",
"No schema specified (neither a schema name nor a schema was given).")
try:
schema = datarequest_schema_get(ctx, schema_name)['schema'] if schema_name else schema
validator = jsonschema.Draft7Validator(schema)
errors = list(validator.iter_errors(data))
return len(errors) == 0
except error.UUJsonValidationError:
# File may be missing or not valid JSON
return False
def cc_email_addresses_get(contact_object: Dict) -> str | None:
try:
cc = contact_object['cc_email_addresses']
return cc.replace(' ', '')
except Exception:
return None
@rule.make(inputs=[], outputs=[0, 1])
def rule_datarequest_review_period_expiration_check(ctx: rule.Context) -> None:
coll = "/{}/{}".format(user.zone(ctx), DRCOLLECTION)
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'endOfReviewPeriod' AND META_DATA_ATTR_VALUE < '{}' AND META_DATA_ATTR_NAME = 'status' AND META_DATA_ATTR_VALUE = 'UNDER_REVIEW'".format(coll, DATAREQUEST + JSON_EXT, int(time.time()))
ccols = ['COLL_NAME']
qcoll = Query(ctx, ccols, criteria, output=AS_DICT)
if len(list(qcoll)) > 0:
datarequest_process_expired_review_periods(ctx, [result['COLL_NAME'].split('/')[-1] for result in list(qcoll)])
def datarequest_sync_avus(ctx: rule.Context, request_id: str) -> None:
"""Sometimes data requests are manually edited in place (e.g. for small
textual changes). This in-place editing is done on the datarequest.json
file.
The contents of this file are set as AVUs on the file itself. This is only
done once, at the submission of the datarequest. Therefore, to keep the AVUs
of datarequest.json files accurate after a manual edit of the data request,
we need to resynchronize the AVUs with the updated contents of the
datarequest.json.
This function does exactly that. It takes exactly 1 numeric argument (the
request ID of the data request).
:param ctx: Combined type of a callback and rei struct
:param request_id: Unique identifier of the data request
:raises UUError: request_id is not a digit.
"""
# Confirm that request_id is a digit
if not request_id.isdigit():
raise error.UUError('request_id is not a digit.')
# Get request data
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
file_path = "{}/{}".format(coll_path, DATAREQUEST + JSON_EXT)
data = datarequest_get(ctx, request_id)
# Re-set the AVUs
jsonutil.set_on_object(ctx, file_path, "data_object", "root", data)
###################################################
# Datarequest workflow API calls #
###################################################
@api.make()
def api_datarequest_browse(ctx: rule.Context,
sort_on: str = 'name',
sort_order: str = 'asc',
offset: int = 0,
limit: int = 10,
archived: bool = False,
dacrequests: bool = True) -> api.Result:
"""Get paginated datarequests, including size/modify date information.
:param ctx: Combined type of a callback and rei struct
:param sort_on: Column to sort on ('name', 'modified')
:param sort_order: Column sort order ('asc' or 'desc')
:param offset: Offset to start browsing from
:param limit: Limit number of results
:param archived: If true, show archived (i.e. rejected) data requests only. If false, only
show non-archived data requests
:param dacrequests: If true, show a DAC member's own data requests (instead of data requests to
be reviewed
:returns: Dict with paginated datarequests
"""
# Convert parameters that couldn't be passed as actual boolean values to booleans
archived = archived == "True"
dacrequests = dacrequests == "True"
dac_member = user.is_member_of(ctx, GROUP_DAC)
coll = "/{}/{}".format(user.zone(ctx), DRCOLLECTION)
def transform(row: Dict) -> Dict:
# Remove ORDER_BY etc. wrappers from column names.
x = {re.sub(r'.*\((.*)\)', '\\1', k): v for k, v in row.items()}
return {'id': x['COLL_NAME'].split('/')[-1],
'name': x['COLL_OWNER_NAME'],
'create_time': int(x['COLL_CREATE_TIME']),
'status': x['META_DATA_ATTR_VALUE']}
def transform_title(row: Dict) -> Dict:
# Remove ORDER_BY etc. wrappers from column names.
x = {re.sub(r'.*\((.*)\)', '\\1', k): v for k, v in row.items()}
return {'id': x['COLL_NAME'].split('/')[-1],
'title': x['META_DATA_ATTR_VALUE']}
def transform_status(row: Dict) -> Dict:
# Remove ORDER_BY etc. wrappers from column names.
x = {re.sub(r'.*\((.*)\)', '\\1', k): v for k, v in row.items()}
return {'id': x['COLL_NAME'].split('/')[-1],
'status': x['META_DATA_ATTR_VALUE']}
if sort_on == 'modified':
# FIXME: Sorting on modify date is borked: There appears to be no
# reliable way to filter out replicas this way - multiple entries for
# the same file may be returned when replication takes place on a
# minute boundary, for example.
# We would want to take the max modify time *per* data name.
# (or not? replication may take place a long time after a modification,
# resulting in a 'too new' date)
ccols = ['COLL_NAME', 'ORDER(COLL_CREATE_TIME)', "COLL_OWNER_NAME", "META_DATA_ATTR_VALUE"]
else:
ccols = ['ORDER(COLL_NAME)', 'COLL_CREATE_TIME', "COLL_OWNER_NAME", "META_DATA_ATTR_VALUE"]
if sort_order == 'desc':
ccols = [x.replace('ORDER(', 'ORDER_DESC(') for x in ccols]
# Build query
#
# Set filter
#
# a) Normal case
if not dac_member and not archived:
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'status' AND META_DATA_ATTR_VALUE != 'PRELIMINARY_REJECT' && != 'REJECTED_AFTER_DATAMANAGER_REVIEW' && != 'REJECTED' && != 'RESUBMITTED' && != 'DATA_READY'".format(coll, DATAREQUEST + JSON_EXT)
# b) Archive case
elif not dac_member and archived:
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'status' AND META_DATA_ATTR_VALUE = 'PRELIMINARY_REJECT' || = 'REJECTED_AFTER_DATAMANAGER_REVIEW' || = 'REJECTED' || = 'RESUBMITTED' || = 'DATA_READY'".format(coll, DATAREQUEST + JSON_EXT)
# c1) DAC reviewable requests case
elif dac_member and not dacrequests and not archived:
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'assignedForReview' AND META_DATA_ATTR_VALUE in '{}'".format(coll, DATAREQUEST + JSON_EXT, user.name(ctx))
# c2) DAC own requests case
elif dac_member and dacrequests and not archived:
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'owner' AND META_DATA_ATTR_VALUE in '{}'".format(coll, DATAREQUEST + JSON_EXT, user.name(ctx))
# c3) DAC reviewed requests
elif dac_member and not dacrequests and archived:
criteria = "COLL_PARENT_NAME = '{}' AND DATA_NAME = '{}' AND META_DATA_ATTR_NAME = 'reviewedBy' AND META_DATA_ATTR_VALUE in '{}'".format(coll, DATAREQUEST + JSON_EXT, user.name(ctx))
# Execute query
qcoll = Query(ctx, ccols, criteria, offset=offset, limit=limit, output=AS_DICT)
if len(list(qcoll)) > 0:
qcoll_title = Query(ctx, ccols, "META_DATA_ATTR_NAME = 'title' AND COLL_PARENT_NAME = '{}'".format(coll), offset=offset, limit=limit, output=AS_DICT)
qcoll_status = Query(ctx, ccols, "META_DATA_ATTR_NAME = 'status' AND COLL_PARENT_NAME = '{}'".format(coll), offset=offset, limit=limit, output=AS_DICT)
else:
return OrderedDict([('total', 0), ('items', [])])
# Merge datarequest title and status into results.
colls = list(map(transform, list(qcoll)))
colls_title = list(map(transform_title, list(qcoll_title)))
colls_status = list(map(transform_status, list(qcoll_status)))
for datarequest in colls:
for datarequest_title in colls_title:
if datarequest_title['id'] == datarequest['id']:
datarequest['title'] = datarequest_title['title']
break
for datarequest_status in colls_status:
if datarequest_status['id'] == datarequest['id']:
datarequest['status'] = datarequest_status['status']
break
# No results at all? Make sure the collection actually exists.
if len(colls) == 0 and not collection.exists(ctx, coll):
return api.Error('nonexistent', 'The given path does not exist')
# (checking this beforehand would waste a query in the most common situation)
return OrderedDict([('total', qcoll.total_rows()), ('items', colls)])
def datarequest_process_expired_review_periods(ctx: rule.Context, request_ids: List) -> None:
"""Process expired review periods by setting their status to REVIEWED.
:param ctx: Combined type of a callback and rei struct
:param request_ids: List of unique data request identifiers
"""
for request_id in request_ids:
status_set(ctx, request_id, status.REVIEWED)
def file_write_and_lock(ctx: rule.Context, coll_path: str, filename: str, data: Dict, readers: List[str]) -> None:
"""Grant temporary write permission and write file to disk.
:param ctx: Combined type of a callback and rei struct
:param coll_path: Path to collection of file
:param filename: Name of file
:param data: The data to be written to disk
:param readers: List of user names that should be given read access to the file
"""
file_path = "{}/{}".format(coll_path, filename)
# Grant temporary write permission
ctx.adminTempWritePermission(coll_path, "grant")
# Write
jsonutil.write(ctx, file_path, data)
# Grant read permission to readers
for reader in readers:
msi.set_acl(ctx, "default", "read", reader, file_path)
# Revoke temporary write permission (unless read permissions were set on the invoking user)
if user.full_name(ctx) not in readers:
msi.set_acl(ctx, "default", "null", user.full_name(ctx), file_path)
# If invoking user is request owner, set read permission for this user on the collection again,
# else revoke individual user permissions on collection entirely (invoking users will still have
# appropriate permissions through group membership, e.g. the project managers group)
permission = "read" if user.name(ctx) == datarequest_owner_get(ctx, coll_path.split('/')[-1]) \
else "revoke"
ctx.adminTempWritePermission(coll_path, permission)
@api.make()
def api_datarequest_submit(ctx: rule.Context, data: Dict, draft: bool, draft_request_id: str | None = None) -> api.Result:
"""Persist a data request to disk.
:param ctx: Combined type of a callback and rei struct
:param data: Contents of the data request
:param draft: Boolean specifying whether the data request should be saved as draft
:param draft_request_id: Unique identifier of the draft data request
:returns: API status
"""
# Set request owner in form data
data['owner'] = user.name(ctx)
# Set draft flag in form data
data['draft'] = draft
# Set schema ID
data['links'] = [OrderedDict([
['rel', 'describedby'],
['href', SCHEMA_URI_PREFIX + SCHEMA_VERSION + '/datarequest/' + SCHEMA + '.json']
])]
# Set submission date in form data
data['submission_timestamp'] = str(datetime.now().strftime('%s'))
# Validate data against schema
if not draft and not datarequest_data_valid(ctx, data, DATAREQUEST):
return api.Error("validation_fail",
"{} form data did not pass validation against its schema.".format(DATAREQUEST))
# Permission check
if (user.is_member_of(ctx, GROUP_PM) or user.is_member_of(ctx, GROUP_DM)):
return api.Error("permission_error", "Action not permitted.")
# If we're not working with a draft, generate a new request ID.
if draft_request_id:
request_id = draft_request_id
else:
# Generate request ID and construct data request collection path.
request_id = str(generate_request_id(ctx))
# Construct data request collection and file path.
coll_path = "/{}/{}/{}".format(user.zone(ctx), DRCOLLECTION, request_id)
file_path = "{}/{}".format(coll_path, DATAREQUEST + JSON_EXT)
# If we're not working with a draft, initialize the data request collection
if not draft_request_id:
# Create collections
try:
dta_path = "{}/{}".format(coll_path, DTA_PATHNAME)
sigdta_path = "{}/{}".format(coll_path, SIGDTA_PATHNAME)
attachments_path = "{}/{}".format(coll_path, ATTACHMENTS_PATHNAME)
collection.create(ctx, coll_path)
collection.create(ctx, attachments_path)
collection.create(ctx, dta_path)
collection.create(ctx, sigdta_path)
except error.UUError as e:
return api.Error("create_collection_fail", "Could not create collection path: {}.".format(e))
# Grant permissions on collections
msi.set_acl(ctx, "default", "read", GROUP_DM, coll_path)
msi.set_acl(ctx, "default", "read", GROUP_DAC, coll_path)
msi.set_acl(ctx, "default", "read", GROUP_PM, coll_path)
msi.set_acl(ctx, "default", "own", "rods", coll_path)
msi.set_acl(ctx, "default", "read", GROUP_DM, attachments_path)
msi.set_acl(ctx, "default", "read", GROUP_DAC, attachments_path)
msi.set_acl(ctx, "default", "read", GROUP_PM, attachments_path)
msi.set_acl(ctx, "default", "own", "rods", attachments_path)
msi.set_acl(ctx, "default", "read", user.full_name(ctx), attachments_path)
msi.set_acl(ctx, "default", "read", GROUP_PM, dta_path)
msi.set_acl(ctx, "default", "read", GROUP_DM, dta_path)
msi.set_acl(ctx, "default", "read", user.full_name(ctx), dta_path)
msi.set_acl(ctx, "default", "own", "rods", dta_path)
msi.set_acl(ctx, "default", "read", GROUP_PM, sigdta_path)
msi.set_acl(ctx, "default", "read", GROUP_DM, sigdta_path)
msi.set_acl(ctx, "default", "read", user.full_name(ctx), sigdta_path)
msi.set_acl(ctx, "default", "own", "rods", sigdta_path)
# Create provenance log
provenance_path = "{}/{}".format(coll_path, PROVENANCE + JSON_EXT)
jsonutil.write(ctx, provenance_path, {})
# Write data request
jsonutil.write(ctx, file_path, data)
# Apply initial permission restrictions to researcher
msi.set_acl(ctx, "default", "null", user.full_name(ctx), provenance_path)
msi.set_acl(ctx, "default", "read", "public", coll_path)
# Write form data to disk
try:
jsonutil.write(ctx, file_path, data)
except error.UUError:
return api.Error('write_error', 'Could not write datarequest to disk.')
# Set the proposal fields as AVUs on the proposal JSON file
jsonutil.set_on_object(ctx, file_path, "data_object", "root", json.dumps(data))
# If draft, set status
if draft:
status_set(ctx, request_id, status.DRAFT)
# If new draft, return request ID of draft data request
if not draft_request_id:
return {"requestId": request_id}
# If update of existing draft, return nothing
else:
return