-
Notifications
You must be signed in to change notification settings - Fork 87
/
models.py
1621 lines (1297 loc) · 49.9 KB
/
models.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
"""
Opal Django Models
"""
import datetime
import functools
import hashlib
import itertools
import json
import logging
import random
import os
from django.utils import timezone
from django.db import models, transaction
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.urls import reverse
from django.core.exceptions import FieldDoesNotExist
from django.utils.encoding import force_str
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from opal.core import (
application, exceptions, lookuplists, plugins, patient_lists, tagging
)
from opal import managers
from opal.utils import camelcase_to_underscore, find_template
from opal.core import serialization
from opal.core.fields import ForeignKeyOrFreeText
from opal.core.subrecords import (
episode_subrecords, patient_subrecords, get_subrecord_from_api_name
)
def get_default_episode_type():
app = application.get_app()
return app.default_episode_category
class SerialisableFields(object):
"""
Mixin class that handles the getting of fields
and field types for serialisation/deserialization
"""
@classmethod
def _get_fieldnames_to_serialize(cls):
"""
Return the list of field names we want to serialize.
"""
# TODO update to use the django 1.8 meta api
fieldnames = [f.attname for f in cls._meta.fields]
for name, value in list(vars(cls).items()):
if isinstance(value, ForeignKeyOrFreeText):
fieldnames.append(name)
# Sometimes FKorFT fields are defined on the parent now we have
# core archetypes - find those fields.
ftfk_fields = [f for f in fieldnames if f.endswith('_fk_id')]
for f in ftfk_fields:
if f[:-6] in fieldnames:
continue
fieldnames.append(f[:-6])
fields = cls._meta.get_fields(include_parents=True)
def m2m(x):
"""
Predicate function to determine whether something
is a ManyToMany field
"""
return isinstance(x, (
models.fields.related.ManyToManyField,
models.fields.related.ManyToManyRel
))
many_to_manys = [field.name for field in fields if m2m(field)]
fieldnames = fieldnames + many_to_manys
fieldnames = [
f for f in fieldnames
if not any((f.endswith('_fk_id'), f.endswith('_ft')))
]
return fieldnames
@classmethod
def _get_field_type(cls, name):
try:
return type(cls._meta.get_field(name))
except FieldDoesNotExist:
pass
# TODO: Make this dynamic
if name in ['patient_id', 'episode_id']:
return models.ForeignKey
try:
value = getattr(cls, name)
if isinstance(value, ForeignKeyOrFreeText):
return ForeignKeyOrFreeText
except AttributeError:
pass
raise exceptions.UnexpectedFieldNameError(
'Unexpected fieldname: %s' % name
)
@classmethod
def get_human_readable_type(cls, field_name):
field_type = cls._get_field(field_name)
if isinstance(field_type, models.NullBooleanField):
return "Either True, False or None"
if isinstance(field_type, models.BooleanField):
return "Either True or False"
if isinstance(field_type, models.DateTimeField):
return "Date & Time"
if isinstance(field_type, models.DateField):
return "Date"
numeric_fields = (
models.AutoField,
models.BigIntegerField,
models.IntegerField,
models.FloatField,
models.DecimalField,
)
if isinstance(field_type, numeric_fields):
return "Number"
if isinstance(field_type, ForeignKeyOrFreeText):
t = "Normally coded as a {} but free text entries are possible."
return t.format(field_type.foreign_model._meta.object_name.lower())
related_fields = (
models.ForeignKey, models.ManyToManyField,
)
if isinstance(field_type, related_fields):
if isinstance(field_type, models.ForeignKey):
t = "One of the {}"
else:
t = "Some of the {}"
related = field_type.remote_field.model
return t.format(related._meta.verbose_name_plural.title())
enum = cls.get_field_enum(field_name)
if enum:
return "One of {}".format(",".join([force_str(e) for e in enum]))
else:
return "Text Field"
@classmethod
def _get_field(cls, name):
try:
return cls._meta.get_field(name)
except FieldDoesNotExist:
return getattr(cls, name)
@classmethod
def _get_field_title(cls, name):
field = cls._get_field(name)
if isinstance(field, models.ManyToOneRel):
field_name = field.related_model._meta.verbose_name_plural
else:
field_name = field.verbose_name
if field_name.islower():
field_name = field_name.title()
return field_name
@classmethod
def _get_field_default(cls, name):
field = cls._get_field(name)
if isinstance(field, models.ManyToOneRel):
default = []
else:
default = field.get_default()
# for blank fields the result is a blank string, lets just remove that
if default == '':
return None
if isinstance(default, datetime.date):
raise exceptions.APIError(
"{0}.{1} returned a date as a default, Opal currently does "
"not support sending dates/datetimes as defaults".format(
cls, name
)
)
return default
@classmethod
def get_field_description(cls, name):
field = cls._get_field(name)
description = getattr(field, 'help_text', "")
if description:
return description
@classmethod
def get_field_enum(cls, name):
field = cls._get_field(name)
choices = getattr(field, "choices", [])
if choices:
return [i[0] for i in choices]
@classmethod
def get_lookup_list_api_name(cls, field_name):
lookup_list = None
field_type = cls._get_field_type(field_name)
if field_type == ForeignKeyOrFreeText:
fld = getattr(cls, field_name)
lookup_list = camelcase_to_underscore(
fld.foreign_model.get_api_name()
)
elif field_type == models.fields.related.ManyToManyField:
related_model = getattr(cls, field_name).field.related_model
if issubclass(related_model, lookuplists.LookupList):
return related_model.get_api_name()
return lookup_list
@classmethod
def build_schema_for_field_name(cls, field_name):
getter = getattr(cls, 'get_field_type_for_' + field_name, None)
if getter is None:
field = cls._get_field_type(field_name)
if field in [models.CharField, ForeignKeyOrFreeText]:
field_type = 'string'
else:
field_type = camelcase_to_underscore(field.__name__[:-5])
else:
field_type = getter()
title = cls._get_field_title(field_name)
default = cls._get_field_default(field_name)
field = {
'name': field_name,
'title': title,
'type': field_type,
'lookup_list': cls.get_lookup_list_api_name(field_name),
'default': default,
'model': cls.__name__,
'description': cls.get_field_description(field_name),
'enum': cls.get_field_enum(field_name)
}
return field
@classmethod
def build_field_schema(cls):
field_schema = []
for fieldname in cls._get_fieldnames_to_serialize():
if fieldname in ['id', 'patient_id', 'episode_id']:
continue
field_schema.append(cls.build_schema_for_field_name(fieldname))
return field_schema
class UpdatesFromDictMixin(SerialisableFields):
"""
Mixin class to provide the deserialization
fields, as well as update logic for our JSON APIs.
"""
@classmethod
def _get_fieldnames_to_extract(cls):
"""
Return a list of fieldname to extract - which means dumping
PID fields.
"""
fieldnames = cls._get_fieldnames_to_serialize()
if hasattr(cls, 'pid_fields'):
for fname in cls.pid_fields:
if fname in fieldnames:
fieldnames.remove(fname)
return fieldnames
@classmethod
def get_field_type_for_consistency_token(cls):
return 'token'
def set_consistency_token(self):
self.consistency_token = '%08x' % random.randrange(16**8)
def get_lookup_list_values_for_names(self, lookuplist, names):
ct = ContentType.objects.get_for_model(lookuplist)
return lookuplist.objects.filter(
models.Q(name__in=names) | models.Q(
synonyms__name__in=names, synonyms__content_type=ct
)
)
def save_many_to_many(self, name, values, field_type):
field = getattr(self, name)
new_lookup_values = self.get_lookup_list_values_for_names(
field.model, values
)
new_values = new_lookup_values.values_list("id", flat=True)
existing_values = field.all().values_list("id", flat=True)
to_add = set(new_values) - set(existing_values)
to_remove = set(existing_values) - set(new_values)
if len(set(new_values)) != len(set(values)):
# the only way this should happen is if one of the incoming
# values is a synonym for another incoming value so lets check this
synonym_found = False
new_names = new_lookup_values.filter(name__in=values)
values_set = set(values)
for new_name in new_names:
synonyms = set(new_name.synonyms.all().values_list(
"name", flat=True)
)
if values_set.intersection(synonyms):
synonym_found = True
logging.info("found synonym {0} for {1}".format(
synonyms, values_set)
)
break
if not synonym_found:
error_msg = 'Unexpected fieldname(s): {}'.format(values)
raise exceptions.APIError(error_msg)
field.add(*to_add)
field.remove(*to_remove)
def update_from_dict(self, data, user, force=False, fields=None):
logging.info("updating {0} with {1} for {2}".format(
self.__class__.__name__, data, user
))
if fields is None:
fields = set(self._get_fieldnames_to_serialize())
if self.consistency_token and not force:
try:
consistency_token = data.pop('consistency_token')
except KeyError:
msg = 'Missing field (consistency_token) for {}'
raise exceptions.MissingConsistencyTokenError(
msg.format(self.__class__.__name__)
)
if consistency_token != self.consistency_token:
raise exceptions.ConsistencyError
post_save = []
unknown_fields = set(data.keys()) - fields
if unknown_fields:
raise exceptions.APIError(
'Unexpected fieldname(s): %s' % list(unknown_fields))
for name in fields:
value = data.get(name, None)
if name == 'consistency_token':
continue # shouldn't be needed - Javascripts bug?
setter = getattr(self, 'set_' + name, None)
if setter is not None:
setter(value, user, data)
else:
if name in data:
field_type = self._get_field_type(name)
if field_type == models.fields.related.ManyToManyField:
post_save.append(
functools.partial(self.save_many_to_many,
name,
value,
field_type))
else:
DateTimeField = models.fields.DateTimeField
if value and field_type == models.fields.DateField:
value = serialization.deserialize_date(value)
elif value and field_type == DateTimeField:
value = serialization.deserialize_datetime(value)
elif value and field_type == models.fields.TimeField:
value = serialization.deserialize_time(value)
setattr(self, name, value)
self.set_consistency_token()
self.save()
for some_func in post_save:
some_func()
class ToDictMixin(SerialisableFields):
""" serialises a model to a dictionary
"""
def to_dict(self, user, fields=None):
"""
Allow a subset of FIELDNAMES
"""
if fields is None:
fields = self._get_fieldnames_to_serialize()
d = {}
for name in fields:
getter = getattr(self, 'get_' + name, None)
if getter is not None:
value = getter(user)
else:
field_type = self._get_field_type(name)
if field_type == models.fields.related.ManyToManyField:
qs = getattr(self, name).all()
value = [i.to_dict(user) for i in qs]
else:
value = getattr(self, name)
d[name] = value
return d
class Filter(models.Model):
"""
Saved filters for users extracting data.
"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
criteria = models.TextField()
def to_dict(self):
return dict(
id=self.pk,
name=self.name,
criteria=json.loads(self.criteria)
)
def update_from_dict(self, data):
self.criteria = json.dumps(data['criteria'])
self.name = data['name']
self.save()
class ContactNumber(models.Model):
name = models.CharField(max_length=255)
number = models.CharField(max_length=255)
def __str__(self):
return '{0}: {1}'.format(self.name, self.number)
class Synonym(models.Model):
name = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = (('name', 'content_type'))
def __str__(self):
return self.name
class Patient(models.Model):
class Meta:
verbose_name = _("Patient")
verbose_name_plural = _("Patients")
objects = managers.PatientQueryset.as_manager()
def __str__(self):
return 'Patient {0}'.format(self.id)
def get_absolute_url(self):
"""
Return the URL for this patient
"""
return '/#/patient/{}'.format(self.id)
def demographics(self):
"""
Shortcut method to return this patient's demographics.
"""
return self.demographics_set.get()
def create_episode(self, **kwargs):
return self.episode_set.create(**kwargs)
def get_active_episode(self):
for episode in self.episode_set.order_by('id').reverse():
if episode.active:
return episode
return None
@transaction.atomic()
def bulk_update(self, dict_of_list_of_upgrades, user,
episode=None, force=False):
"""
takes in a dictionary of api name to a list of fields and
creates the required subrecords. If passed an episode
sub record but no episode it will create an episode
and attatch it.
e.g. {"allergies": [
{"drug": "paracetomol"}
{"drug": "aspirin"}
],
"diagnosis":[
{
"condition": "some test",
"details": "some details"
}
]
}
"""
if "demographics" not in dict_of_list_of_upgrades:
if not self.id:
dict_of_list_of_upgrades["demographics"] = [{}]
if not self.id:
self.save()
#
# We never want to be in the position where we don't have an episode.
# If this patient has never had an episode, we create one now.
# If the patient has preexisting episodes, we will either use an
# episode passed in to us as a kwarg, or create a fresh episode for
# this bulk update once we're sure we have episode subrecord data to
# save.
#
if not self.episode_set.exists():
episode = self.create_episode()
for api_name, list_of_upgrades in dict_of_list_of_upgrades.items():
if(api_name == "tagging"):
episode.set_tag_names_from_tagging_dict(
list_of_upgrades[0], user
)
continue
model = get_subrecord_from_api_name(api_name=api_name)
if model in episode_subrecords():
if episode is None:
episode = self.create_episode()
episode.save()
model.bulk_update_from_dicts(episode, list_of_upgrades, user,
force=force)
else:
# it's a patient subrecord
model.bulk_update_from_dicts(self, list_of_upgrades, user,
force=force)
def to_dict(self, user):
d = {
'id': self.id,
'episodes': {episode.id: episode.to_dict(user) for episode in
self.episode_set.all()}
}
for model in patient_subrecords():
subrecords = model.objects.filter(patient_id=self.id)
d[model.get_api_name()] = [
subrecord.to_dict(user) for subrecord in subrecords
]
return d
def update_from_demographics_dict(self, demographics_data, user):
self.demographics().update_from_dict(demographics_data, user)
def save(self, *args, **kwargs):
created = not bool(self.id)
super(Patient, self).save(*args, **kwargs)
if created:
for subclass in patient_subrecords():
if subclass._is_singleton:
subclass.objects.create(patient=self)
class PatientRecordAccess(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
def to_dict(self, user):
return dict(
patient=self.patient.id,
datetime=self.created,
username=self.user.username
)
class ExternallySourcedModel(models.Model):
# the system upstream that contains this model
external_system = models.CharField(
blank=True,
null=True,
max_length=255,
verbose_name=_("External System")
)
# the identifier used by the upstream system
external_identifier = models.CharField(
blank=True, null=True, max_length=255,
verbose_name=_("Extenal Identifier")
)
class Meta:
abstract = True
@classmethod
def get_modal_footer_template(cls):
return "partials/_sourced_modal_footer.html"
class TrackedModel(models.Model):
# these fields are set automatically from REST requests via
# updates from dict and the getter, setter properties, where available
# (from the update from dict mixin)
created = models.DateTimeField(
blank=True,
null=True,
verbose_name=_("Created")
)
updated = models.DateTimeField(
blank=True, null=True, verbose_name=_("Updated")
)
created_by = models.ForeignKey(
User, blank=True, null=True,
related_name="created_%(app_label)s_%(class)s_subrecords",
on_delete=models.SET_NULL,
verbose_name=_("Created By")
)
updated_by = models.ForeignKey(
User, blank=True, null=True,
related_name="updated_%(app_label)s_%(class)s_subrecords",
on_delete=models.SET_NULL,
verbose_name=_("Updated By")
)
class Meta:
abstract = True
def set_created_by_id(self, incoming_value, user, *args, **kwargs):
if not self.id:
# this means if a record is not created by the api, it will not
# have a created by id
self.created_by = user
def set_updated_by_id(self, incoming_value, user, *args, **kwargs):
if self.id:
self.updated_by = user
def set_updated(self, incoming_value, user, *args, **kwargs):
if self.id:
self.updated = timezone.now()
def set_created(self, incoming_value, user, *args, **kwargs):
if not self.id:
# this means if a record is not created by the api, it will not
# have a created timestamp
self.created = timezone.now()
class Episode(UpdatesFromDictMixin, TrackedModel):
"""
An individual episode of care.
A patient may have many episodes of care, but this maps to one occasion
on which they found themselves on "The List".
"""
category_name = models.CharField(
max_length=200,
default=get_default_episode_type,
verbose_name=_("Category Name")
)
patient = models.ForeignKey(
Patient, on_delete=models.CASCADE, verbose_name=_("Patient")
)
active = models.BooleanField(
default=False, verbose_name=_("Active")
)
start = models.DateField(
null=True, blank=True, verbose_name=_("Start")
)
end = models.DateField(
blank=True, null=True, verbose_name=_("End")
)
consistency_token = models.CharField(
max_length=8, verbose_name=_("Consistency Token")
)
# stage is at what stage of an episode flow is the
# patient at
stage = models.CharField(
max_length=256, null=True, blank=True, verbose_name=_("Stage")
)
class Meta:
verbose_name = _("Episode")
verbose_name_plural = _("Episodes")
objects = managers.EpisodeQueryset.as_manager()
def __init__(self, *args, **kwargs):
super(Episode, self).__init__(*args, **kwargs)
self.__original_active = self.active
def __str__(self):
return 'Episode {0}: {1} - {2}'.format(
self.pk, self.start, self.end
)
def get_absolute_url(self):
"""
Return the URL for this Episode
"""
return '/#/patient/{}/{}'.format(self.patient_id, self.id)
def save(self, *args, **kwargs):
created = not bool(self.id)
current_active_value = self.active
category_active_value = self.category.is_active()
if current_active_value != category_active_value: # Disagreement
if current_active_value != self.__original_active:
# The value of self.active has been set by some code somewhere
# not by __init__() e.g. the original database value at the
# time of instance initalization.
#
# Rather than overriding this silently we should raise a
# ValueError.
msg = "Value of Episode.active has been set to {} but " \
"category.is_active() returns {}"
raise ValueError(
msg.format(current_active_value, category_active_value)
)
self.active = category_active_value
super(Episode, self).save(*args, **kwargs)
# Re-set this in case we changed it once post initialization and then
# the user subsequently saves this instance again
self.__original_active = self.active
if created:
for subclass in episode_subrecords():
if subclass._is_singleton:
subclass.objects.create(episode=self)
@property
def category(self):
from opal.core import episodes
categories = episodes.EpisodeCategory.filter(
display_name=self.category_name
)
if len(categories) == 0:
msg = "Unable to find EpisodeCategory for category name {0}"
msg = msg.format(self.category_name)
raise exceptions.UnexpectedEpisodeCategoryNameError(msg)
else:
category = categories[0]
return category(self)
def visible_to(self, user):
"""
Predicate function to determine whether this episode is visible to
a certain user.
The logic for visibility is held in individual
opal.core.episodes.EpisodeCategory implementations.
"""
return self.category.episode_visible_to(self, user)
def set_stage(self, stage, user, data):
"""
Setter for Episode.stage
Validates that the stage being set is appropriate for the category
and raises ValueError if not.
"""
self.category.set_stage(stage, user, data)
def set_tag_names(self, tag_names, user):
"""
1. Special case mine
2. Archive dangling tags not in our current list.
3. Add new tags.
4. Ensure that we're setting the parents of child tags
5. There is no step 6.
"""
if "mine" not in tag_names:
self.tagging_set.filter(user=user,
value='mine').update(archived=True)
else:
tag, created = self.tagging_set.get_or_create(
value='mine', user=user
)
if not created:
tag.archived = False
tag.save()
tag_names = [t for t in tag_names if not t == 'mine']
# nuke everything and start from fresh so we don't have
# to deal with childless parents
self.tagging_set.exclude(value="mine").filter(archived=False).update(
archived=True,
updated_by=user,
updated=timezone.now()
)
parents = []
for tag in tag_names:
parent = tagging.parent(tag)
if parent:
parents.append(parent)
tag_names += parents
for tag in tag_names:
tagg, created = self.tagging_set.get_or_create(
value=tag, episode=self
)
if created:
tagg.created_by = user
tagg.created = timezone.now()
else:
tagg.archived = False
tagg.updated_by = user
tagg.updated = timezone.now()
tagg.save()
def set_tag_names_from_tagging_dict(self, tagging_dict, user):
"""
Given a dictionary of {tag_name: True} pairs, set tag names
according to those tags which are truthy.
"""
tag_names = [n for n, v in list(tagging_dict.items()) if v is True]
return self.set_tag_names(tag_names, user)
def tagging_dict(self, user):
tag_names = self.get_tag_names(user)
tagging_dict = {i: True for i in tag_names}
tagging_dict["id"] = self.id
return [tagging_dict]
def get_tag_names(self, user, historic=False):
"""
Return the current active tag names for this Episode as strings.
"""
qs = self.tagging_set.filter(Q(user=user) | Q(user=None))
if not historic:
qs = qs.filter(archived=False)
return list(qs.values_list("value", flat=True))
def to_dict(self, user, shallow=False):
"""
Serialisation to JSON for Episodes
"""
d = {
'id' : self.id,
'category_name' : self.category_name,
'active' : self.active,
'consistency_token': self.consistency_token,
'start' : self.start,
'end' : self.end,
'stage' : self.stage,
}
if shallow:
return d
for model in patient_subrecords():
subrecords = model.objects.filter(patient_id=self.patient.id)
d[model.get_api_name()] = [
subrecord.to_dict(user) for subrecord in subrecords
]
for model in episode_subrecords():
subrecords = model.objects.filter(episode_id=self.id)
d[model.get_api_name()] = [
subrecord.to_dict(user) for subrecord in subrecords
]
d['tagging'] = self.tagging_dict(user)
return d
class Subrecord(UpdatesFromDictMixin, ToDictMixin, TrackedModel, models.Model):
_is_singleton = False
_advanced_searchable = True
_exclude_from_subrecords = False
consistency_token = models.CharField(
max_length=8, verbose_name=_("Consistency Token")
)
class Meta:
abstract = True
def __str__(self):
if self.created:
return '{0}: {1} {2}'.format(
self.get_api_name(), self.id, self.created
)
else:
return '{0}: {1}'.format(self.get_api_name(), self.id)
@classmethod
def get_api_name(cls):
return camelcase_to_underscore(cls._meta.object_name)
@classmethod
def get_icon(cls):
return getattr(cls, '_icon', None)
@classmethod
def get_display_name(cls):
if cls._meta.verbose_name.islower():
return cls._meta.verbose_name.title()
return cls._meta.verbose_name
@classmethod
def _get_template(cls, template, prefixes=None):
template_locations = []
if prefixes is None:
prefixes = []
for prefix in prefixes:
template_locations.append(
template.format(os.path.join(prefix, cls.get_api_name()))
)
template_locations.append(template.format(cls.get_api_name()))
return find_template(template_locations)
@classmethod
def get_display_template(cls, prefixes=None):
"""
Return the active display template for our record
"""
if prefixes is None:
prefixes = []
return cls._get_template(
os.path.join("records", "{}.html"),
prefixes=prefixes
)
@classmethod
def get_detail_template(cls, prefixes=None):
"""
Return the active detail template for our record
"""
file_locations = [
os.path.join('records', '{0}_detail.html'),
os.path.join('records', '{0}.html'),
]
if prefixes is None:
prefixes = []
templates = []
for prefix in prefixes:
for file_location in file_locations:
templates.append(file_location.format(
os.path.join(prefix, cls.get_api_name())
))
for file_location in file_locations:
templates.append(
file_location.format(cls.get_api_name())
)
return find_template(templates)
@classmethod
def get_form_template(cls, prefixes=None):
if prefixes is None:
prefixes = []
return cls._get_template(
template=os.path.join("forms", "{}_form.html"),
prefixes=prefixes
)
@classmethod