Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / actes / models.py @ b5877252

1
# -*- coding: utf-8 -*-
2
from datetime import date, time
3

    
4
from django.db import models
5
from django.contrib.auth.models import User
6

    
7
import reversion
8

    
9
from calebasse.agenda.models import Event, EventType
10
from calebasse.agenda.managers import EventManager
11
from calebasse.ressources.models import ServiceLinkedAbstractModel
12
from ..middleware.request import get_request
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
        ordering = ('-created',)
22

    
23
    act = models.ForeignKey('actes.Act',
24
        verbose_name=u'Acte', editable=False)
25
    state_name = models.CharField(max_length=150)
26
    created = models.DateTimeField(u'Création', auto_now_add=True)
27
    author = \
28
        models.ForeignKey(User,
29
        verbose_name=u'Auteur', editable=False, blank=True, null=True)
30
    previous_state = models.ForeignKey('ActValidationState',
31
        verbose_name=u'Etat précédent',
32
        editable=False, blank=True, null=True)
33
    # To record if the validation has be done by the automated validation
34
    auto = models.BooleanField(default=False,
35
            verbose_name=u'Vérouillage')
36

    
37
    def __repr__(self):
38
        return self.state_name + ' ' + str(self.created)
39

    
40
    def __unicode__(self):
41
        return VALIDATION_STATES[self.state_name]
42

    
43

    
44
class ActManager(models.Manager):
45
    def for_today(self, today=None):
46
        today = today or date.today()
47
        return self.filter(date=today)
48

    
49
    def create_act(self, author=None, **kwargs):
50
        act = self.create(**kwargs)
51
        ActValidationState.objects.create(act=act,state_name='NON_VALIDE',
52
            author=author, previous_state=None)
53
        return act
54

    
55
    def next_acts(self, patient_record, today=None):
56
        today = today or date.today()
57
        return self.filter(date__gte=today) \
58
                .filter(patient=patient_record) \
59
                .order_by('date')
60

    
61
    def last_acts(self, patient_record, today=None):
62
        today = today or date.today()
63
        return self.filter(date__lte=today) \
64
                .filter(patient=patient_record) \
65
                .order_by('-date')
66

    
67

    
68
class Act(models.Model):
69
    objects = ActManager()
70

    
71
    patient = models.ForeignKey('dossiers.PatientRecord')
72
    date = models.DateField(u'Date', db_index=True)
73
    time = models.TimeField(u'Heure', blank=True, null=True, default=time(), db_index=True)
74
    _duration = models.IntegerField(u'Durée en minutes', blank=True, null=True, default=0)
75
    act_type = models.ForeignKey('ressources.ActType',
76
            verbose_name=u'Type d\'acte')
77
    validation_locked = models.BooleanField(default=False,
78
            verbose_name=u'Vérouillage', db_index=True)
79
    is_billed = models.BooleanField(default=False,
80
            verbose_name=u'Facturé', db_index=True)
81
    switch_billable = models.BooleanField(default=False,
82
            verbose_name=u'Inverser type facturable')
83
    healthcare = models.ForeignKey('dossiers.HealthCare',
84
            blank=True,
85
            null=True,
86
            verbose_name=u'Prise en charge utilisée pour facturer (CMPP)')
87
    transport_company = models.ForeignKey('ressources.TransportCompany',
88
            blank=True,
89
            null=True,
90
            verbose_name=u'Compagnie de transport')
91
    transport_type = models.ForeignKey('ressources.TransportType',
92
            blank=True,
93
            null=True,
94
            verbose_name=u'Type de transport')
95
    doctors = models.ManyToManyField('personnes.Worker',
96
            limit_choices_to={'type__intervene': True},
97
            verbose_name=u'Intervenants')
98
    pause = models.BooleanField(default=False,
99
            verbose_name=u'Pause facturation', db_index=True)
100
    parent_event = models.ForeignKey('agenda.Event',
101
            verbose_name=u'Rendez-vous lié',
102
            blank=True, null=True,
103
            on_delete=models.SET_NULL)
104
    VALIDATION_CODE_CHOICES = (
105
            ('absent', u'Absent'),
106
            ('present', u'Présent'),
107
            )
108
    attendance = models.CharField(max_length=16,
109
            choices=VALIDATION_CODE_CHOICES,
110
            default='absent',
111
            verbose_name=u'Présence')
112
    comment = models.TextField(u'Commentaire')
113
    old_id = models.CharField(max_length=256,
114
            verbose_name=u'Ancien ID', blank=True, null=True)
115

    
116
    @property
117
    def event(self):
118
        if self.parent_event:
119
            return self.parent_event.today_occurrence(self.date)
120
        return None
121

    
122
    @property
123
    def start_datetime(self):
124
        event = self.event
125
        if event:
126
            return event.start_datetime
127
        return self.date
128

    
129
    def get_hc_tag(self):
130
        if self.healthcare:
131
            try:
132
                self.healthcare.cmpphealthcaretreatment
