-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema_services.py
More file actions
326 lines (285 loc) · 10.9 KB
/
Copy pathschema_services.py
File metadata and controls
326 lines (285 loc) · 10.9 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
from datetime import timedelta
from typing import List, Optional, Tuple, Union
import requests
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from common.utils import (
get_node_id_from_global_id,
get_obj_from_global_id,
update_object,
)
from occurrences.models import (
Enrolment,
EventQueueEnrolment,
Occurrence,
PalvelutarjotinEvent,
StudyGroup,
StudyLevel,
)
from organisations.models import Person
from palvelutarjotin.exceptions import (
CaptchaValidationFailedError,
DataValidationError,
EnrolCancelledOccurrenceError,
EnrolmentClosedError,
EnrolmentMaxNeededOccurrenceReachedError,
EnrolmentNotEnoughCapacityError,
EnrolmentNotStartedError,
InvalidStudyGroupSizeError,
InvalidStudyGroupUnitInfoError,
InvalidTokenError,
MissingMantatoryInformationError,
ObjectDoesNotExistError,
QueueingNotAllowedError,
)
from verification_token.models import VerificationToken
def validate_occurrence_data(p_event, kwargs, updated_obj=None):
end_time = (
kwargs.get("end_time", updated_obj.end_time)
if updated_obj
else kwargs["end_time"]
)
start_time = (
kwargs.get("start_time", updated_obj.start_time)
if updated_obj
else kwargs["start_time"]
)
if end_time <= start_time:
raise DataValidationError("End time must be after start time")
minimum_time = (
(p_event.enrolment_start + timedelta(days=p_event.enrolment_end_days))
if p_event.enrolment_end_days
else p_event.enrolment_start
)
if minimum_time is not None and start_time < minimum_time:
raise DataValidationError("Start time cannot be before the enrolment ends")
@transaction.atomic
def add_contact_persons_to_object(info, contact_persons, obj):
obj.contact_persons.clear()
for p in contact_persons:
p_global_id = p.get("id", None)
if p_global_id:
person = get_obj_from_global_id(info, p_global_id, Person)
else:
person = Person.objects.create(**p)
obj.contact_persons.add(person)
def validate_study_group(study_group: Union[StudyGroup, dict]):
if not isinstance(study_group, dict):
study_group_data = study_group.__dict__
else:
study_group_data = dict(study_group)
if not study_group_data.get("unit_id") and not study_group_data.get("unit_name"):
raise InvalidStudyGroupUnitInfoError(
"Study group should always have an unit id or an unit name."
)
def validate_enrolment( # noqa: C901
study_group: StudyGroup, occurrence: Occurrence, new_enrolment=True
):
validate_study_group(study_group)
# Expensive validation are sorted to bottom
if (
occurrence.p_event.mandatory_additional_information
and not study_group.extra_needs
):
raise MissingMantatoryInformationError(
"This event requires additional information of study group"
)
if occurrence.cancelled:
raise EnrolCancelledOccurrenceError("Cannot enrol cancelled occurrence")
if study_group.group_size_with_adults() < 1:
raise InvalidStudyGroupSizeError(
"Study group should contain at least 1 participant"
)
elif (
occurrence.max_group_size
and study_group.group_size_with_adults() > occurrence.max_group_size
) or (
occurrence.min_group_size
and study_group.group_size_with_adults() < occurrence.min_group_size
):
raise InvalidStudyGroupSizeError(
"Study group size not match occurrence group size"
)
if not occurrence.p_event.enrolment_start or (
timezone.now() < occurrence.p_event.enrolment_start
):
raise EnrolmentNotStartedError("Enrolment is not opened")
if (
occurrence.p_event.enrolment_end_days
and timezone.now()
> occurrence.start_time - timedelta(days=occurrence.p_event.enrolment_end_days)
):
raise EnrolmentClosedError("Enrolment has been closed")
# Skip these validations when updating enrolment
if new_enrolment:
if (
study_group.occurrences.filter(
p_event=occurrence.p_event, cancelled=False
).count()
>= occurrence.p_event.needed_occurrences
):
raise EnrolmentMaxNeededOccurrenceReachedError(
"Number of enrolled occurrences is greater than the needed occurrences"
)
if (
occurrence.seats_taken
+ (
study_group.group_size_with_adults()
if occurrence.seat_type
== Occurrence.OCCURRENCE_SEAT_TYPE_CHILDREN_COUNT
else 1
)
) > occurrence.amount_of_seats:
raise EnrolmentNotEnoughCapacityError(
"Not enough space for this study group"
)
else:
if occurrence.seats_taken > occurrence.amount_of_seats:
raise EnrolmentNotEnoughCapacityError(
"Not enough space for this study group"
)
def verify_captcha(key):
if not key:
raise CaptchaValidationFailedError("Missing captcha verification data")
secret_key = settings.RECAPTCHA_SECRET_KEY
verify_url = settings.RECAPTCHA_VALIDATION_URL
# captcha verification
data = {"response": key, "secret": secret_key}
resp = requests.post(verify_url, data=data, timeout=5)
result_json = resp.json()
if result_json.get("success"):
return True
else:
raise CaptchaValidationFailedError(
f"Captcha verification failed: {result_json.get('error-codes')}"
)
def verify_enrolment_token(enrolment, token):
try:
token_obj = VerificationToken.objects.get(key=token)
except VerificationToken.DoesNotExist:
raise InvalidTokenError("Token is invalid or expired")
if token_obj.content_object != enrolment or not token_obj.is_valid():
raise InvalidTokenError("Token is invalid or expired")
def create_study_group(study_group_data):
study_levels_data = study_group_data.pop("study_levels")
person_data = study_group_data.pop("person")
person = get_or_create_contact_person(person_data)
study_group_data["person_id"] = person.id
validate_study_group(study_group_data)
study_group = StudyGroup.objects.create(**study_group_data)
study_group.study_levels.set(
get_instance_list(StudyLevel, map(lambda x: x.lower(), study_levels_data))
)
return study_group
def update_study_group(study_group_data, study_group_obj=None):
if not study_group_obj:
study_group_global_id = study_group_data.pop("id")
study_group_id = get_node_id_from_global_id(
study_group_global_id, "StudyGroupNode"
)
try:
study_group_obj = StudyGroup.objects.get(id=study_group_id)
except StudyGroup.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
# Handle a person
person_data = study_group_data.pop("person", None)
if person_data:
person = get_or_create_contact_person(person_data)
study_group_data["person_id"] = person.id
# Handle study levels
study_levels_data = study_group_data.pop("study_levels", None)
if study_levels_data:
study_group_obj.study_levels.set(
get_instance_list(StudyLevel, map(lambda x: x.lower(), study_levels_data))
)
validate_study_group(study_group_data)
# update the populated object
update_object(study_group_obj, study_group_data)
return study_group_obj
def get_or_create_contact_person(contact_person_data):
"""
If a contact person id is given,
get a contact person with a given non-assignable id
or else, create a contact person with a given data.
"""
if contact_person_data.get("id"):
person_id = get_node_id_from_global_id(
contact_person_data.get("id"), "PersonNode"
)
try:
person = Person.objects.get(id=person_id)
except Person.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
else:
person = Person.objects.create(**contact_person_data)
return person
def get_instance_list(model_class, instance_pks: List[str]):
result = []
for instance_pk in instance_pks:
try:
instance = model_class.objects.get(pk=instance_pk)
result.append(instance)
except model_class.DoesNotExist as e:
raise ObjectDoesNotExistError(e)
return result
def enrol_to_occurrence(
study_group: StudyGroup,
occurrences: List[Occurrence],
person: Person,
is_part_of_cultural_route: bool,
notification_type,
send_notifications_on_auto_acceptance=True,
):
enrolments: List[Enrolment] = []
notifiable_enrolments: List[Tuple[Enrolment, Optional[str]]] = []
for occurrence in occurrences:
validate_enrolment(study_group, occurrence)
enrolment: Enrolment = Enrolment.objects.create(
study_group=study_group,
occurrence=occurrence,
person=person,
is_part_of_cultural_route=is_part_of_cultural_route,
notification_type=notification_type,
)
if occurrence.p_event.auto_acceptance:
custom_message: Optional[str] = (
enrolment.occurrence.p_event.safe_translation_getter(
"auto_acceptance_message", language_code=person.language
)
)
# Skip notifications sending here:
# Send the notifications all at once when the data changes are done.
enrolment.approve(send_notification=False)
if send_notifications_on_auto_acceptance:
notifiable_enrolments.append((enrolment, custom_message))
enrolments.append(enrolment)
# Send all the notifications all at once when the data changes are done.
for enrolment, custom_message in notifiable_enrolments:
enrolment.send_approve_notification(custom_message=custom_message)
return enrolments
def enrol_to_event_queue(
study_group: StudyGroup,
p_event: PalvelutarjotinEvent,
person: Person,
is_part_of_cultural_route: bool,
notification_type: str,
):
if not p_event.is_queueing_allowed:
raise QueueingNotAllowedError("Queueing to this event is not allowed")
validate_study_group(study_group)
try:
event_queue_enrolment = EventQueueEnrolment.objects.get(
p_event=p_event, study_group__group_name=study_group.group_name
)
except EventQueueEnrolment.DoesNotExist:
event_queue_enrolment = EventQueueEnrolment(
p_event=p_event,
study_group=study_group,
person=person,
is_part_of_cultural_route=is_part_of_cultural_route,
notification_type=notification_type,
enrolment_time=timezone.now(),
)
event_queue_enrolment.save()
return event_queue_enrolment