1
|
# -*- coding: utf-8 -*-
|
2
|
from django.db import models
|
3
|
from django.contrib.auth.models import User
|
4
|
|
5
|
import reversion
|
6
|
|
7
|
from calebasse.agenda.models import Event, EventType
|
8
|
from calebasse.agenda.managers import EventManager
|
9
|
from calebasse.dossiers.models import SessadHealthCareNotification, \
|
10
|
CmppHealthCareDiagnostic, CmppHealthCareTreatment
|
11
|
from calebasse.actes.validation import are_all_acts_of_the_day_locked
|
12
|
from calebasse.ressources.models import ServiceLinkedAbstractModel
|
13
|
|
14
|
from validation_states import VALIDATION_STATES, NON_VALIDE
|
15
|
|
16
|
|
17
|
class ActValidationState(models.Model):
|
18
|
|
19
|
class Meta:
|
20
|
app_label = 'actes'
|
21
|
|
22
|
act = models.ForeignKey('actes.Act',
|
23
|
verbose_name=u'Acte', editable=False)
|
24
|
state_name = models.CharField(max_length=150)
|
25
|
created = models.DateTimeField(u'Création', auto_now_add=True)
|
26
|
author = \
|
27
|
models.ForeignKey(User,
|
28
|
verbose_name=u'Auteur', editable=False)
|
29
|
previous_state = models.ForeignKey('ActValidationState',
|
30
|
verbose_name=u'Etat précédent',
|
31
|
editable=False, blank=True, null=True)
|
32
|
# To record if the validation has be done by the automated validation
|
33
|
auto = models.BooleanField(default=False,
|
34
|
verbose_name=u'Vérouillage')
|
35
|
|
36
|
def __repr__(self):
|
37
|
return self.state_name + ' ' + str(self.created)
|
38
|
|
39
|
def __unicode__(self):
|
40
|
return VALIDATION_STATES[self.state_name]
|
41
|
|
42
|
|
43
|
class Act(models.Model):
|
44
|
patient = models.ForeignKey('dossiers.PatientRecord')
|
45
|
date = models.DateTimeField()
|
46
|
act_type = models.ForeignKey('ressources.ActType',
|
47
|
verbose_name=u'Type d\'acte')
|
48
|
validation_locked = models.BooleanField(default=False,
|
49
|
verbose_name=u'Vérouillage')
|
50
|
is_billed = models.BooleanField(default=False,
|
51
|
verbose_name=u'Facturé')
|
52
|
switch_billable = models.BooleanField(default=False,
|
53
|
verbose_name=u'Inverser type facturable')
|
54
|
healthcare = models.ForeignKey('dossiers.HealthCare',
|
55
|
blank=True,
|
56
|
null=True,
|
57
|
verbose_name=u'Prise en charge utilisée pour facturer (CMPP)')
|
58
|
transport_company = models.ForeignKey('ressources.TransportCompany',
|
59
|
blank=True,
|
60
|
null=True,
|
61
|
verbose_name=u'Compagnie de transport')
|
62
|
transport_type = models.ForeignKey('ressources.TransportType',
|
63
|
blank=True,
|
64
|
null=True,
|
65
|
verbose_name=u'Type de transport')
|
66
|
doctors = models.ManyToManyField('personnes.Worker',
|
67
|
limit_choices_to={'type__intervene': True},
|
68
|
verbose_name=u'Thérapeutes')
|
69
|
pause = models.BooleanField(default=False,
|
70
|
verbose_name=u'Pause facturation')
|
71
|
|
72
|
def is_absent(self):
|
73
|
if self.get_state() in ('ABS_NON_EXC', 'ABS_EXC', 'ANNUL_NOUS',
|
74
|
'ANNUL_FAMILLE', 'ABS_ESS_PPS', 'ENF_HOSP'):
|
75
|
return True
|
76
|
|
77
|
def get_state(self):
|
78
|
return self.actvalidationstate_set.latest('created')
|
79
|
|
80
|
def is_state(self, state_name):
|
81
|
state = self.get_state()
|
82
|
if state and state.state_name == state_name:
|
83
|
return True
|
84
|
return False
|
85
|
|
86
|
def set_state(self, state_name, author, auto=False,
|
87
|
change_state_check=True):
|
88
|
if not author:
|
89
|
raise Exception('Missing author to set state')
|
90
|
if not state_name in VALIDATION_STATES.keys():
|
91
|
raise Exception("Etat d'acte non existant %s")
|
92
|
current_state = self.get_state()
|
93
|
ActValidationState(act=self, state_name=state_name,
|
94
|
author=author, previous_state=current_state).save()
|
95
|
|
96
|
def is_billable(self):
|
97
|
if (self.act_type.billable and not self.switch_billable) or \
|
98
|
(not self.act_type.billable and self.switch_billable):
|
99
|
return True
|
100
|
|
101
|
# START Specific to sessad healthcare
|
102
|
def was_covered_by_notification(self):
|
103
|
notifications = \
|
104
|
SessadHealthCareNotification.objects.filter(patient=self.patient,
|
105
|
start_date__lte=self.date, end_date__gte=self.date)
|
106
|
if notifications:
|
107
|
return True
|
108
|
# END Specific to sessad healthcare
|
109
|
|
110
|
# START Specific to cmpp healthcare
|
111
|
def is_act_covered_by_diagnostic_healthcare(self):
|
112
|
# L'acte est déja pointé par une prise en charge
|
113
|
if self.is_billed:
|
114
|
# Sinon ce peut une refacturation, donc ne pas tenir compte qu'il
|
115
|
# y est une healthcare non vide
|
116
|
if self.healthcare and isinstance(self.healthcare,
|
117
|
CmppHealthCareDiagnostic):
|
118
|
return (False, self.healthcare)
|
119
|
elif self.healthcare:
|
120
|
return (False, None)
|
121
|
# L'acte doit être facturable
|
122
|
if not (are_all_acts_of_the_day_locked(self.date) and \
|
123
|
self.is_state('VALIDE') and self.is_billable()):
|
124
|
return (False, None)
|
125
|
# On prend la dernière prise en charge diagnostic, l'acte ne sera pas
|
126
|
# pris en charge sur une prise en charge précédente
|
127
|
# Il peut arriver que l'on ait ajouté une prise en charge de
|
128
|
# traitement alors que tous les actes pour le diag ne sont pas encore facturés
|
129
|
try:
|
130
|
hc = CmppHealthCareDiagnostic.objects.\
|
131
|
filter(patient=self.patient).latest('start_date')
|
132
|
except:
|
133
|
return (False, None)
|
134
|
if not hc:
|
135
|
# On pourrait ici créer une prise en charge de diagnostic
|
136
|
return (False, None)
|
137
|
if self.date < hc.start_date:
|
138
|
return (False, None)
|
139
|
# Les acts facturés déja couvert par la prise en charge sont pointés
|
140
|
# dans hc.act_set.all()
|
141
|
nb_acts_billed = len(hc.act_set.all())
|
142
|
if nb_acts_billed >= hc.get_act_number():
|
143
|
return (False, None)
|
144
|
# Il faut ajouter les actes facturables non encore facturés qui précède cet
|
145
|
# acte
|
146
|
acts_billable = [a for a in self.patient.act_set.\
|
147
|
filter(is_billed=False).order_by('date') \
|
148
|
if are_all_acts_of_the_day_locked(a.date) and \
|
149
|
a.is_state('VALIDE') and a.is_billable()]
|
150
|
count = 0
|
151
|
for a in acts_billable:
|
152
|
if nb_acts_billed + count >= hc.get_act_number():
|
153
|
return (False, None)
|
154
|
if a.date >= hc.start_date:
|
155
|
if a.id == self.id:
|
156
|
return (True, hc)
|
157
|
count = count + 1
|
158
|
return (False, None)
|
159
|
|
160
|
def is_act_covered_by_treatment_healthcare(self):
|
161
|
# L'acte est déja pointé par une prise en charge
|
162
|
if self.is_billed:
|
163
|
# Sinon ce peut une refacturation, donc ne pas tenir compte qu'il
|
164
|
# y est une healthcare non vide
|
165
|
if self.healthcare and isinstance(self.healthcare,
|
166
|
CmppHealthCareTreatment):
|
167
|
return (False, self.healthcare)
|
168
|
elif self.healthcare:
|
169
|
return (False, None)
|
170
|
# L'acte doit être facturable
|
171
|
if not (are_all_acts_of_the_day_locked(self.date) and \
|
172
|
self.is_state('VALIDE') and self.is_billable()):
|
173
|
return (False, None)
|
174
|
# On prend la dernière prise en charge diagnostic, l'acte ne sera pas
|
175
|
# pris en charge sur une prise en charge précédente
|
176
|
# Il peut arriver que l'on ait ajouté une prise en charge de
|
177
|
# traitement alors que tous les actes pour le diag ne sont pas encore facturés
|
178
|
try:
|
179
|
hc = CmppHealthCareTreatment.objects.\
|
180
|
filter(patient=self.patient).latest('start_date')
|
181
|
except:
|
182
|
return (False, None)
|
183
|
if not hc:
|
184
|
return (False, None)
|
185
|
if self.date < hc.start_date or self.date > hc.end_date:
|
186
|
return (False, None)
|
187
|
# Les acts facturés déja couvert par la prise en charge sont pointés
|
188
|
# dans hc.act_set.all()
|
189
|
nb_acts_billed = len(hc.act_set.all())
|
190
|
if nb_acts_billed >= hc.get_act_number():
|
191
|
return (False, None)
|
192
|
# Il faut ajouter les actes facturables non encore facturés qui précède cet
|
193
|
# acte
|
194
|
acts_billable = [a for a in self.patient.act_set.\
|
195
|
filter(is_billed=False).order_by('date') \
|
196
|
if are_all_acts_of_the_day_locked(a.date) and \
|
197
|
a.is_state('VALIDE') and a.is_billable()]
|
198
|
count = 0
|
199
|
for a in acts_billable:
|
200
|
if nb_acts_billed + count >= hc.get_act_number():
|
201
|
return (False, None)
|
202
|
if a.date >= hc.start_date and a.date <= hc.end_date:
|
203
|
if a.id == self.id:
|
204
|
return (True, hc)
|
205
|
count = count + 1
|
206
|
return (False, None)
|
207
|
# END Specific to cmpp healthcare
|
208
|
|
209
|
def __unicode__(self):
|
210
|
return u'{0} le {1} pour {2} avec {3}'.format(
|
211
|
self.act_type, self.date, self.patient,
|
212
|
', '.join(map(unicode, self.doctors.all())))
|
213
|
|
214
|
def __repr__(self):
|
215
|
return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
|
216
|
|
217
|
class Meta:
|
218
|
verbose_name = u"Acte"
|
219
|
verbose_name_plural = u"Actes"
|
220
|
ordering = ['-date', 'patient']
|
221
|
|
222
|
|
223
|
class EventActManager(EventManager):
|
224
|
|
225
|
def create_patient_appointment(self, creator, title, patient, participants,
|
226
|
act_type, service, start_datetime, end_datetime, description='',
|
227
|
room=None, note=None, **rrule_params):
|
228
|
"""
|
229
|
This method allow you to create a new patient appointment quickly
|
230
|
|
231
|
Args:
|
232
|
title: patient appointment title (str)
|
233
|
patient: Patient object
|
234
|
participants: List of CalebasseUser (therapists)
|
235
|
act_type: ActType object
|
236
|
service: Service object. Use session service by defaut
|
237
|
start_datetime: datetime with the start date and time
|
238
|
end_datetime: datetime with the end date and time
|
239
|
freq, count, until, byweekday, rrule_params:
|
240
|
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
|
241
|
|
242
|
Example:
|
243
|
Look at calebasse.agenda.tests.EventTest (test_create_appointments
|
244
|
method)
|
245
|
"""
|
246
|
|
247
|
event_type, created = EventType.objects.get_or_create(
|
248
|
label=u"Rendez-vous patient"
|
249
|
)
|
250
|
|
251
|
act_event = EventAct.objects.create(
|
252
|
title=title,
|
253
|
event_type=event_type,
|
254
|
patient=patient,
|
255
|
act_type=act_type,
|
256
|
date=start_datetime,
|
257
|
)
|
258
|
act_event.doctors = participants
|
259
|
ActValidationState(act=act_event, state_name='NON_VALIDE',
|
260
|
author=creator, previous_state=None).save()
|
261
|
|
262
|
return self._set_event(act_event, participants, description,
|
263
|
services=[service], start_datetime=start_datetime,
|
264
|
end_datetime=end_datetime,
|
265
|
room=room, note=note, **rrule_params)
|
266
|
|
267
|
def modify_patient_appointment(self, creator, title, patient, participants,
|
268
|
act_type, service, start_datetime, end_datetime, description='',
|
269
|
room=None, note=None, **rrule_params):
|
270
|
"""
|
271
|
This method allow you to create a new patient appointment quickly
|
272
|
|
273
|
Args:
|
274
|
creator: author of the modification
|
275
|
title: patient appointment title (str)
|
276
|
patient: Patient object
|
277
|
participants: List of CalebasseUser (therapists)
|
278
|
act_type: ActType object
|
279
|
service: Service object. Use session service by defaut
|
280
|
start_datetime: datetime with the start date and time
|
281
|
end_datetime: datetime with the end date and time
|
282
|
description: description of the event
|
283
|
room: room where the event will take place
|
284
|
freq, count, until, byweekday, rrule_params:
|
285
|
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
|
286
|
|
287
|
Example:
|
288
|
Look at calebasse.agenda.tests.EventTest (test_create_appointments
|
289
|
method)
|
290
|
"""
|
291
|
|
292
|
event_type, created = EventType.objects.get_or_create(
|
293
|
label=u"Rendez-vous patient"
|
294
|
)
|
295
|
|
296
|
act_event = EventAct.objects.create(
|
297
|
title=title,
|
298
|
event_type=event_type,
|
299
|
patient=patient,
|
300
|
act_type=act_type,
|
301
|
date=start_datetime,
|
302
|
)
|
303
|
act_event.doctors = participants
|
304
|
ActValidationState(act=act_event, state_name=NON_VALIDE,
|
305
|
author=creator, previous_state=None).save()
|
306
|
|
307
|
return self._set_event(act_event, participants, description,
|
308
|
services=[service], start_datetime=start_datetime,
|
309
|
end_datetime=end_datetime,
|
310
|
room=room, note=note, **rrule_params)
|
311
|
|
312
|
class EventAct(Act, Event):
|
313
|
objects = EventActManager()
|
314
|
|
315
|
VALIDATION_CODE_CHOICES = (
|
316
|
('absent', u'Absent'),
|
317
|
('present', u'Présent'),
|
318
|
)
|
319
|
attendance = models.CharField(max_length=16,
|
320
|
choices=VALIDATION_CODE_CHOICES,
|
321
|
default='absent',
|
322
|
verbose_name=u'Présence')
|
323
|
convocation_sent = models.BooleanField(blank=True,
|
324
|
verbose_name=u'Convoqué')
|
325
|
|
326
|
def __unicode__(self):
|
327
|
return u'Rdv le {0} de {1} avec {2} pour {3}'.format(
|
328
|
self.occurrence_set.all()[0].start_time, self.patient,
|
329
|
', '.join(map(unicode, self.participants.all())),
|
330
|
self.act_type)
|
331
|
|
332
|
def __repr__(self):
|
333
|
return (u'<%s %r %r>' % (self.__class__.__name__, unicode(self),
|
334
|
self.id)).encode('utf-8')
|
335
|
|
336
|
def start_time(self):
|
337
|
return self.occurrence_set.all()[0].start_time
|
338
|
|
339
|
def duration(self):
|
340
|
o = self.occurrence_set.all()[0]
|
341
|
td = o.end_time - o.start_time
|
342
|
hours, remainder = divmod(td.seconds, 3600)
|
343
|
minutes, remainder = divmod(remainder, 60)
|
344
|
return '%02d:%02d' % (hours, minutes)
|
345
|
|
346
|
class Meta:
|
347
|
verbose_name = 'Rendez-vous patient'
|
348
|
verbose_name_plural = 'Rendez-vous patient'
|
349
|
ordering = ['-date', 'patient']
|
350
|
|
351
|
reversion.register(EventAct, follow=['act_ptr', 'event_ptr'])
|
352
|
|
353
|
class ValidationMessage(ServiceLinkedAbstractModel):
|
354
|
validation_date = models.DateTimeField()
|
355
|
what = models.CharField(max_length=256)
|
356
|
who = models.ForeignKey(User)
|
357
|
when = models.DateTimeField(auto_now_add=True)
|