133
                return 'T'
134
            except:
135
                pass
136
            try:
137
                self.healthcare.cmpphealthcarediagnostic
138
                acts = self.healthcare.act_set.order_by('date')
139
                i = 1
140
                for act in acts:
141
                    if act.id == self.id:
142
                        return 'D' + str(i)
143
                    i = i + 1
144
            except:
145
                pass
146
        return None
147

    
148
    def is_new(self):
149
        states = self.actvalidationstate_set.all()
150
        states_len = len(states)
151
        return states_len == 0 or \
152
            (states_len == 1 and states[0].state_name == 'NON_VALIDE')
153

    
154
    def is_absent(self):
155
        state = self.get_state()
156
        if state and state.state_name in ('ABS_NON_EXC', 'ABS_EXC', 'ABS_INTER', 'ANNUL_NOUS',
157
                'ANNUL_FAMILLE', 'REPORTE', 'ABS_ESS_PPS', 'ENF_HOSP'):
158
            return True
159
        return False
160

    
161
    def get_state(self):
162
        states = sorted(self.actvalidationstate_set.all(),
163
                key=lambda avs: avs.created, reverse=True)
164
        if states:
165
            return states[0]
166
        return None
167

    
168
    def is_state(self, state_name):
169
        state = self.get_state()
170
        if state and state.state_name == state_name:
171
            return True
172
        return False
173

    
174
    def set_state(self, state_name, author, auto=False,
175
            change_state_check=True):
176
        if not author:
177
            raise Exception('Missing author to set state')
178
        if not state_name in VALIDATION_STATES.keys():
179
            raise Exception("Etat d'acte non existant %s")
180
        current_state = self.get_state()
181
        ActValidationState(act=self, state_name=state_name,
182
            author=author, previous_state=current_state).save()
183

    
184
    def is_billable(self):
185
        if (self.act_type.billable and not self.switch_billable) or \
186
                (not self.act_type.billable and self.switch_billable):
187
            return True
188

    
189
    # START Specific to sessad healthcare
190
    def was_covered_by_notification(self):
191
        from calebasse.dossiers.models import SessadHealthCareNotification
192
        notifications = \
193
            SessadHealthCareNotification.objects.filter(patient=self.patient,
194
            start_date__lte=self.date, end_date__gte=self.date)
195
        if notifications:
196
            return True
197
    # END Specific to sessad healthcare
198

    
199
    # START Specific to cmpp healthcare
200
    def is_act_covered_by_diagnostic_healthcare(self):
201
        from calebasse.dossiers.models import CmppHealthCareDiagnostic
202
        from validation import are_all_acts_of_the_day_locked
203
        # L'acte est déja pointé par une prise en charge
204
        if self.is_billed:
205
            # Sinon ce peut une refacturation, donc ne pas tenir compte qu'il
206
            # y est une healthcare non vide
207
            if self.healthcare and isinstance(self.healthcare,
208
                    CmppHealthCareDiagnostic):
209
                return (False, self.healthcare)
210
            elif self.healthcare:
211
                return (False, None)
212
        # L'acte doit être facturable
213
        if not (are_all_acts_of_the_day_locked(self.date) and \
214
                self.is_state('VALIDE') and self.is_billable()):
215
            return (False, None)
216
        # On prend la dernière prise en charge diagnostic, l'acte ne sera pas
217
        # pris en charge sur une prise en charge précédente
218
        # Il peut arriver que l'on ait ajouté une prise en charge de
219
        # traitement alors que tous les actes pour le diag ne sont pas encore facturés
220
        try:
221
            hc = CmppHealthCareDiagnostic.objects.\
222
                filter(patient=self.patient).latest('start_date')
223
        except:
224
            return (False, None)
225
        if not hc:
226
            # On pourrait ici créer une prise en charge de diagnostic
227
            return (False, None)
228
        if self.date < hc.start_date:
229
            return (False, None)
230
        # Les acts facturés déja couvert par la prise en charge sont pointés
231
        # dans hc.act_set.all()
232
        nb_acts_billed = len(hc.act_set.all())
233
        if nb_acts_billed >= hc.get_act_number():
234
            return (False, None)
235
        # Il faut ajouter les actes facturables non encore facturés qui précède cet
236
        # acte
237
        acts_billable = [a for a in self.patient.act_set.\
238
            filter(is_billed=False).order_by('date') \
239
            if are_all_acts_of_the_day_locked(a.date) and \
240
            a.is_state('VALIDE') and a.is_billable()]
241
        count = 0
242
        for a in acts_billable:
243
            if nb_acts_billed + count >= hc.get_act_number():
244
                return (False, None)
245
            if a.date >= hc.start_date:
246
                if a.id == self.id:
247
                    return (True, hc)
248
                count = count + 1
249
        return (False, None)
