Project

General

Profile

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

calebasse / calebasse / actes / models.py @ 1edcbebd

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
from calebasse.actes.validation_states import VALIDATION_STATES
8
from calebasse.ressources.models import ServiceLinkedAbstractModel
9
from ..middleware.request import get_request
10

    
11
class ActValidationState(models.Model):
12

    
13
    class Meta:
14
        app_label = 'actes'
15
        ordering = ('-created',)
16

    
17
    act = models.ForeignKey('actes.Act',
18
        verbose_name=u'Acte', editable=False)
19
    state_name = models.CharField(max_length=150)
20
    created = models.DateTimeField(u'Création', auto_now_add=True)
21
    author = \
22
        models.ForeignKey(User,
23
        verbose_name=u'Auteur', editable=False, blank=True, null=True,
24
        on_delete=models.SET_NULL)
25
    previous_state = models.ForeignKey('ActValidationState',
26
        verbose_name=u'Etat précédent',
27
        editable=False, blank=True, null=True)
28
    # To record if the validation has be done by the automated validation
29
    auto = models.BooleanField(default=False,
30
            verbose_name=u'Validaté automatiquement')
31

    
32
    def __repr__(self):
33
        return self.state_name + ' ' + str(self.created)
34

    
35
    def __unicode__(self):
36
        return VALIDATION_STATES[self.state_name]
37

    
38

    
39
class ActManager(models.Manager):
40
    def for_today(self, today=None):
41
        today = today or date.today()
42
        return self.filter(date=today)
43

    
44
    def create_act(self, author=None, **kwargs):
45
        act = Act(**kwargs)
46
        last_validation_state = ActValidationState.objects.create(
47
                act=act,state_name='NON_VALIDE',
48
                author=author, previous_state=None)
49
        act.last_validation_state = last_validation_state
50
        act.save()
51
        return act
52

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

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

    
65

    
66
class Act(models.Model):
67
    objects = ActManager()
68

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

    
124
    @property
125
    def event(self):
126
        if self.parent_event:
127
            return self.parent_event.today_occurrence(self.date)
128
        return None
129

    
130
    @property
131
    def start_datetime(self):
132
        event = self.event
133
        if event:
134
            return event.start_datetime
135
        return self.date
136

    
137
    def get_hc_tag(self):
138
        if self.healthcare:
139
            beg = None
140
            try:
141
                self.healthcare.cmpphealthcaretreatment
142
                beg = 'T'
143
            except:
144
                pass
145
            try:
146
                self.healthcare.cmpphealthcarediagnostic
147
                beg = 'D'
148
            except:
149
                pass
150
            if beg:
151
                acts = list(self.healthcare.act_set.order_by('date').values_list('id', flat=True))
152
                beg += str(acts.index(self.id) + 1)
153
                return beg
154
        return None
155

    
156
    def is_new(self):
157
        return (not self.get_state() or self.is_state('NON_VALIDE'))
158

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

    
166
    def is_present(self):
167
        return (not self.is_new() and not self.is_absent())
168

    
169
    def get_state(self):
170
        try:
171
            return self.last_validation_state
172
        except:
173
            return None
174

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

    
181
    def set_state(self, state_name, author, auto=False,
182
            change_state_check=True):
183
        if not self.id:
184
            self.save()
185
        if self.is_billed:
186
            raise Exception('Billed act state can not be modified')
187
        if not author:
188
            raise Exception('Missing author to set state')
189
        if not state_name in VALIDATION_STATES.keys():
190
            raise Exception("Etat d'acte non existant %s")
191
        current_state = self.get_state()
192
        last_validation_state = ActValidationState.objects.create(
193
                act=self,
194
                state_name=state_name,
195
                author=author,
196
                previous_state=current_state)
197
        self.last_validation_state = last_validation_state
198
        if state_name == 'VALIDE':
199
            self.valide = True
200
        else:
201
            self.valide = False
202
        get_request().record('act-update', '{obj_id} state changed to {state} by {user} from {ip}',
203
                              obj_id=self.id, state=last_validation_state, user=author)
204
        self.save()
205

    
206
    def is_billable(self):
207
        billable = self.act_type.billable
208
        if (billable and not self.switch_billable) or \
209
                (not billable and self.switch_billable):
210
            return True
211
        return False
212

    
213
    # START Specific to sessad healthcare
214
    def was_covered_by_notification(self):
215
        from calebasse.dossiers.models import SessadHealthCareNotification
216
        notifications = \
217
            SessadHealthCareNotification.objects.filter(patient=self.patient,
218
            start_date__lte=self.date, end_date__gte=self.date)
219
        if notifications:
220
            return True
221
    # END Specific to sessad healthcare
222

    
223
    def save(self, *args, **kwargs):
224
        if self.parent_event and not self.parent_event.canceled:
225
            super(Act, self).save(*args, **kwargs)
226

    
227
    def duration(self):
228
        '''Return a displayable duration for this field.'''
229
        hours, remainder = divmod(self._duration, 60)
230
        return '%02d:%02d' % (hours, remainder)
231

    
232
    def __unicode__(self):
233
        if self.time:
234
            return u'{0} le {1} à {2} pour {3} avec {4}'.format(
235
                    self.act_type, self.date.strftime('%d/%m/%Y'),
236
                    self.time.strftime('%H:%M'), self.patient,
237
                    ', '.join(map(unicode, self.doctors.all())))
238
        return u'{0} le {1} pour {2} avec {3}'.format(
239
                self.act_type, self.date.strftime('%d/%m/%Y'), self.patient,
240
                ', '.join(map(unicode, self.doctors.all())))
241

    
242
    def __repr__(self):
243
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
244

    
245
    def cancel(self):
246
        '''Parent event is canceled completely, or partially, act upon it.
247
        '''
248
        new_act = self.actvalidationstate_set.count() > 1
249
        if self.date <= date.today():
250
            if new_act:
251
                self.set_state('ANNUL_NOUS', get_request().user)
252
            self.parent_event = None
253
            self.save()
254
        else:
255
            self.delete()
256

    
257
    def get_invoice_number(self):
258
        try:
259
            if self.is_billed:
260
                return self.invoice_set.order_by('-number')[0].number
261
        except:
262
            pass
263
        return None
264

    
265
    def delete(self):
266
        obj_id = self.id
267
        super(Act, self).delete()
268

    
269
    class Meta:
270
        verbose_name = u"Acte"
271
        verbose_name_plural = u"Actes"
272
        ordering = ['-date', 'patient']
273

    
274

    
275
class ValidationMessage(ServiceLinkedAbstractModel):
276
    validation_date = models.DateTimeField()
277
    what = models.CharField(max_length=256)
278
    who = models.ForeignKey(User)
279
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)