/
views.py
3840 lines (3353 loc) · 155 KB
/
views.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
"""Application views."""
import csv
import itertools
import json
import math
import mimetypes
import os
import secrets
import traceback
from datetime import datetime
from io import BytesIO
import requests
import tablib
import yaml
import orcid_api_v3 as v3
from flask import (Response, abort, flash, jsonify, redirect, render_template, request, send_file,
send_from_directory, stream_with_context, url_for)
from flask_admin._compat import csv_encode
from flask_admin.actions import action
from flask_admin.babel import gettext
from flask_admin.base import expose
from flask_admin.contrib.peewee import ModelView, filters
from flask_admin.contrib.peewee.form import CustomModelConverter
from flask_admin.contrib.peewee.view import save_inline
from flask_admin.form import SecureForm, rules
from flask_admin.helpers import get_redirect_target
from flask_admin.model import BaseModelView, typefmt
from flask_login import current_user, login_required
from flask_rq2.job import FlaskJob
from jinja2 import Markup
from orcid_api.rest import ApiException
from playhouse.shortcuts import model_to_dict
from peewee import SQL
from werkzeug.utils import secure_filename
from wtforms.fields import BooleanField
from urllib.parse import parse_qs, urlparse
from wtforms import validators
from . import SENTRY_DSN, admin, app, cache, limiter, models, orcid_client, rq, utils
from .apis import yamlfy
from .forms import (AddressForm, ApplicationFrom, BitmapMultipleValueField, CredentialForm, EmailTemplateForm,
ExternalIdentifierForm, FileUploadForm, FundingForm, GroupIdForm, LogoForm, OrgRegistrationForm,
OtherNameKeywordForm, PartialDateField, PeerReviewForm, ProfileSyncForm,
RecordForm, ResearcherUrlForm, UserInvitationForm, WebhookForm, WorkForm,
validate_orcid_id_field)
from .login_provider import roles_required
from .models import (JOIN, Affiliation, AffiliationRecord, AffiliationExternalId, CharField,
Client, Delegate, ExternalId, FixedCharField, File, FundingContributor,
FundingInvitee, FundingRecord, Grant, GroupIdRecord, ModelException,
NestedDict, OtherIdRecord, OrcidApiCall, OrcidToken, Organisation, OrgInfo,
OrgInvitation, PartialDate, PropertyRecord, PeerReviewExternalId,
PeerReviewInvitee, PeerReviewRecord, Role, Task, TaskType, TextField, Token,
Url, User, UserInvitation, UserOrg, UserOrgAffiliation, WorkContributor,
WorkExternalId, WorkInvitee, WorkRecord, db)
# NB! Should be disabled in production
from .pyinfo import info
from .utils import get_next_url, read_uploaded_file, send_user_invitation
HEADERS = {"Accept": "application/vnd.orcid+json", "Content-type": "application/vnd.orcid+json"}
ORCID_BASE_URL = app.config["ORCID_BASE_URL"]
@app.errorhandler(401)
def unauthorized(e):
"""Handle Unauthorized (401)."""
_next = get_next_url()
if _next:
flash(
"You have not been authenticated, or do not have the necessary permissions to access this page",
"danger")
return redirect(_next)
return render_template("401.html"), 401
@app.errorhandler(403)
def forbidden(e):
"""Handle Forbidden (403)."""
_next = get_next_url()
if _next:
flash("Page Not Found", "danger")
flash(
"You might not have the necessary permissions to access this page.",
"danger")
return redirect(_next)
return render_template("403.html"), 403
@app.errorhandler(404)
def page_not_found(e):
"""Handle nonexistin pages."""
_next = get_next_url()
if _next:
flash("Page Not Found", "danger")
return redirect(_next)
return render_template("404.html"), 404
@app.errorhandler(500)
def internal_error(error):
"""Handle internal error."""
trace = traceback.format_exc()
if SENTRY_DSN:
from sentry_sdk import last_event_id
return render_template(
"500.html",
trace=trace,
error_message=str(error),
sentry_event_id=last_event_id())
else:
return render_template("500.html", trace=trace, error_message=str(error))
@app.route("/favicon.ico")
def favicon():
"""Support for the "favicon" legacy: favicon location in the root directory."""
return send_from_directory(
os.path.join(app.root_path, "static", "images"),
"favicon.ico",
mimetype="image/vnd.microsoft.icon")
@app.route("/status")
@limiter.limit("30/minute")
def status():
"""Check the application health status attempting to connect to the DB.
NB! This entry point should be protected and accessible
only form the application monitoring servers.
"""
try:
now = db.execute_sql("SELECT now();").fetchone()[0]
return jsonify({
"status": "Connection successful.",
"db-timestamp": now.isoformat(),
})
except Exception as ex:
return jsonify({
"status": "Error",
"message": str(ex),
}), 503 # Service Unavailable
@app.route("/pyinfo/<message>")
@app.route("/pyinfo")
@roles_required(Role.SUPERUSER)
def pyinfo(message=None):
"""Show Python and runtime environment and settings or test exception handling."""
if message:
raise Exception(message)
return render_template("pyinfo.html", **info)
@app.route("/u/<short_id>")
def short_url(short_id):
"""Redirect to the full URL."""
try:
u = Url.get(short_id=short_id)
if request.args:
return redirect(utils.append_qs(u.url, **request.args))
return redirect(u.url)
except Url.DoesNotExist:
abort(404)
def orcid_link_formatter(view, context, model, name):
"""Format ORCID ID for ModelViews."""
if not model.orcid:
return ""
return Markup(f'<a href="{ORCID_BASE_URL}{model.orcid}" target="_blank">{model.orcid}</a>')
class AppCustomModelConverter(CustomModelConverter):
"""Customized field mapping to revove the extra validator.
This is a workaround for https://github.com/coleifer/wtf-peewee/issues/48.
TODO: remove it as soon as the issue gets resoved.
"""
def convert(self, model, field, field_args):
"""Remove the 'Required' validator if the model field is optional."""
fi = super().convert(model, field, field_args)
if field.null and field.choices:
for v in fi.field.kwargs.get("validators", []):
if isinstance(v, validators.Required):
fi.field.kwargs["validators"].remove(v)
break
return fi
class AppModelView(ModelView):
"""ModelView customization."""
roles = {1: "Superuser", 2: "Administrator", 4: "Researcher", 8: "Technical Contact"}
column_editable_list = ["name", "is_active", "email", "role", "city", "region", "value", "url", "display_index"]
roles_required = Role.SUPERUSER
export_types = [
"csv",
"xls",
"tsv",
"yaml",
"json",
"xlsx",
"ods",
"html",
]
form_args = dict(
roles=dict(choices=roles.items()),
email=dict(validators=[validators.email()]),
orcid=dict(validators=[validate_orcid_id_field]))
if app.config["ENV"] not in ["dev", "test", "dev0", ] and not app.debug:
form_base_class = SecureForm
column_formatters = dict(
roles=lambda v, c, m, p: ", ".join(n for r, n in v.roles.items() if r & m.roles),
orcid=orcid_link_formatter)
column_default_sort = ("id", True)
column_labels = dict(org="Organisation", orcid="ORCID iD")
column_type_formatters = dict(typefmt.BASE_FORMATTERS)
column_type_formatters.update({datetime: lambda view, value: isodate(value)})
column_type_formatters_export = dict(typefmt.EXPORT_FORMATTERS)
column_type_formatters_export.update({PartialDate: lambda view, value: str(value)})
column_formatters_export = dict(orcid=lambda v, c, m, p: m.orcid)
column_exclude_list = (
"updated_at",
"updated_by",
)
form_overrides = dict(start_date=PartialDateField,
end_date=PartialDateField,
proposal_start_date=PartialDateField,
proposal_end_date=PartialDateField)
form_widget_args = {c: {"readonly": True} for c in column_exclude_list}
form_excluded_columns = ["created_at", "updated_at", "created_by", "updated_by"]
model_form_converter = AppCustomModelConverter
column_display_pk = False
def __init__(self, model=None, *args, **kwargs):
"""Pick the model based on the ModelView class name assuming it is ModelClass + "Admin"."""
if model is None:
if hasattr(self, "model"):
model = self.model
else:
model_class_name = self.__class__.__name__.replace("Admin", '')
model = globals().get(model_class_name)
if model is None:
if model_class_name not in dir(models):
raise Exception(f"Model class {model_class_name} doesn't exit.")
model = models.__dict__.get(model_class_name)
super().__init__(model, *args, **kwargs)
# TODO: remove when it gets merged into the upstream repo (it's a workaround to make
# joins LEFT OUTER)
def _handle_join(self, query, field, joins):
if field.model != self.model:
model_name = field.model.__name__
foreign_keys, _ = self.model._meta.get_rel_for_model(field.model)
if model_name not in joins:
# TODO: find a simple way of getting to the right joining forein key
if len(foreign_keys) > 1:
query = query.join(field.model, JOIN.LEFT_OUTER, on=foreign_keys[0])
else:
query = query.join(field.model, JOIN.LEFT_OUTER)
joins.add(model_name)
return query
def get_one(self, rec_id):
"""Handle missing data."""
try:
return super().get_one(rec_id)
except self.model.DoesNotExist:
flash(f"The record with given ID: {rec_id} doesn't exist or it has been deleted.", "danger")
abort(404)
def init_search(self):
"""Include linked columns in the search if they are defined with 'liked_table.column'."""
if self.column_searchable_list:
for p in self.column_searchable_list:
if isinstance(p, str):
if "." in p:
m, p = p.split('.')
m = getattr(self.model, m).rel_model
p = getattr(m, p)
else:
p = getattr(self.model, p)
# Check type
if not isinstance(p, (
CharField,
TextField,
)):
raise Exception(
f'Can only search on text columns. Failed to setup search for "{p}"')
self._search_fields.append(p)
return bool(self._search_fields)
def is_accessible(self):
"""Verify if the view is accessible for the current user."""
if not current_user.is_active or not current_user.is_authenticated:
return False
if current_user.has_role(self.roles_required):
return True
return False
def inaccessible_callback(self, name, **kwargs):
"""Handle access denial. Redirect to login page if user doesn"t have access."""
return redirect(url_for("index", next=request.url))
def get_query(self):
"""Add URL query to the data select for foreign key and select data that user has access to."""
query = super().get_query()
if current_user and not current_user.has_role(Role.SUPERUSER) and current_user.has_role(
Role.ADMIN):
# Show only rows related to the current organisation the user is admin for.
# Skip this part for SUPERUSER.
column_names = [c.column_name for c in self.model._meta.fields.values()]
if "org_id" in column_names or "organisation_id" in column_names:
if "org_id" in column_names:
query = query.where(self.model.org_id == current_user.organisation.id)
else:
query = query.where(self.model.organisation_id == current_user.organisation.id)
if request.args and any(a.endswith("_id") for a in request.args):
for f in self.model._meta.fields.values():
if f.column_name.endswith("_id") and f.column_name in request.args:
query = query.where(f == int(request.args[f.column_name]))
return query
def _get_list_extra_args(self):
"""Workaround for https://github.com/flask-admin/flask-admin/issues/1512."""
view_args = super()._get_list_extra_args()
extra_args = {
k: v
for k, v in request.args.items()
if k not in (
"page",
"page_size",
"sort",
"desc",
"search",
) and not k.startswith("flt")
}
view_args.extra_args = extra_args
return view_args
class AuditLogModelView(AppModelView):
"""Audit Log model view."""
can_edit = False
can_delete = False
can_create = False
can_view_details = False
column_default_sort = [("ts", True), ("id", True)]
def __init__(self, model, *args, **kwargs):
"""Set up the search list."""
self.column_searchable_list = [
f for f in model._meta.fields.values() if isinstance(f, (CharField, FixedCharField, TextField))
]
self.column_filters = [
filters.DateBetweenFilter(column=model.ts, name="Time-stamp"),
filters.FilterEqual(
column=model.op,
options=[("U", "Updated"), ("D", "Deleted")],
name="Operation"),
]
super().__init__(model, *args, **kwargs)
class MailLogAdmin(AppModelView):
"""Mail Log model view."""
can_edit = False
can_delete = False
can_create = False
can_view_details = True
class UserAdmin(AppModelView):
"""User model view."""
roles = {1: "Superuser", 2: "Administrator", 4: "Researcher", 8: "Technical Contact"}
edit_template = "admin/user_edit.html"
form_extra_fields = dict(is_superuser=BooleanField("Is Superuser"))
form_excluded_columns = (
"roles",
"created_at",
"updated_at",
"created_by",
"updated_by",
)
column_exclude_list = (
"password",
"username",
"first_name",
"last_name",
)
column_searchable_list = (
"name",
"orcid",
"email",
"eppn",
"organisation.name",
)
form_overrides = dict(roles=BitmapMultipleValueField)
form_ajax_refs = {
"organisation": {
"fields": (Organisation.name, "name")
},
}
can_export = True
class OrganisationAdmin(AppModelView):
"""Organisation model view."""
column_formatters = {
"logo":
lambda v, c, m, p: Markup(
'<img style="max-height: 100px; max-width: 100px;" src="'
f"""{url_for('logo_image', token=m.logo.token)}" alt="the logo of {m.name}">""") if m.logo else ''
}
column_exclude_list = (
"orcid_client_id",
"orcid_secret",
"created_at",
"updated_at",
"created_by",
"updated_by",
"email_template",
"email_template_enabled",
)
form_excluded_columns = AppModelView.form_excluded_columns[:]
form_excluded_columns.append("logo")
column_searchable_list = (
"name",
"tuakiri_name",
"city",
)
form_ajax_refs = {
"tech_contact": {
"fields": (User.name, User.email),
"page_size": 5
},
}
edit_template = "admin/organisation_edit.html"
form_widget_args = AppModelView.form_widget_args
form_widget_args["api_credentials_requested_at"] = {"readonly": True}
form_widget_args["api_credentials_entered_at"] = {"readonly": True}
def update_model(self, form, model):
"""Handle change of the technical contact."""
# Technical contact changed:
if form.tech_contact.data and form.tech_contact.data.id != model.tech_contact_id:
# Revoke the TECHNICAL role if thre is no org the user is tech.contact for.
if model.tech_contact and model.tech_contact.has_role(
Role.TECHNICAL) and not Organisation.select().where(
Organisation.tech_contact_id == model.tech_contact_id,
Organisation.id != model.id).exists():
app.logger.info(r"Revoked TECHNICAL from {model.tech_contact}")
model.tech_contact.roles &= ~Role.TECHNICAL
model.tech_contact.save()
return super().update_model(form, model)
class OrgInfoAdmin(AppModelView):
"""OrgInfo model view."""
can_export = True
column_searchable_list = (
"name",
"tuakiri_name",
"city",
"first_name",
"last_name",
"email",
)
form_rules = [
rules.FieldSet(["name", "tuakiri_name"], "Naming"),
rules.FieldSet(["title", "first_name", "last_name", "role", "email", "phone", "is_public"],
"Technical Contact"),
rules.FieldSet(["country", "city"], "Address"),
rules.FieldSet(["disambiguated_id", "disambiguation_source"], "Disambiguation Data"),
]
@action("invite", "Register Organisation",
"Are you sure you want to register selected organisations?")
def action_invite(self, ids):
"""Batch registration of organisations."""
count = 0
for oi in OrgInfo.select().where(OrgInfo.id.in_(ids)):
try:
register_org(
org_name=oi.name,
email=oi.email,
tech_contact=True,
via_orcid=(False if oi.tuakiri_name else True),
first_name=oi.first_name,
last_name=oi.last_name,
city=oi.city,
country=oi.country,
course_or_role=oi.role,
disambiguated_id=oi.disambiguated_id,
disambiguation_source=oi.disambiguation_source)
count += 1
except Exception as ex:
flash(f"Failed to send an invitation to {oi.email}: {ex}")
app.logger.exception(f"Failed to send registration invitation to {oi.email}.")
flash("%d invitations were sent successfully." % count)
class OrcidTokenAdmin(AppModelView):
"""ORCID token model view."""
column_searchable_list = (
"user.name",
"user.email",
"org.name",
)
can_export = True
can_create = False
class OrcidApiCallAmin(AppModelView):
"""ORCID API calls."""
column_list = [
"method", "url", "query_params", "body", "status", "put_code", "response",
"response_time_ms"
]
column_default_sort = ("id", True)
can_export = True
can_edit = False
can_delete = False
can_create = False
can_view_details = True
column_searchable_list = (
"url",
"body",
"response",
"user.name",
)
column_formatters = AppModelView.column_formatters
column_formatters_detail = dict()
@staticmethod
def truncate_value(v, c, m, p):
"""Truncate very long strings."""
value = getattr(m, p)
return value[:100] + " ..." if value and len(value) > 100 else value
OrcidApiCallAmin.column_formatters.update(dict(
body=OrcidApiCallAmin.truncate_value, response=OrcidApiCallAmin.truncate_value))
class UserInvitationAdmin(AppModelView):
"""User Invitations."""
can_export = True
can_edit = False
can_delete = False
can_create = False
column_searchable_list = (
"email",
"organisation",
"department",
"first_name",
"last_name",
"token",
"inviter.name",
)
class OrgInvitationAdmin(AppModelView):
"""User Invitations."""
can_export = True
can_edit = False
can_delete = False
can_create = False
column_searchable_list = (
"email",
"org.name",
"token",
"inviter.name",
)
class UserOrgAmin(AppModelView):
"""User Organisations."""
column_searchable_list = (
"user.email",
"org.name",
)
class TaskAdmin(AppModelView):
"""Task model view."""
roles_required = Role.SUPERUSER | Role.ADMIN
list_template = "view_tasks.html"
can_edit = False
can_create = False
can_delete = True
column_searchable_list = [
"filename", "created_by.email", "created_by.name", "created_by.first_name",
"created_by.last_name", "org.name"
]
column_list = [
"task_type", "filename", "created_at", "org", "completed_at", "created_by", "expires_at",
"expiry_email_sent_at", "completed_count"
]
# form_excluded_columns = [
# "is_deleted", "completed_at", "expires_at", "expiry_email_sent_at", "organisation"
# ]
column_filters = (
filters.DateBetweenFilter(column=Task.created_at, name="Uploaded Date"),
filters.FilterEqual(column=Task.task_type, options=models.TaskType.options(), name="Task Type"),
)
column_formatters = dict(
task_type=lambda v, c, m, p: m.task_type.name.replace('_', ' ').title() if m.task_type else "N/A",
completed_count=lambda v, c, m, p: (
'' if not m.record_count else f"{m.completed_count} / {m.record_count} ({m.completed_percent:.1f}%)"),
)
class RecordModelView(AppModelView):
"""Task record model view."""
roles_required = Role.SUPERUSER | Role.ADMIN
list_template = "record_list.html"
column_exclude_list = (
"task",
"organisation",
)
form_excluded_columns = [
"task",
"organisation",
"processed_at",
"status",
]
column_export_exclude_list = (
"task",
)
can_edit = True
can_create = False
can_delete = True
can_view_details = True
can_export = True
form_widget_args = {"external_id": {"readonly": True}, "task": {"readonly": True}}
def render(self, template, **kwargs):
"""Pass the task to the render function as an added argument."""
if template == self.list_template and "task" not in kwargs:
task_id = request.args.get("task_id")
if task_id:
try:
kwargs["task"] = Task.get(id=task_id)
except Task.DoesNotExist:
flash(f"The task with ID: {task_id} doesn't exist.", "danger")
abort(404)
else:
return redirect(request.args.get("url") or url_for("task.index_view"))
return super().render(template, **kwargs)
def is_accessible(self):
"""Verify if the task view is accessible for the current user."""
if not super().is_accessible():
return False
# Added the feature for superuser to access task related to all research organiastion
if current_user.is_superuser:
return True
if request.method == "POST" and request.form.get("rowid"):
# get the first ROWID:
rowid = int(request.form.get("rowid"))
task_id = self.model.get(id=rowid).task_id
else:
task_id = self.current_task_id
if not task_id:
_id = request.args.get("id")
if not _id:
flash("Cannot invoke the task view without task ID", "danger")
flash("Missing or incorrect task ID value", "danger")
return False
else:
task_id = self.model.get(id=_id).task_id
try:
task = Task.get(id=task_id)
if task.org.id != current_user.organisation.id:
flash("Access denied! You cannot access this task.", "danger")
return False
except Task.DoesNotExist:
flash("The task doesn't exist.", "danger")
abort(404)
except ValueError as ex:
flash(str(ex), "danger")
return False
return True
def get_export_name(self, export_type='csv'):
"""Get export file name using the original imported file name.
:return: The exported csv file name.
"""
task_id = request.args.get("task_id")
if task_id:
try:
task = Task.get(id=task_id)
filename = os.path.splitext(task.filename)[0]
return "%s_%s.%s" % (filename, datetime.utcnow().strftime("%Y-%m-%d_%H-%M-%S"),
export_type)
except Task.DoesNotExist:
flash(f"The batch task doesn't exist", "danger")
abort(404)
return super().get_export_name(export_type=export_type)
@models.lazy_property
def record_processing_func(self):
"""Record processing function."""
return getattr(utils, f"process_{self.model.underscore_name()}s")
def enqueue_record(self, record_id):
"""Enqueue the specified record or all active and not yet processed ones."""
self.record_processing_func.queue(record_id=record_id)
@action("activate", "Activate for processing",
"""Are you sure you want to activate the selected records for batch processing?
By clicking "OK" you are affirming that the selected records to be written are,
to the best of your knowledge, correct!""")
def action_activate(self, ids):
"""Batch registraion of users."""
try:
status = "The record was activated at " + datetime.now().isoformat(timespec="seconds")
count = self.model.update(is_active=True, status=status).where(
self.model.is_active == False, # noqa: E712
self.model.id.in_(ids)).execute()
if self.model == AffiliationRecord:
records = self.model.select().where(self.model.id.in_(ids)).order_by(
self.model.email, self.model.orcid)
for _, chunk in itertools.groupby(records, lambda r: (r.email, r.orcid, )):
self.enqueue_record([r.id for r in chunk])
else:
for record_id in ids:
self.enqueue_record(record_id)
except Exception as ex:
flash(f"Failed to activate the selected records: {ex}")
app.logger.exception("Failed to activate the selected records")
else:
flash(f"{count} records were activated for batch processing.")
@action("reset", "Reset for processing",
"Are you sure you want to reset the selected records for batch processing?")
def action_reset(self, ids):
"""Reset batch task records."""
status = "The record was reset at " + datetime.utcnow().isoformat(timespec="seconds")
task_id = None
with db.atomic() as transaction:
try:
if request.method == "POST" and request.form.get("rowid"):
# get the first ROWID:
rowid = int(request.form.get("rowid"))
task_id = self.model.get(id=rowid).task_id
else:
task_id = request.form.get('task_id')
task = Task.get(id=task_id)
count = self.model.update(
processed_at=None, status=status).where(self.model.is_active,
self.model.id.in_(ids)).execute()
if hasattr(self.model, "invitees"):
im = self.model.invitees.rel_model
count = im.update(
processed_at=None, status=status).where(im.record.in_(ids)).execute()
emails = im.select(im.email).where(im.record_id.in_(ids))
else:
emails = self.model.select(self.model.email).where(self.model.id.in_(ids))
# Delete the userInvitation token for selected reset items.
UserInvitation.delete().where(UserInvitation.email.in_(emails)).execute()
for record_id in ids:
self.enqueue_record(record_id)
except Exception as ex:
transaction.rollback()
flash(f"Failed to activate the selected records: {ex}")
app.logger.exception("Failed to activate the selected records")
else:
task.expires_at = None
task.expiry_email_sent_at = None
task.completed_at = None
task.save()
flash(
f"{count} {task.task_type.name} records were reset and/or updated for batch processing."
)
def create_form(self):
"""Prefill form with organisation default values."""
form = super().create_form()
if request.method == "GET":
org = current_user.organisation
if hasattr(form, "org_name"):
form.org_name.data = org.name
if hasattr(form, "city"):
form.city.data = org.city
if hasattr(form, "region"):
form.region.data = org.region
if hasattr(form, "country"):
form.country.data = org.country
if hasattr(form, "disambiguated_id"):
form.disambiguated_id.data = org.disambiguated_id
if hasattr(form, "disambiguation_source"):
form.disambiguation_source.data = org.disambiguation_source
return form
@property
def current_task_id(self):
"""Get task_id form the query pameter task_id or url."""
try:
task_id = request.args.get("task_id")
if task_id:
return int(task_id)
url = request.args.get("url")
if not url:
flash("Missing return URL.", "danger")
return False
qs = parse_qs(urlparse(url).query)
task_id = qs.get("task_id", [None])[0]
if task_id:
return int(task_id)
except:
return None
def create_model(self, form):
"""Link model to the current task."""
task_id = self.current_task_id
if not task_id:
flash("Missing task ID.", "danger")
return False
try:
model = self.model(task_id=task_id)
form.populate_obj(model)
self._on_model_change(form, model, True)
model.save()
# For peewee have to save inline forms after model was saved
save_inline(form, model)
except Exception as ex:
if not self.handle_view_exception(ex):
flash(f"Failed to create record: {ex}", "danger")
app.log.exception("Failed to create record.")
return False
else:
self.after_model_change(form, model, True)
if model.is_active:
self.enqueue_record(model.id)
return model
def update_model(self, form, model):
"""Handle change of the record. Enqueue the record if got activated."""
is_active = model.is_active
update_resp = super().update_model(form, model)
if update_resp and not is_active and model.is_active:
self.enqueue_record(model.id)
return update_resp
class RecordChildAdmin(AppModelView):
"""Batch processing record child model common bits."""
roles_required = Role.SUPERUSER | Role.ADMIN
list_template = "record_child_list.html"
can_edit = True
can_create = True
can_delete = True
can_view_details = True
column_exclude_list = ["record"]
form_excluded_columns = ["record", "record", "status", "processed_at"]
column_details_exclude_list = ["record"]
def is_accessible(self):
"""Verify if the view is accessible for the current user."""
if not super().is_accessible():
flash("Access denied! You cannot access this record.", "danger")
return False
return True
@property
def current_record_id(self):
"""Get record_id form the query pameter record_id or url."""
try:
record_id = request.args.get("record_id")
if record_id:
return int(record_id)
url = request.args.get("url")
if not url:
flash("Missing return URL.", "danger")
return None
qs = parse_qs(urlparse(url).query)
record_id = qs.get("record_id", [None])[0]
if record_id:
return int(record_id)
except:
return None
def create_model(self, form):
"""Link model to the current record."""
record_id = self.current_record_id
if not record_id:
flash("Missing record ID.", "danger")
return False
try:
model = self.model()
form.populate_obj(model)
model.record_id = record_id
self._on_model_change(form, model, True)
model.save()
# For peewee have to save inline forms after model was saved
save_inline(form, model)
except Exception as ex:
if not self.handle_view_exception(ex):
flash(f"Failed to create record: {ex}", "danger")
app.log.exception("Failed to create record.")
return False
else:
self.after_model_change(form, model, True)
return model
class ExternalIdAdmin(RecordChildAdmin):
"""Combine ExternalId model view."""
can_edit = True
can_create = True
can_delete = True
can_view_details = True
form_widget_args = {"external_id": {"readonly": True}}
def is_accessible(self):
"""Verify if the external id's view is accessible for the current user."""
if not super().is_accessible():
flash("Access denied! You cannot access this task.", "danger")
return False
return True
class InviteeAdmin(RecordChildAdmin):
"""Combine Invitees record model view."""
@action("reset", "Reset for processing",
"Are you sure you want to reset the selected records for batch processing?")
def action_reset(self, ids):
"""Batch reset of users."""
with db.atomic() as transaction:
try:
status = " The record was reset at " + datetime.utcnow().isoformat(timespec="seconds")
count = self.model.update(
processed_at=None, status=status).where(self.model.id.in_(ids)).execute()
record_id = self.model.select().where(
self.model.id.in_(ids))[0].record_id