-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema.py
More file actions
1284 lines (1085 loc) · 44.7 KB
/
Copy pathschema.py
File metadata and controls
1284 lines (1085 loc) · 44.7 KB
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
import re
from typing import List
import graphene
from auditlog_extra.graphene_decorators import auditlog_access
from django.apps import apps
from django.conf import settings
from django.db import IntegrityError, transaction
from django.utils import timezone
from django.utils.translation import get_language
from django.utils.translation import gettext_lazy as _
from graphene.utils.str_converters import to_snake_case
from graphene_django import DjangoConnectionField, DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from common.utils import (
LanguageEnum,
get_editable_obj_from_global_id,
get_node_id_from_global_id,
map_enums_to_values_in_kwargs,
raise_permission_denied_if_not_event_staff,
update_object,
update_object_with_translations,
)
from graphene_linked_events.schema import LocalisedObject, Place
from graphene_linked_events.utils import api_client, format_response, json2obj
from occurrences.consts import NOTIFICATION_TYPES
from occurrences.filters import OccurrenceFilter
from occurrences.models import (
Enrolment,
EventQueueEnrolment,
Language,
Occurrence,
PalvelutarjotinEvent,
StudyGroup,
StudyLevel,
VenueCustomData,
)
from occurrences.schema_services import (
add_contact_persons_to_object,
create_study_group,
enrol_to_event_queue,
enrol_to_occurrence,
get_instance_list,
get_or_create_contact_person,
update_study_group,
validate_enrolment,
validate_occurrence_data,
verify_captcha,
verify_enrolment_token,
)
from organisations.decorators import event_staff_member_required
from organisations.models import Organisation
from organisations.schema import PersonNodeInput
from palvelutarjotin.exceptions import (
AlreadyJoinedEventError,
ApiUsageError,
EnrolCancelledOccurrenceError,
ObjectDoesNotExistError,
)
# TODO: Get rid of this when the graphene and django_filters gives the support.
class OrderedDjangoFilterConnectionField(DjangoFilterConnectionField):
"""
OrderedDjangoFilterConnectionField makes it possible to use
a filter to order the result nodes.
Example:
--------
query {
posts(orderBy: "-createdAt") {
title
}
}
In newer versions of
graphene, django-graphene and django-filters this feature comes out of the box:
https://docs.graphene-python.org/projects/django/en/latest/filtering/#ordering
Example:
--------
class UserFilter(FilterSet):
class Meta:
model = UserModel
order_by = OrderingFilter(
fields=(
('name', 'created_at'),
)
)
"""
@classmethod
def resolve_queryset(
cls, connection, iterable, info, args, filtering_args, filterset_class
):
qs = super(DjangoFilterConnectionField, cls).resolve_queryset(
connection, iterable, info, args
)
filter_kwargs = {k: v for k, v in args.items() if k in filtering_args}
qs = filterset_class(data=filter_kwargs, queryset=qs, request=info.context).qs
order = args.get("orderBy", None)
if order:
if type(order) is str:
snake_order = to_snake_case(order)
else:
snake_order = [to_snake_case(o) for o in order]
qs = qs.order_by(*snake_order)
return qs
StudyLevelTranslation = apps.get_model("occurrences", "StudyLevelTranslation")
VenueTranslation = apps.get_model("occurrences", "VenueCustomDataTranslation")
PalvelutarjotinEventTranslation = apps.get_model(
"occurrences", "PalvelutarjotinEventTranslation"
)
NotificationTypeEnum = graphene.Enum(
"NotificationType", [(t[0].upper(), t[0]) for t in NOTIFICATION_TYPES]
)
EnrolmentStatusEnum = graphene.Enum(
"EnrolmentStatus", [(s[0].upper(), s[0]) for s in Enrolment.STATUSES]
)
EventQueueEnrolmentStatusEnum = graphene.Enum(
"EventQueueEnrolmentStatus",
[(s[0].upper(), s[0]) for s in EventQueueEnrolment.QUEUE_STATUSES],
)
OccurrenceSeatTypeEnum = graphene.Enum(
"SeatType", [(t[0].upper(), t[0]) for t in Occurrence.OCCURRENCE_SEAT_TYPES]
)
class OccurrenceNode(DjangoObjectType):
remaining_seats = graphene.Int(required=True)
seats_taken = graphene.Int(required=True)
seats_approved = graphene.Int(required=True)
linked_event = graphene.Field(
"graphene_linked_events.schema.Event",
description="Only use this field in single event query for "
+ "best performance.",
)
def resolve_linked_event(self, info, **kwargs):
response = api_client.retrieve(
"event",
self.p_event.linked_event_id,
is_event_staff=getattr(info.context.user, "is_event_staff", False),
)
obj = json2obj(format_response(response))
return obj
class Meta:
model = Occurrence
fields = "__all__"
interfaces = (graphene.relay.Node,)
filterset_class = OccurrenceFilter
@classmethod
def get_queryset(cls, queryset, info):
return (
super()
.get_queryset(queryset, info)
.select_related("p_event")
.prefetch_related("languages")
.order_by("start_time")
)
def resolve_remaining_seats(self, info, **kwargs):
return self.amount_of_seats - self.seats_taken
class PalvelutarjotinEventTranslationType(DjangoObjectType):
language_code = LanguageEnum(required=True)
auto_acceptance_message = graphene.String(required=True)
class Meta:
model = PalvelutarjotinEventTranslation
exclude = ("id", "master")
class PalvelutarjotinEventNode(DjangoObjectType):
next_occurrence_datetime = graphene.DateTime()
last_occurrence_datetime = graphene.DateTime()
has_space_for_enrolments = graphene.Boolean(
description=_(
"Determines whether any upcoming occurrence has any space left "
"for new enrolments."
)
)
occurrences = OrderedDjangoFilterConnectionField(
OccurrenceNode, orderBy=graphene.List(of_type=graphene.String), max_limit=400
)
auto_acceptance_message = graphene.String(
description="Translated field in the language defined in request "
"ACCEPT-LANGUAGE header "
)
translations = graphene.List(PalvelutarjotinEventTranslationType)
class Meta:
model = PalvelutarjotinEvent
fields = "__all__"
interfaces = (graphene.relay.Node,)
def resolve_next_occurrence_datetime(self, info, **kwargs):
# Filter the prefetched occurrences in Python to avoid extra DB queries.
now = timezone.now()
upcoming = [
o
for o in self.occurrences.all()
if not o.cancelled and o.start_time >= now
]
if not upcoming:
return None
return min(upcoming, key=lambda o: o.start_time).start_time
def resolve_last_occurrence_datetime(self, info, **kwargs):
# Filter the prefetched occurrences in Python to avoid extra DB queries.
non_cancelled = [o for o in self.occurrences.all() if not o.cancelled]
if not non_cancelled:
return None
return max(non_cancelled, key=lambda o: o.start_time).start_time
def resolve_has_space_for_enrolments(self, info, **kwargs):
"""
Determines whether any upcoming or ongoing occurrence has any space left for
enrolments.
This method leverages the internal `has_space_for_enrolments` logic to ascertain
if there are any future event occurrences with available spaces for enrollment.
Args:
info: Contextual information provided by the GraphQL execution environment
(may not be used in this specific implementation).
**kwargs: Additional keyword arguments
(may not be used in this specific implementation).
Returns:
- True: If at least one upcoming or ongoing occurrence has space for
enrolments.
- False: If no upcoming occurrences have space for enrolments.
- None: If the event doesn't utilize the enrolments system or
relies on an external enrolments system.
"""
return self.has_space_for_enrolments()
def resolve_translations(self, info, **kwargs):
return self.translations.all()
@classmethod
def get_queryset(cls, queryset, info):
lang = get_language()
return queryset.language(lang)
@classmethod
def get_node(cls, info, id):
return super().get_node(info, id)
class PalvelutarjotinEventTranslationsInput(graphene.InputObjectType):
auto_acceptance_message = graphene.String(
description="A custom message included in notification template "
"when auto acceptance is set on.",
)
language_code = LanguageEnum(required=True)
class PalvelutarjotinEventInput(graphene.InputObjectType):
enrolment_start = graphene.DateTime()
enrolment_end_days = graphene.Int()
external_enrolment_url = graphene.String()
needed_occurrences = graphene.Int(required=True)
contact_person_id = graphene.ID()
contact_phone_number = graphene.String()
contact_email = graphene.String()
auto_acceptance = graphene.Boolean()
is_queueing_allowed = graphene.Boolean()
mandatory_additional_information = graphene.Boolean()
translations = graphene.List(PalvelutarjotinEventTranslationsInput)
class StudyLevelTranslationType(DjangoObjectType):
language_code = LanguageEnum(required=True)
class Meta:
model = StudyLevelTranslation
exclude = ("id", "master")
class StudyLevelNode(DjangoObjectType):
id = graphene.ID(source="pk", required=True)
label = graphene.String(
description="Translated field in the language defined in request "
"ACCEPT-LANGUAGE header "
)
class Meta:
model = StudyLevel
interfaces = (graphene.relay.Node,)
exclude = ("study_groups",)
@classmethod
def get_queryset(cls, queryset, info):
lang = get_language()
return queryset.language(lang).prefetch_related("translations")
class ExternalPlace(graphene.ObjectType):
name = graphene.Field(LocalisedObject)
class UnitNode(graphene.Union):
class Meta:
types = (ExternalPlace, Place)
@classmethod
def resolve_type(cls, instance, info):
if getattr(instance, "_meta", None) == "ExternalPlace":
return ExternalPlace
if getattr(instance, "id", None):
return Place
return ExternalPlace
@auditlog_access # log access because of personal information
class StudyGroupNode(DjangoObjectType):
class Meta:
model = StudyGroup
fields = "__all__"
interfaces = (graphene.relay.Node,)
unit = graphene.Field(UnitNode)
@staticmethod
def resolve_unit(parent, info, **kwargs):
if parent.unit_id:
response = api_client.retrieve("place", parent.unit_id)
return json2obj(format_response(response))
if parent.unit_name:
return ExternalPlace(
name={
"fi": parent.unit_name,
"sv": parent.unit_name,
"en": parent.unit_name,
}
)
return None
@classmethod
def get_queryset(cls, queryset, info):
"""
The study groups are available only for the staff members.
Also the staff member should get only the study groups
participating in event of an organisation
he has access to. So, the study groups list should be
filtered by the organisation
"""
path = ".".join(str(path_element) for path_element in info.path.as_list())
path = re.sub(r"\d+", "<int>", path) # Map non-negative integers to "<int>"
if (
# Allow access to the study group created in EnrolEventQueueMutation
path == "enrolEventQueue.eventQueueEnrolment.studyGroup"
# Allow access to the study group in cancellingEnrolment query
or path == "cancellingEnrolment.studyGroup"
# Allow access to the study group through person's event queue enrolments,
or path == "person.eventqueueenrolmentSet.edges.<int>.node.studyGroup"
# Allow access to the study group in EnrolOccurrenceMutation
or path == "enrolOccurrence.enrolments.<int>.studyGroup"
):
return queryset
raise_permission_denied_if_not_event_staff(info.context.user)
return queryset.user_can_view(info.context.user)
class VenueTranslationType(DjangoObjectType):
language_code = LanguageEnum(required=True)
class Meta:
model = VenueTranslation
exclude = ("id", "master")
class VenueTranslationsInput(graphene.InputObjectType):
description = graphene.String()
language_code = LanguageEnum(required=True)
class VenueNode(DjangoObjectType):
description = graphene.String(
description="Translated field in the language defined in request "
"ACCEPT-LANGUAGE header "
)
id = graphene.ID(
source="place_id", description="place_id from linkedEvent", required=True
)
class Meta:
model = VenueCustomData
interfaces = (graphene.relay.Node,)
exclude = ("place_id",)
@classmethod
def get_queryset(cls, queryset, info):
lang = get_language()
return queryset.language(lang)
@classmethod
def get_node(cls, info, id):
return super().get_node(info, id)
class LanguageNode(DjangoObjectType):
id = graphene.ID(source="pk", required=True)
class Meta:
model = Language
exclude = ("occurrences",)
interfaces = (graphene.relay.Node,)
class LanguageInput(graphene.InputObjectType):
id = graphene.String()
class AddOccurrenceMutation(graphene.relay.ClientIDMutation):
class Input:
place_id = graphene.String()
min_group_size = graphene.Int()
max_group_size = graphene.Int()
start_time = graphene.DateTime(required=True)
end_time = graphene.DateTime(required=True)
contact_persons = graphene.List(PersonNodeInput)
p_event_id = graphene.ID(required=True)
amount_of_seats = graphene.Int(required=True)
seat_type = OccurrenceSeatTypeEnum()
languages = graphene.NonNull(graphene.List(LanguageInput))
occurrence = graphene.Field(OccurrenceNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
p_event = get_editable_obj_from_global_id(
info, kwargs["p_event_id"], PalvelutarjotinEvent
)
validate_occurrence_data(p_event, kwargs)
contact_persons = kwargs.pop("contact_persons", None)
languages = kwargs.pop("languages", None)
kwargs["p_event_id"] = p_event.id
occurrence = Occurrence.objects.create(**kwargs)
if contact_persons:
add_contact_persons_to_object(info, contact_persons, occurrence)
if languages:
occurrence.languages.set(
get_instance_list(Language, [x["id"].lower() for x in languages])
)
return AddOccurrenceMutation(occurrence=occurrence)
class UpdateOccurrenceMutation(graphene.relay.ClientIDMutation):
class Input:
id = graphene.GlobalID()
place_id = graphene.String()
min_group_size = graphene.Int()
max_group_size = graphene.Int()
start_time = graphene.DateTime()
end_time = graphene.DateTime()
contact_persons = graphene.List(
PersonNodeInput,
description="Should include all contact "
"persons of the occurrence, "
"missing contact persons will be "
"removed during mutation",
)
p_event_id = graphene.ID()
amount_of_seats = graphene.Int()
languages = graphene.NonNull(
graphene.List(LanguageInput),
description="If present, should include all languages of the occurrence",
)
seat_type = OccurrenceSeatTypeEnum()
occurrence = graphene.Field(OccurrenceNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
occurrence = get_editable_obj_from_global_id(info, kwargs.pop("id"), Occurrence)
p_event = occurrence.p_event
validate_occurrence_data(p_event, kwargs, occurrence)
contact_persons = kwargs.pop("contact_persons", None)
languages = kwargs.pop("languages", None)
if kwargs.get("p_event_id"):
p_event = get_editable_obj_from_global_id(
info, kwargs["p_event_id"], PalvelutarjotinEvent
)
kwargs["p_event_id"] = p_event.id
"""
1. If there are no enrolments done to the occurrence of a published event,
it should be possible to edit it.
2. If there are some enrolments done to the published event,
it should not be editable.
"""
if p_event.is_published() and occurrence.seats_taken > 0:
raise ApiUsageError(
"Cannot update occurrence of published event with enrolments"
)
update_object(occurrence, kwargs)
# Nested update
if contact_persons:
add_contact_persons_to_object(info, contact_persons, occurrence)
if languages:
occurrence.languages.set(
get_instance_list(Language, [x["id"].lower() for x in languages])
)
return UpdateOccurrenceMutation(occurrence=occurrence)
class DeleteOccurrenceMutation(graphene.ClientIDMutation):
class Input:
id = graphene.GlobalID()
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
occurrence = get_editable_obj_from_global_id(info, kwargs.pop("id"), Occurrence)
if occurrence.p_event.is_published() and not occurrence.cancelled:
raise ApiUsageError(
"Cannot delete published occurrence. Event is "
"published or occurrence is not cancelled"
)
occurrence.delete()
return DeleteOccurrenceMutation()
class CancelOccurrenceMutation(graphene.ClientIDMutation):
class Input:
id = graphene.GlobalID()
reason = graphene.String()
occurrence = graphene.Field(OccurrenceNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
occurrence = get_editable_obj_from_global_id(info, kwargs.pop("id"), Occurrence)
if occurrence.cancelled:
raise ApiUsageError("Occurrence is already cancelled")
occurrence.cancel(reason=kwargs.pop("reason", None))
return CancelOccurrenceMutation(occurrence)
class AddVenueMutation(graphene.relay.ClientIDMutation):
class Input:
id = graphene.ID(description="Place id from linked event", required=True)
translations = graphene.List(VenueTranslationsInput)
has_clothing_storage = graphene.Boolean(required=True)
has_snack_eating_place = graphene.Boolean(required=True)
outdoor_activity = graphene.Boolean(required=True)
has_toilet_nearby = graphene.Boolean(required=True)
has_area_for_group_work = graphene.Boolean(required=True)
has_indoor_playing_area = graphene.Boolean(required=True)
has_outdoor_playing_area = graphene.Boolean(required=True)
venue = graphene.Field(VenueNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
# TODO: Add validation
kwargs["place_id"] = kwargs.pop("id")
translations = kwargs.pop("translations")
venue, _ = VenueCustomData.objects.get_or_create(**kwargs)
venue.create_or_update_translations(translations)
return AddVenueMutation(venue=venue)
class UpdateVenueMutation(graphene.relay.ClientIDMutation):
class Input:
id = graphene.ID(description="Place id from linked event", required=True)
translations = graphene.List(VenueTranslationsInput)
has_clothing_storage = graphene.Boolean()
has_snack_eating_place = graphene.Boolean()
outdoor_activity = graphene.Boolean()
has_toilet_nearby = graphene.Boolean()
has_area_for_group_work = graphene.Boolean()
has_indoor_playing_area = graphene.Boolean()
has_outdoor_playing_area = graphene.Boolean()
venue = graphene.Field(VenueNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
# TODO: Add validation
try:
venue = VenueCustomData.objects.get(pk=kwargs.pop("id"))
update_object_with_translations(venue, kwargs)
except VenueCustomData.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
return UpdateVenueMutation(venue=venue)
class DeleteVenueMutation(graphene.relay.ClientIDMutation):
class Input:
id = graphene.ID(description="Place id from linked event", required=True)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
try:
venue = VenueCustomData.objects.get(pk=kwargs.pop("id"))
venue.delete()
except VenueCustomData.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
return DeleteVenueMutation()
class EnrolmentConnectionWithCount(graphene.Connection):
class Meta:
abstract = True
count = graphene.Int()
def resolve_count(self, info, **kwargs):
return self.length
@auditlog_access # log access because of personal information
class EnrolmentNode(DjangoObjectType):
notification_type = NotificationTypeEnum()
status = EnrolmentStatusEnum()
class Meta:
model = Enrolment
fields = "__all__"
filter_fields = ["status", "occurrence_id"]
interfaces = (graphene.relay.Node,)
connection_class = EnrolmentConnectionWithCount
@classmethod
@event_staff_member_required
def get_queryset(cls, queryset, info):
"""
The enrolments are available only for the staff members.
Also the staff member should get only the enrolments
done to the occurrences provided by an organisation
he has access to. So, the enrolments list should be
filtered by the organisation
"""
return queryset.user_can_view(info.context.user)
@auditlog_access # log access because of personal information
class EventQueueEnrolmentNode(DjangoObjectType):
notification_type = NotificationTypeEnum()
status = EventQueueEnrolmentStatusEnum()
class Meta:
model = EventQueueEnrolment
fields = "__all__"
filter_fields = ["p_event_id"]
interfaces = (graphene.relay.Node,)
connection_class = EnrolmentConnectionWithCount
@classmethod
@event_staff_member_required
def get_queryset(cls, queryset, info):
"""
The enrolments are available only for the staff members.
Also the staff member should get only the enrolments
done to the occurrences provided by an organisation
he has access to. So, the enrolments list should be
filtered by the organisation
"""
return queryset.user_can_view(info.context.user)
class StudyGroupInput(graphene.InputObjectType):
person = graphene.NonNull(
PersonNodeInput,
description="If person input doesn't include person id, "
"a new person "
"object will be created",
)
unit_id = graphene.String()
unit_name = graphene.String()
group_size = graphene.Int(required=True)
group_name = graphene.String()
extra_needs = graphene.String()
amount_of_adult = graphene.Int()
study_levels = graphene.List(graphene.String)
preferred_times = graphene.String()
class EnrolInputBase:
study_group = StudyGroupInput(description="Study group data", required=True)
notification_type = NotificationTypeEnum()
person = PersonNodeInput(
description="Leave blank if the contact person is "
"the same with group contact person"
)
captcha_key = graphene.String(
description="The user response token provided "
"by the reCAPTCHA client-side "
"integration",
)
class EnrolEventQueueMutation(graphene.relay.ClientIDMutation):
class Input(EnrolInputBase):
p_event_id = graphene.ID(
required=True, description="The event that a group would like to queue to"
)
event_queue_enrolment = graphene.Field(EventQueueEnrolmentNode)
@classmethod
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
if settings.CAPTCHA_ENABLED:
verify_captcha(kwargs.pop("captcha_key", None))
else:
# UI will always send the captcha,
# and if it is not removed,
# it will raise an error.
kwargs.pop("captcha_key", None)
p_event_id = get_node_id_from_global_id(
kwargs.pop("p_event_id"), "PalvelutarjotinEventNode"
)
p_event = PalvelutarjotinEvent.objects.get(id=p_event_id)
study_group = create_study_group(kwargs.pop("study_group"))
contact_person_data = kwargs.pop("person", None)
notification_type = kwargs.pop(
"notification_type",
EventQueueEnrolment._meta.get_field("notification_type").get_default(),
)
# Use group contact person if person data not submitted
if contact_person_data:
person = get_or_create_contact_person(contact_person_data)
else:
person = study_group.person
event_queue_enrolment = enrol_to_event_queue(
study_group=study_group,
p_event=p_event,
person=person,
notification_type=notification_type,
)
return EnrolEventQueueMutation(event_queue_enrolment=event_queue_enrolment)
class UnenrolEventQueueMutation(graphene.relay.ClientIDMutation):
class Input:
p_event_id = graphene.GlobalID()
study_group_id = graphene.GlobalID(description="Study group id")
p_event = graphene.Field(PalvelutarjotinEventNode)
study_group = graphene.Field(StudyGroupNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
group_id = get_node_id_from_global_id(
kwargs["study_group_id"], "StudyGroupNode"
)
try:
study_group = StudyGroup.objects.get(pk=group_id)
except StudyGroup.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
p_event = get_editable_obj_from_global_id(
info, kwargs["p_event_id"], PalvelutarjotinEvent
)
# Need to unenrol all related occurrence of the study group
enrolments = study_group.queued_enrolments.filter(p_event=p_event)
for e in enrolments:
e.delete()
return UnenrolEventQueueMutation(study_group=study_group, p_event=p_event)
class PickEnrolmentFromQueueMutation(graphene.relay.ClientIDMutation):
class Input:
occurrence_id = graphene.GlobalID()
event_queue_enrolment_id = graphene.GlobalID()
enrolment = graphene.Field(EnrolmentNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
occurrence = get_editable_obj_from_global_id(
info, kwargs["occurrence_id"], Occurrence
)
queue_enrolment = get_editable_obj_from_global_id(
info, kwargs["event_queue_enrolment_id"], EventQueueEnrolment
)
if occurrence.p_event != queue_enrolment.p_event:
raise ApiUsageError(
"The queued enrolment and the occurrence must be for the same event"
)
if occurrence.cancelled:
raise EnrolCancelledOccurrenceError(
"Cannot approve enrolment to cancelled occurrence"
)
try:
enrolment = queue_enrolment.create_enrolment(occurrence)
except IntegrityError:
event_id = occurrence.p_event.linked_event_id
raise AlreadyJoinedEventError(
f"The study group ({queue_enrolment.study_group}) is already "
f"in the list of enrolment of this event ({event_id})."
)
return ApproveEnrolmentMutation(enrolment=enrolment)
class EnrolOccurrenceMutation(graphene.relay.ClientIDMutation):
class Input(EnrolInputBase):
occurrence_ids = graphene.NonNull(
graphene.List(graphene.ID), description="Occurrence ids of event"
)
send_notifications = graphene.Boolean(
description="Should the related notifications be sent during the mutation. "
"Default is True.",
)
enrolments = graphene.List(EnrolmentNode)
@classmethod
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
if settings.CAPTCHA_ENABLED:
verify_captcha(kwargs.pop("captcha_key", None))
else:
# UI will always send the captcha,
# and if it is not removed,
# it will raise an error.
kwargs.pop("captcha_key", None)
study_group = create_study_group(kwargs.pop("study_group"))
contact_person_data = kwargs.pop("person", None)
notification_type = kwargs.pop(
"notification_type",
Enrolment._meta.get_field("notification_type").get_default(),
)
send_notifications = kwargs.pop("send_notifications", True)
occurrence_ids = [
get_node_id_from_global_id(occurrence_gid, "OccurrenceNode")
for occurrence_gid in kwargs.pop("occurrence_ids")
]
occurrences = get_instance_list(Occurrence, occurrence_ids)
# Use group contact person if person data not submitted
if contact_person_data:
person = get_or_create_contact_person(contact_person_data)
else:
person = study_group.person
enrolments = enrol_to_occurrence(
study_group=study_group,
occurrences=occurrences,
person=person,
notification_type=notification_type,
send_notifications_on_auto_acceptance=send_notifications,
)
return EnrolOccurrenceMutation(enrolments=enrolments)
class UnenrolOccurrenceMutation(graphene.relay.ClientIDMutation):
class Input:
occurrence_id = graphene.GlobalID(description="Occurrence id of event")
study_group_id = graphene.GlobalID(description="Study group id")
occurrence = graphene.Field(OccurrenceNode)
study_group = graphene.Field(StudyGroupNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
group_id = get_node_id_from_global_id(
kwargs["study_group_id"], "StudyGroupNode"
)
try:
study_group = StudyGroup.objects.get(pk=group_id)
except StudyGroup.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
occurrence = get_editable_obj_from_global_id(
info, kwargs["occurrence_id"], Occurrence
)
# Need to unenrol all related occurrence of the study group
enrolments = study_group.enrolments.filter(
occurrence__p_event=occurrence.p_event
)
for e in enrolments:
e.delete()
return UnenrolOccurrenceMutation(study_group=study_group, occurrence=occurrence)
class UpdateEnrolmentMutation(graphene.relay.ClientIDMutation):
class Input:
enrolment_id = graphene.GlobalID()
notification_type = NotificationTypeEnum()
study_group = StudyGroupInput(description="Study group input")
person = PersonNodeInput(
description="Leave blank if the contact person is "
"the same with group contact person"
)
enrolment = graphene.Field(EnrolmentNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
enrolment = get_editable_obj_from_global_id(
info, kwargs.pop("enrolment_id"), Enrolment
)
study_group = enrolment.study_group
study_group_data = kwargs.pop("study_group", None)
if study_group_data:
update_study_group(study_group_data, study_group)
contact_person_data = kwargs.pop("person", None)
# Use latest group contact person if person data not submitted
if contact_person_data:
person = get_or_create_contact_person(contact_person_data)
else:
person = study_group.person
kwargs["person_id"] = person.id
# Update all related enrolments
enrolments = Enrolment.objects.filter(
occurrence__p_event=enrolment.occurrence.p_event,
study_group=enrolment.study_group,
)
for enrolment in enrolments:
validate_enrolment(study_group, enrolment.occurrence, new_enrolment=False)
update_object(enrolment, kwargs)
return UpdateEnrolmentMutation(enrolment=enrolment)
class ApproveEnrolmentMutation(graphene.relay.ClientIDMutation):
class Input:
enrolment_id = graphene.GlobalID()
custom_message = graphene.String()
enrolment = graphene.Field(EnrolmentNode)
@classmethod
@event_staff_member_required
@transaction.atomic
@map_enums_to_values_in_kwargs
def mutate_and_get_payload(cls, root, info, **kwargs):
e = get_editable_obj_from_global_id(info, kwargs["enrolment_id"], Enrolment)
custom_message = kwargs.pop("custom_message", None)
# Do not allow manual approvement if enrolment require more than 1 occurrences
if e.occurrence.p_event.needed_occurrences > 1:
raise ApiUsageError(
"Cannot approve enrolment that requires more than 1 occurrence"
)
if e.occurrence.cancelled:
raise EnrolCancelledOccurrenceError(
"Cannot approve enrolment to cancelled occurrence"
)
e.approve(custom_message=custom_message)
e.refresh_from_db()
return ApproveEnrolmentMutation(enrolment=e)