Project

General

Profile

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

calebasse / calebasse / actes / models.py @ 4e0fb78c

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'Validaté automatiquement')
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
    is_lost = models.BooleanField(default=False,
82
            verbose_name=u'Acte perdu', db_index=True)
83
    switch_billable = models.BooleanField(default=False,
84
            verbose_name=u'Inverser type facturable')
85
    healthcare = models.ForeignKey('dossiers.HealthCare',
86
            blank=True,
87
            null=True,
88
            verbose_name=u'Prise en charge utilisée pour facturer (CMPP)')
89
    transport_company = models.ForeignKey('ressources.TransportCompany',
90
            blank=True,
91
            null=True,
92
            verbose_name=u'Compagnie de transport')
93
    transport_type = models.ForeignKey('ressources.TransportType',
94
            blank=True,
95
            null=True,
96
            verbose_name=u'Type de transport')
97
    doctors = models.ManyToManyField('personnes.Worker',
98
            limit_choices_to={'type__intervene': True},
99
            verbose_name=u'Intervenants')
100
    pause = models.BooleanField(default=False,
101
            verbose_name=u'Pause facturation', db_index=True)
102
    parent_event = models.ForeignKey('agenda.Event',
103
            verbose_name=u'Rendez-vous lié',
104
            blank=True, null=True,
105
            on_delete=models.SET_NULL)
106
    VALIDATION_CODE_CHOICES = (
107
            ('absent', u'Absent'),
108
            ('present', u'Présent'),
109
            )
110
    attendance = models.CharField(max_length=16,
111
            choices=VALIDATION_CODE_CHOICES,
112
            default='absent',
113
            verbose_name=u'Présence')
114
    comment = models.TextField(u'Commentaire')
115
    old_id = models.CharField(max_length=256,
116
            verbose_name=u'Ancien ID', blank=True, null=True)
117

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

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

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

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

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

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

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

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

    
188
    def is_billable(self):
189
        if (self.act_type.billable and not self.switch_billable) or \
190
                (not self.act_type.billable and self.switch_billable):
191
            return True
192

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

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

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

    
304
    def save(self, *args, **kwargs):
305
        super(Act, self).save(*args, **kwargs)
306

    
307
    def duration(self):
308
        '''Return a displayable duration for this field.'''
309
        hours, remainder = divmod(self._duration, 60)
310
        return '%02d:%02d' % (hours, remainder)
311

    
312
    def __unicode__(self):
313
        return u'{0} le {1} pour {2} avec {3}'.format(
314
                self.act_type, self.date, self.patient,
315
                ', '.join(map(unicode, self.doctors.all())))
316

    
317
    def __repr__(self):
318
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
319

    
320
    def cancel(self):
321
        '''Parent event is canceled completely, or partially, act upon it.
322
        '''
323
        new_act = self.actvalidationstate_set.count() > 1
324
        if self.date <= date.today():
325
            if new_act:
326
                self.set_state('ANNUL_NOUS', get_request().user)
327
            self.parent_event = None
328
            self.save()
329
        else:
330
            self.delete()
331

    
332
    class Meta:
333
        verbose_name = u"Acte"
334
        verbose_name_plural = u"Actes"
335
        ordering = ['-date', 'patient']
336

    
337

    
338
class EventActManager(EventManager):
339

    
340
    def create_patient_appointment(self, creator, title, patient, participants,
341
            act_type, service, start_datetime, end_datetime, description='',
342
            room=None, note=None, **rrule_params):
343
        """
344
        This method allow you to create a new patient appointment quickly
345

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

    
357
        Example:
358
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
359
            method)
360
        """
361

    
362
        event_type, created = EventType.objects.get_or_create(
363
                label=u"Rendez-vous patient"
364
                )
365

    
366
        act_event = EventAct.objects.create(
367
                title=title,
368
                event_type=event_type,
369
                patient=patient,
370
                act_type=act_type,
371
                date=start_datetime,
372
                )
373
        act_event.doctors = participants
374
        ActValidationState(act=act_event, state_name='NON_VALIDE',
375
            author=creator, previous_state=None).save()
376

    
377
        return self._set_event(act_event, participants, description,
378
                services=[service], start_datetime=start_datetime,
379
                end_datetime=end_datetime,
380
                room=room, note=note, **rrule_params)
381

    
382

    
383
class ValidationMessage(ServiceLinkedAbstractModel):
384
    validation_date = models.DateTimeField()
385
    what = models.CharField(max_length=256)
386
    who = models.ForeignKey(User)
387
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)