250

    
251
#    def is_act_covered_by_treatment_healthcare(self):
252
#        # L'acte est déja pointé par une prise en charge
253
#        if self.is_billed:
254
#            # Sinon ce peut une refacturation, donc ne pas tenir compte qu'il
255
#            # y est une healthcare non vide
256
#            if self.healthcare and isinstance(self.healthcare,
257
#                    CmppHealthCareTreatment):
258
#                return (False, self.healthcare)
259
#            elif self.healthcare:
260
#                return (False, None)
261
#        # L'acte doit être facturable
262
#        if not (are_all_acts_of_the_day_locked(self.date) and \
263
#                self.is_state('VALIDE') and self.is_billable()):
264
#            return (False, None)
265
#        # On prend la dernière prise en charge diagnostic, l'acte ne sera pas
266
#        # pris en charge sur une prise en charge précédente
267
#        # Il peut arriver que l'on ait ajouté une prise en charge de
268
#        # traitement alors que tous les actes pour le diag ne sont pas encore facturés
269
#        try:
270
#            hc = CmppHealthCareTreatment.objects.\
271
#                filter(patient=self.patient).latest('start_date')
272
#        except:
273
#            return (False, None)
274
#        if not hc:
275
#            return (False, None)
276
#        if self.date < hc.start_date or self.date > hc.end_date:
277
#            return (False, None)
278
#        # Les acts facturés déja couvert par la prise en charge sont pointés
279
#        # dans hc.act_set.all()
280
#        nb_acts_billed = len(hc.act_set.all())
281
#        if nb_acts_billed >= hc.get_act_number():
282
#            return (False, None)
283
#        # Il faut ajouter les actes facturables non encore facturés qui précède cet
284
#        # acte
285
#        acts_billable = [a for a in self.patient.act_set.\
286
#            filter(is_billed=False).order_by('date') \
287
#            if are_all_acts_of_the_day_locked(a.date) and \
288
#            a.is_state('VALIDE') and a.is_billable()]
289
#        count = 0
290
#        for a in acts_billable:
291
#            if nb_acts_billed + count >= hc.get_act_number():
292
#                return (False, None)
293
#            if a.date >= hc.start_date and a.date <= hc.end_date:
294
#                if a.id == self.id:
295
#                    return (True, hc)
296
#                count = count + 1
297
#        return (False, None)
298
# END Specific to cmpp healthcare
299

    
300
    def duration(self):
301
        '''Return a displayable duration for this field.'''
302
        hours, remainder = divmod(self._duration, 60)
303
        return '%02d:%02d' % (hours, remainder)
304

    
305
    def __unicode__(self):
306
        return u'{0} le {1} pour {2} avec {3}'.format(
307
                self.act_type, self.date, self.patient,
308
                ', '.join(map(unicode, self.doctors.all())))
309

    
310
    def __repr__(self):
311
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
312

    
313
    def cancel(self):
314
        '''Parent event is canceled completely, or partially, act upon it.
315
        '''
316
        new_act = self.actvalidationstate_set.count() > 1
317
        if self.date <= date.today():
318
            if new_act:
319
                self.set_state('ANNUL_NOUS', get_request().user)
320
            self.parent_event = None
321
            self.save()
322
        else:
323
            self.delete()
324

    
325
    class Meta:
326
        verbose_name = u"Acte"
327
        verbose_name_plural = u"Actes"
328
        ordering = ['-date', 'patient']
329

    
330

    
331
class EventActManager(EventManager):
332

    
333
    def create_patient_appointment(self, creator, title, patient, participants,
334
            act_type, service, start_datetime, end_datetime, description='',
335
            room=None, note=None, **rrule_params):
336
        """
337
        This method allow you to create a new patient appointment quickly
338

    
339
        Args:
340
            title: patient appointment title (str)
341
            patient: Patient object
342
            participants: List of CalebasseUser (therapists)
343
            act_type: ActType object
344
            service: Service object. Use session service by defaut
345
            start_datetime: datetime with the start date and time
346
            end_datetime: datetime with the end date and time
347
            freq, count, until, byweekday, rrule_params:
348
            follow the ``dateutils`` API (see http://labix.org/python-dateutil)
349

    
350
        Example:
351
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
352
            method)
353
        """
354

    
355
        event_type, created = EventType.objects.get_or_create(
356
                label=u"Rendez-vous patient"
357
                )
358

    
359
        act_event = EventAct.objects.create(
360
                title=title,
361
                event_type=event_type,
362
                patient=patient,
363
                act_type=act_type,
364
                date=start_datetime,
365
                )
366
        act_event.doctors = participants
367
        ActValidationState(act=act_event, state_name='NON_VALIDE',
368
            author=creator, previous_state=None).save()
369

    
370
        return self._set_event(act_event, participants, description,
371
                services=[service], start_datetime=start_datetime,
372
                end_datetime=end_datetime,
373
                room=room, note=note, **rrule_params)
374

    
375

    
376
class ValidationMessage(ServiceLinkedAbstractModel):
377
    validation_date = models.DateTimeField()
378
    what = models.CharField(max_length=256)
379
    who = models.ForeignKey(User)
380
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)