Project

General

Profile

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

calebasse / calebasse / actes / models.py @ b5f052b7

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

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

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

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

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

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

    
165
    def get_state(self):
166
#        states = sorted(self.actvalidationstate_set.all(),
167
#                key=lambda avs: avs.created, reverse=True)
168
#        if states:
169
#            return states[0]
170
#        return None
171
        try:
172
            return self.actvalidationstate_set.latest('created')
173
        except:
174
            return None
175

    
176
    def is_state(self, state_name):
177
        state = self.get_state()
178
        if state and state.state_name == state_name:
179
            return True
180
        return False
181

    
182
    def set_state(self, state_name, author, auto=False,
183
            change_state_check=True):
184
        if not self.id:
185
            self.save()
186
        if not author:
187
            raise Exception('Missing author to set state')
188
        if not state_name in VALIDATION_STATES.keys():
189
            raise Exception("Etat d'acte non existant %s")
190
        current_state = self.get_state()
191
        ActValidationState(act=self, state_name=state_name,
192
            author=author, previous_state=current_state).save()
193
        if state_name == 'VALIDE':
194
            self.valide = True
195
        else:
196
            self.valide = False
197
        self.save()
198

    
199
    def is_billable(self):
200
        billable = self.act_type.billable
201
        if (billable and not self.switch_billable) or \
202
                (not billable and self.switch_billable):
203
            return True
204
        return False
205

    
206
    # START Specific to sessad healthcare
207
    def was_covered_by_notification(self):
208
        from calebasse.dossiers.models import SessadHealthCareNotification
209
        notifications = \
210
            SessadHealthCareNotification.objects.filter(patient=self.patient,
211
            start_date__lte=self.date, end_date__gte=self.date)
212
        if notifications:
213
            return True
214
    # END Specific to sessad healthcare
215

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

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

    
317
    def save(self, *args, **kwargs):
318
        super(Act, self).save(*args, **kwargs)
319

    
320
    def duration(self):
321
        '''Return a displayable duration for this field.'''
322
        hours, remainder = divmod(self._duration, 60)
323
        return '%02d:%02d' % (hours, remainder)
324

    
325
    def __unicode__(self):
326
        return u'{0} le {1} pour {2} avec {3}'.format(
327
                self.act_type, self.date, self.patient,
328
                ', '.join(map(unicode, self.doctors.all())))
329

    
330
    def __repr__(self):
331
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
332

    
333
    def cancel(self):
334
        '''Parent event is canceled completely, or partially, act upon it.
335
        '''
336
        new_act = self.actvalidationstate_set.count() > 1
337
        if self.date <= date.today():
338
            if new_act:
339
                self.set_state('ANNUL_NOUS', get_request().user)
340
            self.parent_event = None
341
            self.save()
342
        else:
343
            self.delete()
344

    
345
    class Meta:
346
        verbose_name = u"Acte"
347
        verbose_name_plural = u"Actes"
348
        ordering = ['-date', 'patient']
349

    
350

    
351
class EventActManager(EventManager):
352

    
353
    def create_patient_appointment(self, creator, title, patient, participants,
354
            act_type, service, start_datetime, end_datetime, description='',
355
            room=None, note=None, **rrule_params):
356
        """
357
        This method allow you to create a new patient appointment quickly
358

    
359
        Args:
360
            title: patient appointment title (str)
361
            patient: Patient object
362
            participants: List of CalebasseUser (therapists)
363
            act_type: ActType object
364
            service: Service object. Use session service by defaut
365
            start_datetime: datetime with the start date and time
366
            end_datetime: datetime with the end date and time
367
            freq, count, until, byweekday, rrule_params:
368
            follow the ``dateutils`` API (see http://labix.org/python-dateutil)
369

    
370
        Example:
371
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
372
            method)
373
        """
374

    
375
        event_type, created = EventType.objects.get_or_create(
376
                label=u"Rendez-vous patient"
377
                )
378

    
379
        act_event = EventAct.objects.create(
380
                title=title,
381
                event_type=event_type,
382
                patient=patient,
383
                act_type=act_type,
384
                date=start_datetime,
385
                )
386
        act_event.doctors = participants
387
        ActValidationState(act=act_event, state_name='NON_VALIDE',
388
            author=creator, previous_state=None).save()
389

    
390
        return self._set_event(act_event, participants, description,
391
                services=[service], start_datetime=start_datetime,
392
                end_datetime=end_datetime,
393
                room=room, note=note, **rrule_params)
394

    
395

    
396
class ValidationMessage(ServiceLinkedAbstractModel):
397
    validation_date = models.DateTimeField()
398
    what = models.CharField(max_length=256)
399
    who = models.ForeignKey(User)
400
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)