1
|
# -*- coding: utf-8 -*-
|
2
|
|
3
|
import logging
|
4
|
import os
|
5
|
|
6
|
from datetime import datetime, date
|
7
|
from dateutil.relativedelta import relativedelta
|
8
|
|
9
|
from django import forms
|
10
|
from django.conf import settings
|
11
|
from django.db import models
|
12
|
from django.contrib.auth.models import User
|
13
|
|
14
|
import reversion
|
15
|
|
16
|
from calebasse.choices import LARGE_REGIME_CHOICES
|
17
|
from calebasse.models import PhoneNumberField, ZipCodeField
|
18
|
from calebasse.personnes.models import People
|
19
|
from calebasse.ressources.models import (ServiceLinkedAbstractModel,
|
20
|
NamedAbstractModel, Service)
|
21
|
from calebasse.actes.validation import are_all_acts_of_the_day_locked
|
22
|
|
23
|
DEFAULT_ACT_NUMBER_DIAGNOSTIC = 6
|
24
|
DEFAULT_ACT_NUMBER_TREATMENT = 30
|
25
|
DEFAULT_ACT_NUMBER_PROLONGATION = 10
|
26
|
VALIDITY_PERIOD_TREATMENT_HEALTHCARE_DAYS = 0
|
27
|
VALIDITY_PERIOD_TREATMENT_HEALTHCARE_MONTHS = 0
|
28
|
VALIDITY_PERIOD_TREATMENT_HEALTHCARE_YEARS = 1
|
29
|
|
30
|
logger = logging.getLogger('calebasse.dossiers')
|
31
|
|
32
|
|
33
|
class HealthCare(models.Model):
|
34
|
|
35
|
class Meta:
|
36
|
app_label = 'dossiers'
|
37
|
|
38
|
start_date = models.DateField(verbose_name=u"Date de début")
|
39
|
patient = models.ForeignKey('dossiers.PatientRecord',
|
40
|
verbose_name=u'Dossier patient')
|
41
|
created = models.DateTimeField(u'Création', auto_now_add=True)
|
42
|
author = \
|
43
|
models.ForeignKey(User,
|
44
|
verbose_name=u'Auteur')
|
45
|
comment = models.TextField(max_length=3000, blank=True, null=True, verbose_name=u"Commentaire")
|
46
|
|
47
|
def get_nb_acts_cared(self):
|
48
|
return len(self.act_set.all())
|
49
|
|
50
|
|
51
|
class CmppHealthCareDiagnostic(HealthCare):
|
52
|
|
53
|
class Meta:
|
54
|
app_label = 'dossiers'
|
55
|
|
56
|
act_number = models.IntegerField(default=DEFAULT_ACT_NUMBER_DIAGNOSTIC, verbose_name=u"Nombre d'actes couverts")
|
57
|
|
58
|
def get_act_number(self):
|
59
|
return self.act_number
|
60
|
|
61
|
def set_act_number(self, value):
|
62
|
if value < self.get_nb_acts_cared():
|
63
|
raise Exception("La valeur doit être supérieur au "
|
64
|
"nombre d'actes déjà pris en charge")
|
65
|
self.act_number = value
|
66
|
self.save()
|
67
|
|
68
|
def save(self, **kwargs):
|
69
|
self.start_date = \
|
70
|
datetime(self.start_date.year, self.start_date.month,
|
71
|
self.start_date.day)
|
72
|
super(CmppHealthCareDiagnostic, self).save(**kwargs)
|
73
|
|
74
|
|
75
|
class CmppHealthCareTreatment(HealthCare):
|
76
|
|
77
|
class Meta:
|
78
|
app_label = 'dossiers'
|
79
|
|
80
|
act_number = models.IntegerField(default=DEFAULT_ACT_NUMBER_TREATMENT,
|
81
|
verbose_name=u"Nombre d'actes couverts")
|
82
|
end_date = models.DateField(verbose_name=u"Date de fin")
|
83
|
prolongation = models.IntegerField(default=0,
|
84
|
verbose_name=u'Prolongation')
|
85
|
|
86
|
def get_act_number(self):
|
87
|
if self.is_extended():
|
88
|
return self.act_number + self.prolongation
|
89
|
return self.act_number
|
90
|
|
91
|
def set_act_number(self, value):
|
92
|
if value < self.get_nb_acts_cared():
|
93
|
raise Exception("La valeur doit être supérieur au "
|
94
|
"nombre d'actes déjà pris en charge")
|
95
|
self.act_number = value
|
96
|
self.save()
|
97
|
|
98
|
def is_extended(self):
|
99
|
if self.prolongation > 0:
|
100
|
return True
|
101
|
return False
|
102
|
|
103
|
def add_prolongation(self, value=None):
|
104
|
if not value:
|
105
|
value = DEFAULT_ACT_NUMBER_PROLONGATION
|
106
|
if self.is_extended():
|
107
|
raise Exception(u'Prise en charge déja prolongée')
|
108
|
self.prolongation = value
|
109
|
self.save()
|
110
|
|
111
|
def save(self, **kwargs):
|
112
|
self.start_date = \
|
113
|
datetime(self.start_date.year, self.start_date.month,
|
114
|
self.start_date.day)
|
115
|
self.end_date = self.start_date + \
|
116
|
relativedelta(years=VALIDITY_PERIOD_TREATMENT_HEALTHCARE_YEARS) + \
|
117
|
relativedelta(months=VALIDITY_PERIOD_TREATMENT_HEALTHCARE_MONTHS) + \
|
118
|
relativedelta(days=VALIDITY_PERIOD_TREATMENT_HEALTHCARE_DAYS)
|
119
|
super(CmppHealthCareTreatment, self).save(**kwargs)
|
120
|
|
121
|
|
122
|
class SessadHealthCareNotification(HealthCare):
|
123
|
|
124
|
class Meta:
|
125
|
app_label = 'dossiers'
|
126
|
|
127
|
end_date = models.DateField()
|
128
|
|
129
|
def save(self, **kwargs):
|
130
|
self.start_date = \
|
131
|
datetime(self.start_date.year, self.start_date.month,
|
132
|
self.start_date.day)
|
133
|
self.end_date = \
|
134
|
datetime(self.end_date.year, self.end_date.month,
|
135
|
self.end_date.day)
|
136
|
super(SessadHealthCareNotification, self).save(**kwargs)
|
137
|
|
138
|
reversion.register(CmppHealthCareDiagnostic, follow=['healthcare_ptr'])
|
139
|
reversion.register(CmppHealthCareTreatment, follow=['healthcare_ptr'])
|
140
|
reversion.register(SessadHealthCareNotification, follow=['healthcare_ptr'])
|
141
|
|
142
|
class Status(NamedAbstractModel):
|
143
|
|
144
|
class Meta:
|
145
|
app_label = 'dossiers'
|
146
|
verbose_name = u"Statut d'un état"
|
147
|
verbose_name_plural = u"Statuts d'un état"
|
148
|
|
149
|
type = models.CharField(max_length=80)
|
150
|
services = models.ManyToManyField('ressources.Service')
|
151
|
|
152
|
|
153
|
class FileState(models.Model):
|
154
|
|
155
|
class Meta:
|
156
|
app_label = 'dossiers'
|
157
|
verbose_name = u'Etat du dossier patient'
|
158
|
verbose_name_plural = u'Etats du dossier patient'
|
159
|
|
160
|
patient = models.ForeignKey('dossiers.PatientRecord',
|
161
|
verbose_name=u'Dossier patient')
|
162
|
status = models.ForeignKey('dossiers.Status', verbose_name=u'Statut')
|
163
|
created = models.DateTimeField(u'Création', auto_now_add=True)
|
164
|
date_selected = models.DateTimeField()
|
165
|
author = \
|
166
|
models.ForeignKey(User,
|
167
|
verbose_name=u'Auteur')
|
168
|
comment = models.TextField(max_length=3000, blank=True, null=True)
|
169
|
previous_state = models.ForeignKey('FileState',
|
170
|
verbose_name=u'Etat précédent', blank=True, null=True)
|
171
|
|
172
|
def get_next_state(self):
|
173
|
try:
|
174
|
return FileState.objects.get(previous_state=self)
|
175
|
except:
|
176
|
return None
|
177
|
|
178
|
def save(self, **kwargs):
|
179
|
self.date_selected = \
|
180
|
datetime(self.date_selected.year,
|
181
|
self.date_selected.month, self.date_selected.day)
|
182
|
super(FileState, self).save(**kwargs)
|
183
|
|
184
|
def __unicode__(self):
|
185
|
return self.status.name + ' ' + str(self.date_selected)
|
186
|
|
187
|
def delete(self, *args, **kwargs):
|
188
|
next_state = self.get_next_state()
|
189
|
if next_state and self.previous_state:
|
190
|
next_state.previous_state = self.previous_state
|
191
|
next_state.save()
|
192
|
if self.patient.last_state == self:
|
193
|
self.patient.last_state = self.previous_state
|
194
|
self.patient.save()
|
195
|
super(FileState, self).delete(*args, **kwargs)
|
196
|
|
197
|
class PatientAddress(models.Model):
|
198
|
|
199
|
display_name = models.CharField(max_length=276,
|
200
|
verbose_name=u'Adresse complète', editable=False)
|
201
|
phone = PhoneNumberField(verbose_name=u"Téléphone", blank=True, null=True)
|
202
|
fax = PhoneNumberField(verbose_name=u"Fax", blank=True, null=True)
|
203
|
place_of_life = models.BooleanField(verbose_name=u"Lieu de vie")
|
204
|
number = models.CharField(max_length=12,
|
205
|
verbose_name=u"Numéro", blank=True, null=True)
|
206
|
street = models.CharField(max_length=100,
|
207
|
verbose_name=u"Rue", blank=True, null=True)
|
208
|
address_complement = models.CharField(max_length=100,
|
209
|
blank=True, null=True,
|
210
|
verbose_name=u"Complément d'adresse")
|
211
|
zip_code = ZipCodeField(verbose_name=u"Code postal", blank=True, null=True)
|
212
|
city = models.CharField(max_length=60,
|
213
|
verbose_name=u"Ville", blank=True, null=True)
|
214
|
comment = models.TextField(verbose_name=u"Commentaire",
|
215
|
null=True, blank=True)
|
216
|
|
217
|
def __unicode__(self):
|
218
|
return self.display_name
|
219
|
|
220
|
def save(self, **kwargs):
|
221
|
self.display_name = "%s %s, %s %s" % (self.number, self.street, self.zip_code, self.city)
|
222
|
super(PatientAddress, self).save(**kwargs)
|
223
|
|
224
|
|
225
|
class PatientContact(People):
|
226
|
class Meta:
|
227
|
verbose_name = u'Contact patient'
|
228
|
verbose_name_plural = u'Contacts patient'
|
229
|
|
230
|
mobile = PhoneNumberField(verbose_name=u"Téléphone mobile", blank=True, null=True)
|
231
|
# carte vitale
|
232
|
social_security_id = models.CharField(max_length=13, verbose_name=u"NIR",
|
233
|
null=True, blank=True)
|
234
|
birthdate = models.DateField(verbose_name=u"Date de naissance",
|
235
|
null=True, blank=True)
|
236
|
twinning_rank = models.IntegerField(verbose_name=u"Rang (gémellité)",
|
237
|
null=True, blank=True)
|
238
|
thirdparty_payer = models.BooleanField(verbose_name=u'Tiers-payant',
|
239
|
default=False)
|
240
|
begin_rights = models.DateField(verbose_name=u"Début de droits",
|
241
|
null=True, blank=True)
|
242
|
end_rights = models.DateField(verbose_name=u"Fin de droits",
|
243
|
null=True, blank=True)
|
244
|
health_center = models.ForeignKey('ressources.HealthCenter',
|
245
|
verbose_name=u"Centre d'assurance maladie",
|
246
|
null=True, blank=True)
|
247
|
|
248
|
addresses = models.ManyToManyField('PatientAddress', verbose_name=u"Adresses")
|
249
|
contact_comment = models.TextField(verbose_name=u"Commentaire",
|
250
|
null=True, blank=True)
|
251
|
|
252
|
def get_control_key(self):
|
253
|
if self.social_security_id:
|
254
|
return (97 - (int(self.social_security_id) % 97))
|
255
|
return None
|
256
|
|
257
|
|
258
|
class PatientRecordManager(models.Manager):
|
259
|
def for_service(self, service):
|
260
|
return self.filter(service=service)
|
261
|
|
262
|
class PatientRecord(ServiceLinkedAbstractModel, PatientContact):
|
263
|
objects = PatientRecordManager()
|
264
|
|
265
|
class Meta:
|
266
|
verbose_name = u'Dossier'
|
267
|
verbose_name_plural = u'Dossiers'
|
268
|
|
269
|
created = models.DateTimeField(u'création', auto_now_add=True)
|
270
|
creator = \
|
271
|
models.ForeignKey(User,
|
272
|
verbose_name=u'Créateur dossier patient',
|
273
|
editable=True)
|
274
|
policyholder = models.ForeignKey('PatientContact',
|
275
|
null=True, blank=True,
|
276
|
verbose_name="Assuré", related_name="+",
|
277
|
on_delete=models.SET_NULL)
|
278
|
contacts = models.ManyToManyField('PatientContact',
|
279
|
related_name='contact_of')
|
280
|
nationality = models.CharField(verbose_name=u"Nationalité",
|
281
|
max_length=70, null=True, blank=True)
|
282
|
paper_id = models.CharField(max_length=6,
|
283
|
verbose_name=u"N° dossier papier",
|
284
|
null=True, blank=True)
|
285
|
last_state = models.ForeignKey(FileState, related_name='+',
|
286
|
null=True, on_delete=models.SET_NULL)
|
287
|
comment = models.TextField(verbose_name=u"Commentaire",
|
288
|
null=True, blank=True, default=None)
|
289
|
pause = models.BooleanField(verbose_name=u"Pause facturation",
|
290
|
default=False)
|
291
|
socialisation_durations = models.ManyToManyField('ressources.SocialisationDuration',
|
292
|
related_name='socialisation_duration_of')
|
293
|
mdph_requests = models.ManyToManyField('ressources.MDPHRequest',
|
294
|
related_name='mdph_requests_of')
|
295
|
mdph_responses = models.ManyToManyField('ressources.MDPHResponse',
|
296
|
related_name='mdph_responses_of')
|
297
|
|
298
|
# Physiology and health data
|
299
|
size = models.IntegerField(verbose_name=u"Taille (cm)",
|
300
|
null=True, blank=True, default=None)
|
301
|
weight = models.IntegerField(verbose_name=u"Poids (g)",
|
302
|
null=True, blank=True, default=None)
|
303
|
pregnancy_term = models.IntegerField(verbose_name=u"Terme en semaines",
|
304
|
null=True, blank=True, default=None)
|
305
|
cranium_perimeter = models.DecimalField(verbose_name=u"Périmètre cranien", max_digits=5, decimal_places=2,
|
306
|
null=True, blank=True, default=None)
|
307
|
chest_perimeter = models.DecimalField(verbose_name=u"Périmètre thoracique", max_digits=5, decimal_places=2,
|
308
|
null=True, blank=True, default=None)
|
309
|
apgar_score_one = models.IntegerField(verbose_name=u"Test d'Apgar (1)",
|
310
|
null=True, blank=True, default=None)
|
311
|
apgar_score_two = models.IntegerField(verbose_name=u"Test d'Apgar (5)",
|
312
|
null=True, blank=True, default=None)
|
313
|
mises_1 = models.ManyToManyField('ressources.CodeCFTMEA', related_name="mises1",
|
314
|
verbose_name=u"Axe I : catégories cliniques",
|
315
|
null=True, blank=True, default=None)
|
316
|
mises_2 = models.ManyToManyField('ressources.CodeCFTMEA', related_name="mises2",
|
317
|
verbose_name=u"Axe II : facteurs organiques",
|
318
|
null=True, blank=True, default=None)
|
319
|
mises_3 = models.ManyToManyField('ressources.CodeCFTMEA', related_name="mises3",
|
320
|
verbose_name=u"Axe II : facteurs environnementaux",
|
321
|
null=True, blank=True, default=None)
|
322
|
|
323
|
# Inscription motive
|
324
|
analysemotive = models.ForeignKey('ressources.AnalyseMotive',
|
325
|
verbose_name=u"Motif (analysé)",
|
326
|
null=True, blank=True, default=None)
|
327
|
familymotive = models.ForeignKey('ressources.FamilyMotive',
|
328
|
verbose_name=u"Motif (famille)",
|
329
|
null=True, blank=True, default=None)
|
330
|
provenance = models.ForeignKey('ressources.Provenance',
|
331
|
verbose_name=u"Provenance",
|
332
|
null=True, blank=True, default=None)
|
333
|
advicegiver = models.ForeignKey('ressources.AdviceGiver',
|
334
|
verbose_name=u"Conseilleur",
|
335
|
null=True, blank=True, default=None)
|
336
|
|
337
|
# Family
|
338
|
sibship_place = models.IntegerField(verbose_name=u"Place dans la fratrie",
|
339
|
null=True, blank=True, default=None)
|
340
|
nb_children_family = models.IntegerField(verbose_name=u"Nombre d'enfants dans la fratrie",
|
341
|
null=True, blank=True, default=None)
|
342
|
parental_authority = models.ForeignKey('ressources.ParentalAuthorityType',
|
343
|
verbose_name=u"Autorité parentale",
|
344
|
null=True, blank=True, default=None)
|
345
|
family_situation = models.ForeignKey('ressources.FamilySituationType',
|
346
|
verbose_name=u"Situation familiale",
|
347
|
null=True, blank=True, default=None)
|
348
|
child_custody = models.ForeignKey('ressources.ParentalCustodyType',
|
349
|
verbose_name=u"Garde parentale",
|
350
|
null=True, blank=True, default=None)
|
351
|
|
352
|
# Transport
|
353
|
transporttype = models.ForeignKey('ressources.TransportType',
|
354
|
verbose_name=u"Type de transport",
|
355
|
null=True, blank=True, default=None)
|
356
|
transportcompany = models.ForeignKey('ressources.TransportCompany',
|
357
|
verbose_name=u"Compagnie de transport",
|
358
|
null=True, blank=True, default=None)
|
359
|
|
360
|
# FollowUp
|
361
|
coordinators = models.ManyToManyField('personnes.Worker',
|
362
|
verbose_name=u"Coordinateurs",
|
363
|
null=True, blank=True, default=None)
|
364
|
externaldoctor = models.ForeignKey('personnes.ExternalTherapist',
|
365
|
verbose_name=u"Médecin extérieur",
|
366
|
null=True, blank=True, default=None)
|
367
|
externalintervener = models.ForeignKey('personnes.ExternalWorker',
|
368
|
verbose_name=u"Intervenant extérieur",
|
369
|
null=True, blank=True, default=None)
|
370
|
|
371
|
old_id = models.CharField(max_length=256,
|
372
|
verbose_name=u'Ancien ID', blank=True, null=True)
|
373
|
old_old_id = models.CharField(max_length=256,
|
374
|
verbose_name=u'Ancien ancien ID', blank=True, null=True)
|
375
|
|
376
|
def __init__(self, *args, **kwargs):
|
377
|
super(PatientRecord, self).__init__(*args, **kwargs)
|
378
|
if not hasattr(self, 'service'):
|
379
|
raise Exception('The field service is mandatory.')
|
380
|
|
381
|
def get_state(self):
|
382
|
return self.last_state
|
383
|
|
384
|
def get_initial_state(self):
|
385
|
return self.filestate_set.order_by('date_selected')[0]
|
386
|
|
387
|
def get_current_state(self):
|
388
|
today = date.today()
|
389
|
return self.get_state_at_day(today)
|
390
|
|
391
|
def get_state_at_day(self, date):
|
392
|
state = self.get_state()
|
393
|
while(state):
|
394
|
if datetime(state.date_selected.year,
|
395
|
state.date_selected.month, state.date_selected.day) <= \
|
396
|
datetime(date.year, date.month, date.day):
|
397
|
return state
|
398
|
state = state.previous_state
|
399
|
return self.get_state()
|
400
|
|
401
|
def was_in_state_at_day(self, date, status_type):
|
402
|
state_at_day = self.get_state_at_day(date)
|
403
|
if state_at_day and state_at_day.status.type == status_type:
|
404
|
return True
|
405
|
return False
|
406
|
|
407
|
def get_states_history(self):
|
408
|
return self.filestate_set.order_by('date_selected')
|
409
|
|
410
|
def can_be_deleted(self):
|
411
|
for act in self.act_set.all():
|
412
|
if act.is_state('VALIDE'):
|
413
|
return False
|
414
|
return True
|
415
|
|
416
|
def delete(self, *args, **kwargs):
|
417
|
if self.can_be_deleted():
|
418
|
super(PatientRecord, self).delete(*args, **kwargs)
|
419
|
|
420
|
def get_ondisk_directory(self, service):
|
421
|
if not settings.PATIENT_FILES_BASE_DIRECTORY:
|
422
|
return None
|
423
|
|
424
|
dirnames = []
|
425
|
dirname = self.last_name.upper()
|
426
|
dirnames.append(dirname)
|
427
|
if self.first_name:
|
428
|
dirname = '%s %s' % (dirname, self.first_name)
|
429
|
dirnames.append(dirname)
|
430
|
if self.paper_id:
|
431
|
dirname = '%s %s' % (dirname, self.paper_id)
|
432
|
dirnames.append(dirname)
|
433
|
|
434
|
for i, dirname in enumerate(dirnames):
|
435
|
fullpath = os.path.join(settings.PATIENT_FILES_BASE_DIRECTORY, service, dirname)
|
436
|
try:
|
437
|
next_fullpath = os.path.join(settings.PATIENT_FILES_BASE_DIRECTORY, service, dirnames[i+1])
|
438
|
except IndexError:
|
439
|
pass
|
440
|
else:
|
441
|
if os.path.exists(fullpath) and not os.path.exists(next_fullpath):
|
442
|
os.rename(fullpath, next_fullpath)
|
443
|
continue
|
444
|
if not os.path.exists(fullpath):
|
445
|
os.makedirs(fullpath)
|
446
|
for subdir in settings.PATIENT_SUBDIRECTORIES:
|
447
|
subdir_fullpath = os.path.join(fullpath, subdir)
|
448
|
if not os.path.exists(subdir_fullpath):
|
449
|
os.makedirs(subdir_fullpath)
|
450
|
return fullpath
|
451
|
|
452
|
def get_client_side_directory(self, service):
|
453
|
directory = self.get_ondisk_directory(service)
|
454
|
if not directory:
|
455
|
return None
|
456
|
if not settings.CLIENT_SIDE_PATIENT_FILES_BASE_DIRECTORY:
|
457
|
return None
|
458
|
return os.path.join(settings.CLIENT_SIDE_PATIENT_FILES_BASE_DIRECTORY,
|
459
|
directory[len(settings.PATIENT_FILES_BASE_DIRECTORY)+1:])
|
460
|
|
461
|
def set_state(self, status, author, date_selected=None, comment=None):
|
462
|
if not author:
|
463
|
raise Exception('Missing author to set state')
|
464
|
if not date_selected:
|
465
|
date_selected = datetime.now()
|
466
|
current_state = self.get_state()
|
467
|
if not current_state:
|
468
|
raise Exception('Invalid patient record. '
|
469
|
'Missing current state.')
|
470
|
if date_selected < current_state.date_selected:
|
471
|
raise Exception('You cannot set a state starting the %s that '
|
472
|
'is before the previous state starting at day %s.' % \
|
473
|
(str(date_selected), str(current_state.date_selected)))
|
474
|
filestate = FileState.objects.create(patient=self, status=status,
|
475
|
date_selected=date_selected, author=author, comment=comment,
|
476
|
previous_state=current_state)
|
477
|
self.last_state = filestate
|
478
|
self.save()
|
479
|
|
480
|
def change_day_selected_of_state(self, state, new_date):
|
481
|
if state.previous_state:
|
482
|
if new_date < state.previous_state.date_selected:
|
483
|
raise Exception('You cannot set a state starting the %s '
|
484
|
'before the previous state starting at day %s.' % \
|
485
|
(str(new_date), str(state.previous_state.date_selected)))
|
486
|
next_state = state.get_next_state()
|
487
|
if next_state:
|
488
|
if new_date > next_state.date_selected:
|
489
|
raise Exception('You cannot set a state starting the %s '
|
490
|
'after the following state starting at day %s.' % \
|
491
|
(str(new_date), str(next_state.date_selected)))
|
492
|
state.date_selected = new_date
|
493
|
state.save()
|
494
|
|
495
|
def remove_state(self, state):
|
496
|
if state.patient.id != self.id:
|
497
|
raise Exception('The state given is not about this patient '
|
498
|
'record but about %s' % state.patient)
|
499
|
next_state = state.get_next_state()
|
500
|
if not next_state:
|
501
|
self.remove_last_state()
|
502
|
else:
|
503
|
next_state.previous_state = state.previous_state
|
504
|
next_state.save()
|
505
|
state.delete()
|
506
|
|
507
|
def remove_last_state(self):
|
508
|
try:
|
509
|
self.get_state().delete()
|
510
|
except:
|
511
|
pass
|
512
|
|
513
|
# START Specific to sessad healthcare
|
514
|
def get_last_notification(self):
|
515
|
return SessadHealthCareNotification.objects.filter(patient=self, ).\
|
516
|
latest('end_date')
|
517
|
|
518
|
def days_before_notification_expiration(self):
|
519
|
today = datetime.today()
|
520
|
notification = self.get_last_notification(self)
|
521
|
if not notification:
|
522
|
return 0
|
523
|
if notification.end_date < today:
|
524
|
return 0
|
525
|
else:
|
526
|
return notification.end_date - today
|
527
|
# END Specific to sessad healthcare
|
528
|
|
529
|
# START Specific to cmpp healthcare
|
530
|
def create_diag_healthcare(self, modifier):
|
531
|
"""
|
532
|
Gestion de l'inscription automatique.
|
533
|
|
534
|
Si un premier acte est validé alors une prise en charge
|
535
|
diagnostique est ajoutée. Cela fera basculer le dossier dans l'état
|
536
|
en diagnostic.
|
537
|
|
538
|
A voir si auto ou manuel :
|
539
|
Si ce n'est pas le premier acte validé mais que l'acte précédement
|
540
|
facturé a plus d'un an, on peut créer une prise en charge
|
541
|
diagnostique. Même s'il y a une prise en charge de traitement
|
542
|
expirée depuis moins d'un an donc renouvelable.
|
543
|
|
544
|
"""
|
545
|
acts = self.act_set.order_by('date')
|
546
|
hcds = CmppHealthCareDiagnostic.objects.filter(patient=self).order_by('-start_date')
|
547
|
if not hcds:
|
548
|
# Pas de prise en charge, on recherche l'acte facturable le plus
|
549
|
# ancien, on crée une pc diag à la même date.
|
550
|
for act in acts:
|
551
|
if act.is_state('VALIDE') and act.is_billable():
|
552
|
CmppHealthCareDiagnostic(patient=self, author=modifier,
|
553
|
start_date=act.date).save()
|
554
|
break
|
555
|
else:
|
556
|
# On recherche l'acte facturable non facturé le plus ancien et
|
557
|
# l'on regarde s'il a plus d'un an
|
558
|
try:
|
559
|
last_billed_act = self.act_set.filter(is_billed=True).\
|
560
|
latest('date')
|
561
|
if last_billed_act:
|
562
|
for act in acts:
|
563
|
if act.is_state('VALIDE') and \
|
564
|
act.is_billable() and \
|
565
|
(act.date - last_billed_act.date).days >= 365:
|
566
|
return True
|
567
|
except:
|
568
|
pass
|
569
|
return False
|
570
|
|
571
|
def automated_switch_state(self, modifier):
|
572
|
# Quel est le dernier acte facturable.
|
573
|
acts = self.act_set.order_by('-date')
|
574
|
# Si cet acte peut-être pris en charge en diagnostic c'est un acte de
|
575
|
# diagnostic, sinon c'est un acte de traitement.
|
576
|
last_state_services = self.last_state.status.\
|
577
|
services.values_list('name', flat=True)
|
578
|
cmpp = Service.objects.get(name='CMPP')
|
579
|
for act in acts:
|
580
|
if act.is_state('VALIDE') and act.is_billable() and \
|
581
|
act.date >= self.get_state().date_selected.date() and \
|
582
|
are_all_acts_of_the_day_locked(act.date):
|
583
|
cared, hc = act.is_act_covered_by_diagnostic_healthcare()
|
584
|
if hc:
|
585
|
if (self.last_state.status.type == "ACCUEIL" \
|
586
|
or self.last_state.status.type == "TRAITEMENT") \
|
587
|
and "CMPP" in last_state_services:
|
588
|
status = Status.objects.filter(type="DIAGNOSTIC").\
|
589
|
filter(services__name='CMPP')[0]
|
590
|
try:
|
591
|
self.set_state(status, modifier,
|
592
|
date_selected=act.date)
|
593
|
except:
|
594
|
pass
|
595
|
# Sinon, si le dossier est en diag, s'il ne peut être couvert
|
596
|
# en diag, il est en traitement.
|
597
|
elif self.last_state.status.type == "DIAGNOSTIC" and \
|
598
|
"CMPP" in last_state_services:
|
599
|
status = Status.objects.filter(type="TRAITEMENT").\
|
600
|
filter(services__name='CMPP')[0]
|
601
|
try:
|
602
|
self.set_state(status, modifier,
|
603
|
date_selected=act.date)
|
604
|
except:
|
605
|
pass
|
606
|
break
|
607
|
# END Specific to cmpp healthcare
|
608
|
|
609
|
reversion.register(PatientRecord, follow=['people_ptr'])
|
610
|
|
611
|
|
612
|
def create_patient(first_name, last_name, service, creator,
|
613
|
date_selected=None):
|
614
|
logger.debug('create_patient: creation for patient %s %s in service %s '
|
615
|
'by %s' % (first_name, last_name, service, creator))
|
616
|
if not (first_name and last_name and service and creator):
|
617
|
raise Exception('Missing parameter to create a patient record.')
|
618
|
status = Status.objects.filter(type="ACCUEIL").filter(services=service)
|
619
|
if not status:
|
620
|
raise Exception('%s has no ACCEUIL status' % service.name)
|
621
|
patient = PatientRecord.objects.create(first_name=first_name,
|
622
|
last_name=last_name, service=service,
|
623
|
creator=creator)
|
624
|
fs = FileState(status=status[0], author=creator, previous_state=None)
|
625
|
if not date_selected:
|
626
|
date_selected = patient.created
|
627
|
fs.patient = patient
|
628
|
fs.date_selected = date_selected
|
629
|
fs.save()
|
630
|
patient.last_state = fs
|
631
|
patient.save()
|
632
|
return patient
|