Project

General

Profile

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

calebasse / calebasse / actes / models.py @ d6400658

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 self.id:
177
            self.save()
178
        if not author:
179
            raise Exception('Missing author to set state')
180
        if not state_name in VALIDATION_STATES.keys():
181
            raise Exception("Etat d'acte non existant %s")
182
        current_state = self.get_state()
183
        ActValidationState(act=self, state_name=state_name,
184
            author=author, previous_state=current_state).save()
185

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

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

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

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

    
302
    def save(self, *args, **kwargs):
303
        super(Act, self).save(*args, **kwargs)
304

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

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

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

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

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

    
335

    
336
class EventActManager(EventManager):
337

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

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

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

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

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

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

    
380

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