Project

General

Profile

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

calebasse / calebasse / actes / models.py @ bcb3b530

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
    VALIDATION_CODE_CHOICES = (
104
            ('absent', u'Absent'),
105
            ('present', u'Présent'),
106
            )
107
    attendance = models.CharField(max_length=16,
108
            choices=VALIDATION_CODE_CHOICES,
109
            default='absent',
110
            verbose_name=u'Présence')
111
    comment = models.TextField(u'Commentaire')
112
    old_id = models.CharField(max_length=256,
113
            verbose_name=u'Ancien ID', blank=True, null=True)
114

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

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

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

    
147
    def is_absent(self):
148
        state = self.get_state()
149
        if state and state.state_name in ('ABS_NON_EXC', 'ABS_EXC', 'ABS_INTER', 'ANNUL_NOUS',
150
                'ANNUL_FAMILLE', 'REPORTE', 'ABS_ESS_PPS', 'ENF_HOSP'):
151
            return True
152
        return False
153

    
154
    def get_state(self):
155
        states = sorted(self.actvalidationstate_set.all(),
156
                key=lambda avs: avs.created, reverse=True)
157
        if states:
158
            return states[0]
159
        return None
160

    
161
    def is_state(self, state_name):
162
        state = self.get_state()
163
        if state and state.state_name == state_name:
164
            return True
165
        return False
166

    
167
    def set_state(self, state_name, author, auto=False,
168
            change_state_check=True):
169
        if not author:
170
            raise Exception('Missing author to set state')
171
        if not state_name in VALIDATION_STATES.keys():
172
            raise Exception("Etat d'acte non existant %s")
173
        current_state = self.get_state()
174
        ActValidationState(act=self, state_name=state_name,
175
            author=author, previous_state=current_state).save()
176

    
177
    def is_billable(self):
178
        if (self.act_type.billable and not self.switch_billable) or \
179
                (not self.act_type.billable and self.switch_billable):
180
            return True
181

    
182
    # START Specific to sessad healthcare
183
    def was_covered_by_notification(self):
184
        from calebasse.dossiers.models import SessadHealthCareNotification
185
        notifications = \
186
            SessadHealthCareNotification.objects.filter(patient=self.patient,
187
            start_date__lte=self.date, end_date__gte=self.date)
188
        if notifications:
189
            return True
190
    # END Specific to sessad healthcare
191

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

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

    
293
    def duration(self):
294
        '''Return a displayable duration for this field.'''
295
        hours, remainder = divmod(self._duration, 60)
296
        return '%02d:%02d' % (hours, remainder)
297

    
298
    def __unicode__(self):
299
        return u'{0} le {1} pour {2} avec {3}'.format(
300
                self.act_type, self.date, self.patient,
301
                ', '.join(map(unicode, self.doctors.all())))
302

    
303
    def __repr__(self):
304
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
305

    
306
    def cancel(self):
307
        '''Parent event is canceled completely, or partially, act upon it.
308
        '''
309
        new_act = self.actvalidationstate_set.count() > 1
310
        if self.date <= date.today():
311
            if new_act:
312
                self.set_state('ANNUL_NOUS', get_request().user)
313
            self.parent_event = None
314
            self.save()
315
        else:
316
            self.delete()
317

    
318
    class Meta:
319
        verbose_name = u"Acte"
320
        verbose_name_plural = u"Actes"
321
        ordering = ['-date', 'patient']
322

    
323

    
324
class EventActManager(EventManager):
325

    
326
    def create_patient_appointment(self, creator, title, patient, participants,
327
            act_type, service, start_datetime, end_datetime, description='',
328
            room=None, note=None, **rrule_params):
329
        """
330
        This method allow you to create a new patient appointment quickly
331

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

    
343
        Example:
344
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
345
            method)
346
        """
347

    
348
        event_type, created = EventType.objects.get_or_create(
349
                label=u"Rendez-vous patient"
350
                )
351

    
352
        act_event = EventAct.objects.create(
353
                title=title,
354
                event_type=event_type,
355
                patient=patient,
356
                act_type=act_type,
357
                date=start_datetime,
358
                )
359
        act_event.doctors = participants
360
        ActValidationState(act=act_event, state_name='NON_VALIDE',
361
            author=creator, previous_state=None).save()
362

    
363
        return self._set_event(act_event, participants, description,
364
                services=[service], start_datetime=start_datetime,
365
                end_datetime=end_datetime,
366
                room=room, note=note, **rrule_params)
367

    
368

    
369
class ValidationMessage(ServiceLinkedAbstractModel):
370
    validation_date = models.DateTimeField()
371
    what = models.CharField(max_length=256)
372
    who = models.ForeignKey(User)
373
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)