forked from botswana-harvard/edc-visit-tracking
-
Notifications
You must be signed in to change notification settings - Fork 1
/
visit_form_validator.py
300 lines (262 loc) · 11.4 KB
/
visit_form_validator.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
from __future__ import annotations
from copy import deepcopy
from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Optional
from zoneinfo import ZoneInfo
from django import forms
from django.conf import settings
from edc_appointment.constants import MISSED_APPT
from edc_appointment.form_validator_mixins import WindowPeriodFormValidatorMixin
from edc_appointment.form_validators import validate_appt_datetime_unique
from edc_constants.constants import OTHER
from edc_form_validators import INVALID_ERROR, REQUIRED_ERROR, FormValidator
from edc_metadata.constants import KEYED
from edc_metadata.utils import (
get_crf_metadata_model_cls,
get_requisition_metadata_model_cls,
)
from edc_utils import formatted_datetime
from edc_visit_schedule.utils import is_baseline
from ..constants import MISSED_VISIT, UNSCHEDULED
from ..utils import get_subject_visit_missed_model_cls
from ..visit_sequence import VisitSequence, VisitSequenceError
if TYPE_CHECKING:
from edc_appointment.models import Appointment
EDC_VISIT_TRACKING_ALLOW_MISSED_UNSCHEDULED = getattr(
settings, "EDC_VISIT_TRACKING_ALLOW_MISSED_UNSCHEDULED", False
)
class VisitFormValidator(WindowPeriodFormValidatorMixin, FormValidator):
"""Form validator for visit models (e.g. subject_visit).
See also `report_datetime` checks in the
`VisitTrackingCrfModelFormMixin`.
"""
visit_sequence_cls = VisitSequence
validate_missed_visit_reason = True
validate_unscheduled_visit_reason = True
report_datetime_field_attr = "report_datetime"
def _clean(self) -> None:
super()._clean()
if not self.appointment:
raise forms.ValidationError(
{"appointment": "This field is required"}, code=REQUIRED_ERROR
)
validate_appt_datetime_unique(
form_validator=self,
appointment=self.appointment,
appt_datetime=self.appointment.appt_datetime,
form_field="appointment",
)
self.validate_visit_datetime_unique()
self.validate_visit_datetime_not_before_appointment()
self.validate_visit_datetime_matches_appt_datetime_at_baseline()
self.validate_visit_datetime_in_window_period()
self.validate_visits_completed_in_order()
self.validate_visit_code_sequence_and_reason()
self.validate_visit_reason()
self.required_if(OTHER, field="info_source", field_required="info_source_other")
@property
def subject_identifier(self) -> str:
return self.appointment.subject_identifier
@property
def appointment(self) -> Appointment:
appointment = None
if "appointment" in self.cleaned_data:
appointment = self.cleaned_data.get("appointment")
elif self.instance:
appointment = self.instance.appointment
if not appointment:
self.raise_validation_error("Appointment is required.", INVALID_ERROR)
return appointment
@property
def report_datetime(self) -> datetime | None:
"""Returns report datetime in local timezone (from form
cleaned_data).
"""
report_datetime = None
if "report_datetime" in self.cleaned_data:
report_datetime = self.cleaned_data.get("report_datetime")
elif self.instance:
report_datetime = self.instance.report_datetime
return report_datetime
@property
def report_datetime_utc(self) -> datetime | None:
"""Returns report datetime in UTC timezone"""
if self.report_datetime:
return self.report_datetime.astimezone(ZoneInfo("UTC"))
return None
@property
def appt_datetime_local(self) -> datetime:
"""Returns appt datetime in local timezone"""
return self.appointment.appt_datetime.astimezone(ZoneInfo(settings.TIME_ZONE))
def validate_visit_datetime_in_window_period(self, *args) -> None:
"""Asserts the report_datetime is within the visits lower and
upper boundaries of the visit_schedule.schdule.visit.
See also `edc_visit_schedule`.
"""
if self.report_datetime:
args = [self.appointment, self.report_datetime, self.report_datetime_field_attr]
self.datetime_in_window_or_raise(*args)
def validate_visit_datetime_unique(self: Any) -> None:
"""Assert one visit report per day"""
if self.report_datetime:
qs = self.instance.__class__.objects.filter(
subject_identifier=self.subject_identifier,
report_datetime__date=self.report_datetime_utc.date(),
visit_schedule_name=self.instance.visit_schedule_name,
schedule_name=self.instance.schedule_name,
)
if getattr(self.instance, "id"):
qs = qs.exclude(id=self.instance.id)
if qs.count() > 1:
raise self.raise_validation_error(
{"report_datetime": "Visit report already exist for this date (M)"},
INVALID_ERROR,
)
elif qs.count() == 1:
raise self.raise_validation_error(
{
"report_datetime": "A visit report already exists for this date. "
f"See {qs[0].visit_code}.{qs[0].visit_code_sequence}"
},
INVALID_ERROR,
)
def validate_visit_datetime_not_before_appointment(
self,
) -> None:
"""Asserts the report_datetime is not before the
appt_datetime.
"""
if report_datetime_local := self.report_datetime:
if report_datetime_local.date() < self.appt_datetime_local.date():
appt_datetime_str = formatted_datetime(
self.appt_datetime_local, format_as_date=True
)
self.raise_validation_error(
{
"report_datetime": (
"Invalid. Cannot be before appointment date. "
f"Got appointment date {appt_datetime_str}"
)
},
INVALID_ERROR,
)
def validate_visit_datetime_matches_appt_datetime_at_baseline(self) -> None:
"""Asserts the report_datetime matches the appt_datetime
as baseline.
"""
if is_baseline(instance=self.appointment):
if report_datetime_local := self.report_datetime:
if report_datetime_local.date() != self.appt_datetime_local.date():
appt_datetime_str = formatted_datetime(
self.appt_datetime_local, format_as_date=True
)
self.raise_validation_error(
{
"report_datetime": (
"Invalid. Must match appointment date at baseline. "
"If necessary, change the appointment date and try again. "
f"Got appointment date {appt_datetime_str}"
)
},
INVALID_ERROR,
)
def validate_visits_completed_in_order(self) -> None:
"""Asserts visits are completed in order."""
visit_sequence = self.visit_sequence_cls(appointment=self.appointment)
try:
visit_sequence.enforce_sequence()
except VisitSequenceError as e:
raise forms.ValidationError(e, code=INVALID_ERROR)
def validate_visit_code_sequence_and_reason(self) -> None:
"""Asserts the `reason` makes sense relative to the
visit_code_sequence coming from the appointment.
"""
appointment = self.appointment
reason = self.cleaned_data.get("reason")
if appointment:
if not appointment.visit_code_sequence and reason == UNSCHEDULED:
raise forms.ValidationError(
{"reason": "Invalid. This is not an unscheduled visit. See appointment."},
code=INVALID_ERROR,
)
if (
appointment.visit_code_sequence
and reason != UNSCHEDULED
and EDC_VISIT_TRACKING_ALLOW_MISSED_UNSCHEDULED is False
):
raise forms.ValidationError(
{"reason": "Invalid. This is an unscheduled visit. See appointment."},
code=INVALID_ERROR,
)
# raise if CRF metadata exist
if reason == MISSED_VISIT and self.metadata_exists_for(
entry_status=KEYED,
exclude_models=[get_subject_visit_missed_model_cls()._meta.label_lower],
):
raise forms.ValidationError(
{"reason": "Invalid. Some CRF data has already been submitted."},
code=INVALID_ERROR,
)
def validate_visit_reason(self) -> None:
"""Asserts that reason=missed if appointment is missed"""
if (
self.appointment.appt_timing == MISSED_APPT
and self.cleaned_data.get("reason") != MISSED_VISIT
):
self.raise_validation_error(
{"reason": "Invalid. This appointment was reported as missed"}, INVALID_ERROR
)
if self.validate_missed_visit_reason:
self.required_if(MISSED_VISIT, field="reason", field_required="reason_missed")
self.required_if(
OTHER, field="reason_missed", field_required="reason_missed_other"
)
if self.validate_unscheduled_visit_reason:
if "reason_unscheduled" in self.cleaned_data:
self.applicable_if(
UNSCHEDULED, field="reason", field_applicable="reason_unscheduled"
)
self.required_if(
OTHER,
field="reason_unscheduled",
field_required="reason_unscheduled_other",
)
def metadata_exists_for(
self,
entry_status: str = None,
filter_models: Optional[List[str]] = None,
exclude_models: Optional[List[str]] = None,
) -> int:
"""Returns True if metadata exists for this visit for
the given entry_status.
"""
exclude_opts: dict = {}
filter_opts = deepcopy(self.crf_filter_options)
filter_opts.update(entry_status=entry_status or KEYED)
if filter_models:
filter_opts.update(model__in=filter_models)
if exclude_models:
exclude_opts.update(model__in=exclude_models)
return (
get_crf_metadata_model_cls()
.objects.filter(**filter_opts)
.exclude(**exclude_opts)
.count()
+ get_requisition_metadata_model_cls()
.objects.filter(**filter_opts)
.exclude(**exclude_opts)
.count()
)
@property
def crf_filter_options(self) -> dict:
"""Returns a dictionary of `filter` options when querying
models CrfMetadata / RequisitionMetadata.
"""
return dict(
subject_identifier=self.subject_identifier,
visit_code=self.appointment.visit_code,
visit_code_sequence=self.appointment.visit_code_sequence,
visit_schedule_name=self.appointment.visit_schedule_name,
schedule_name=self.appointment.schedule_name,
entry_status=KEYED,
)