Project

General

Profile

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

calebasse / calebasse / actes / models.py @ b93b5302

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
    @property
138
    def comment(self):
139
        if self.parent_event:
140
            return self.parent_event.description
141
        return None
142

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

    
162
    def is_new(self):
163
        return (not self.get_state() or self.is_state('NON_VALIDE'))
164

    
165
    def is_absent(self):
166
        state = self.get_state()
167
        if state and state.state_name in ('ABS_NON_EXC', 'ABS_EXC', 'ABS_INTER', 'ANNUL_NOUS',
168
                'ANNUL_FAMILLE', 'REPORTE', 'ABS_ESS_PPS', 'ENF_HOSP'):
169
            return True
170
        return False
171

    
172
    def is_present(self):
173
        return (not self.is_new() and not self.is_absent())
174

    
175
    def get_state(self):
176
        try:
177
            return self.last_validation_state
178
        except:
179
            return None
180

    
181
    def is_state(self, state_name):
182
        state = self.get_state()
183
        if state and state.state_name == state_name:
184
            return True
185
        return False
186

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

    
212
    def is_billable(self):
213
        billable = self.act_type.billable
214
        if (billable and not self.switch_billable) or \
215
                (not billable and self.switch_billable):
216
            return True
217
        return False
218

    
219
    # START Specific to sessad healthcare
220
    def was_covered_by_notification(self):
221
        from calebasse.dossiers.models import SessadHealthCareNotification
222
        notifications = \
223
            SessadHealthCareNotification.objects.filter(patient=self.patient,
224
            start_date__lte=self.date, end_date__gte=self.date)
225
        if notifications:
226
            return True
227
    # END Specific to sessad healthcare
228

    
229
    def save(self, *args, **kwargs):
230
        super(Act, self).save(*args, **kwargs)
231

    
232
    def duration(self):
233
        '''Return a displayable duration for this field.'''
234
        hours, remainder = divmod(self._duration, 60)
235
        return '%02d:%02d' % (hours, remainder)
236

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

    
247
    def __repr__(self):
248
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
249

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

    
262
    def get_invoice_number(self):
263
        try:
264
            if self.is_billed:
265
                return self.invoice_set.order_by('-number')[0].number
266
        except:
267
            pass
268
        return None
269

    
270
    def delete(self):
271
        obj_id = self.id
272
        super(Act, self).delete()
273

    
274
    class Meta:
275
        verbose_name = u"Acte"
276
        verbose_name_plural = u"Actes"
277
        ordering = ['-date', 'patient']
278

    
279

    
280
class ValidationMessage(ServiceLinkedAbstractModel):
281
    validation_date = models.DateTimeField()
282
    what = models.CharField(max_length=256)
283
    who = models.ForeignKey(User)
284
    when = models.DateTimeField(auto_now_add=True)
(4-4/9)