Project

General

Profile

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

calebasse / calebasse / actes / models.py @ b8fe32bb

1 1097fd0a Benjamin Dauvergne
# -*- coding: utf-8 -*-
2 50e85412 Benjamin Dauvergne
from datetime import date, time
3 76974b6f Benjamin Dauvergne
4 1097fd0a Benjamin Dauvergne
from django.db import models
5 d602f09e Mikaël Ates
from django.contrib.auth.models import User
6 1097fd0a Benjamin Dauvergne
7 3c5df84d Jérôme Schneider
from calebasse.actes.validation_states import VALIDATION_STATES
8 0d46dc26 Mikaël Ates
from calebasse.ressources.models import ServiceLinkedAbstractModel
9 5c2d0ea2 Benjamin Dauvergne
from ..middleware.request import get_request
10 1097fd0a Benjamin Dauvergne
11 d602f09e Mikaël Ates
class ActValidationState(models.Model):
12
13
    class Meta:
14
        app_label = 'actes'
15 8bf43f56 Benjamin Dauvergne
        ordering = ('-created',)
16 d602f09e Mikaël Ates
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 06af80c6 Mikaël Ates
        verbose_name=u'Auteur', editable=False, blank=True, null=True,
24
        on_delete=models.SET_NULL)
25 d602f09e Mikaël Ates
    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 a0440975 Mikaël Ates
    auto = models.BooleanField(default=False,
30 70268033 Mikaël Ates
            verbose_name=u'Validaté automatiquement')
31 d602f09e Mikaël Ates
32 a4233531 Benjamin Dauvergne
    def __repr__(self):
33 ef86b6e5 Mikaël Ates
        return self.state_name + ' ' + str(self.created)
34
35 a4233531 Benjamin Dauvergne
    def __unicode__(self):
36
        return VALIDATION_STATES[self.state_name]
37
38 4704ebbc Mikaël Ates
39 76974b6f Benjamin Dauvergne
class ActManager(models.Manager):
40 50e85412 Benjamin Dauvergne
    def for_today(self, today=None):
41
        today = today or date.today()
42
        return self.filter(date=today)
43
44 76974b6f Benjamin Dauvergne
    def create_act(self, author=None, **kwargs):
45 981abc28 Jérôme Schneider
        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 76974b6f Benjamin Dauvergne
        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 96f613c6 Benjamin Dauvergne
class Act(models.Model):
67 76974b6f Benjamin Dauvergne
    objects = ActManager()
68
69 a0440975 Mikaël Ates
    patient = models.ForeignKey('dossiers.PatientRecord')
70 e9fb7b88 Benjamin Dauvergne
    date = models.DateField(u'Date', db_index=True)
71
    time = models.TimeField(u'Heure', blank=True, null=True, default=time(), db_index=True)
72 13f3e0a7 Benjamin Dauvergne
    _duration = models.IntegerField(u'Durée en minutes', blank=True, null=True, default=0)
73 96f613c6 Benjamin Dauvergne
    act_type = models.ForeignKey('ressources.ActType',
74
            verbose_name=u'Type d\'acte')
75 a0440975 Mikaël Ates
    validation_locked = models.BooleanField(default=False,
76 e9fb7b88 Benjamin Dauvergne
            verbose_name=u'Vérouillage', db_index=True)
77 33375338 Mikaël Ates
    is_billed = models.BooleanField(default=False,
78 e9fb7b88 Benjamin Dauvergne
            verbose_name=u'Facturé', db_index=True)
79 ece5949c Mikaël Ates
    is_lost = models.BooleanField(default=False,
80
            verbose_name=u'Acte perdu', db_index=True)
81 981abc28 Jérôme Schneider
    last_validation_state = models.ForeignKey(ActValidationState,
82
            related_name='+',
83
            null=True, default=None,
84
            on_delete=models.SET_NULL)
85 f8d74927 Mikaël Ates
    valide = models.BooleanField(default=False,
86 90ff0811 Jérôme Schneider
            verbose_name=u'Validé', db_index=True)
87 33375338 Mikaël Ates
    switch_billable = models.BooleanField(default=False,
88
            verbose_name=u'Inverser type facturable')
89 c0014064 Mikaël Ates
    healthcare = models.ForeignKey('dossiers.HealthCare',
90
            blank=True,
91
            null=True,
92 8a3f3db7 Mikaël Ates
            on_delete=models.SET_NULL,
93 ea2e8d11 Mikaël Ates
            verbose_name=u'Prise en charge utilisée pour facturer (CMPP)')
94 96f613c6 Benjamin Dauvergne
    transport_company = models.ForeignKey('ressources.TransportCompany',
95
            blank=True,
96
            null=True,
97 8a3f3db7 Mikaël Ates
            on_delete=models.SET_NULL,
98 96f613c6 Benjamin Dauvergne
            verbose_name=u'Compagnie de transport')
99
    transport_type = models.ForeignKey('ressources.TransportType',
100
            blank=True,
101
            null=True,
102 8a3f3db7 Mikaël Ates
            on_delete=models.SET_NULL,
103 96f613c6 Benjamin Dauvergne
            verbose_name=u'Type de transport')
104 3c279673 Benjamin Dauvergne
    doctors = models.ManyToManyField('personnes.Worker',
105 d602f09e Mikaël Ates
            limit_choices_to={'type__intervene': True},
106 9291e362 Mikaël Ates
            verbose_name=u'Intervenants')
107 bc7e290e Mikaël Ates
    pause = models.BooleanField(default=False,
108 e9fb7b88 Benjamin Dauvergne
            verbose_name=u'Pause facturation', db_index=True)
109 0906807f Mikaël Ates
    parent_event = models.ForeignKey('agenda.Event',
110 76974b6f Benjamin Dauvergne
            verbose_name=u'Rendez-vous lié',
111 39019102 Benjamin Dauvergne
            blank=True, null=True,
112
            on_delete=models.SET_NULL)
113 76974b6f Benjamin Dauvergne
    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 99777656 Benjamin Dauvergne
    old_id = models.CharField(max_length=256,
122
            verbose_name=u'Ancien ID', blank=True, null=True)
123 76974b6f Benjamin Dauvergne
124
    @property
125
    def event(self):
126
        if self.parent_event:
127 5c2d0ea2 Benjamin Dauvergne
            return self.parent_event.today_occurrence(self.date)
128 76974b6f Benjamin Dauvergne
        return None
129
130
    @property
131 a1759d39 Benjamin Dauvergne
    def start_datetime(self):
132 76974b6f Benjamin Dauvergne
        event = self.event
133
        if event:
134 a1759d39 Benjamin Dauvergne
            return event.start_datetime
135
        return self.date
136 55a8e535 Benjamin Dauvergne
137 b8fe32bb Mikaël Ates
    @property
138
    def comment(self):
139
        if self.parent_event:
140
            return self.parent_event.description
141
        return None
142
143 19b3ab02 Mikaël Ates
    def get_hc_tag(self):
144
        if self.healthcare:
145 7f1f3811 Mikaël Ates
            beg = None
146 19b3ab02 Mikaël Ates
            try:
147
                self.healthcare.cmpphealthcaretreatment
148 7f1f3811 Mikaël Ates
                beg = 'T'
149 19b3ab02 Mikaël Ates
            except:
150
                pass
151
            try:
152
                self.healthcare.cmpphealthcarediagnostic
153 7f1f3811 Mikaël Ates
                beg = 'D'
154 19b3ab02 Mikaël Ates
            except:
155
                pass
156 7f1f3811 Mikaël Ates
            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 19b3ab02 Mikaël Ates
        return None
161
162 b5877252 Benjamin Dauvergne
    def is_new(self):
163 dee0e636 Mikaël Ates
        return (not self.get_state() or self.is_state('NON_VALIDE'))
164 b5877252 Benjamin Dauvergne
165 a0440975 Mikaël Ates
    def is_absent(self):
166 5f4c5dd2 Frédéric Péters
        state = self.get_state()
167 08bf3477 Mikaël Ates
        if state and state.state_name in ('ABS_NON_EXC', 'ABS_EXC', 'ABS_INTER', 'ANNUL_NOUS',
168 6c9a3a0d Mikaël Ates
                'ANNUL_FAMILLE', 'REPORTE', 'ABS_ESS_PPS', 'ENF_HOSP'):
169 a0440975 Mikaël Ates
            return True
170 5f4c5dd2 Frédéric Péters
        return False
171 a0440975 Mikaël Ates
172 0f2084f9 Mikaël Ates
    def is_present(self):
173
        return (not self.is_new() and not self.is_absent())
174
175 a0440975 Mikaël Ates
    def get_state(self):
176 c743d1bf Mikaël Ates
        try:
177
            return self.last_validation_state
178
        except:
179
            return None
180 a0440975 Mikaël Ates
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 d6400658 Benjamin Dauvergne
        if not self.id:
190
            self.save()
191 65ffd25d Mikaël Ates
        if self.is_billed:
192
            raise Exception('Billed act state can not be modified')
193 a0440975 Mikaël Ates
        if not author:
194
            raise Exception('Missing author to set state')
195 4704ebbc Mikaël Ates
        if not state_name in VALIDATION_STATES.keys():
196 a0440975 Mikaël Ates
            raise Exception("Etat d'acte non existant %s")
197
        current_state = self.get_state()
198 55dfa03a Jérôme Schneider
        last_validation_state = ActValidationState.objects.create(
199
                act=self,
200 981abc28 Jérôme Schneider
                state_name=state_name,
201
                author=author,
202 55dfa03a Jérôme Schneider
                previous_state=current_state)
203 981abc28 Jérôme Schneider
        self.last_validation_state = last_validation_state
204 f8d74927 Mikaël Ates
        if state_name == 'VALIDE':
205
            self.valide = True
206
        else:
207
            self.valide = False
208 a01d85be Serghei MIHAI
        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 f8d74927 Mikaël Ates
        self.save()
211 a0440975 Mikaël Ates
212 33375338 Mikaël Ates
    def is_billable(self):
213 f8d74927 Mikaël Ates
        billable = self.act_type.billable
214
        if (billable and not self.switch_billable) or \
215
                (not billable and self.switch_billable):
216 33375338 Mikaël Ates
            return True
217 f8d74927 Mikaël Ates
        return False
218 33375338 Mikaël Ates
219 ef86b6e5 Mikaël Ates
    # START Specific to sessad healthcare
220
    def was_covered_by_notification(self):
221 0906807f Mikaël Ates
        from calebasse.dossiers.models import SessadHealthCareNotification
222 ef86b6e5 Mikaël Ates
        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 433b67bb Benjamin Dauvergne
    def save(self, *args, **kwargs):
230 c4d2d185 Serghei MIHAI
        if self.parent_event and not self.parent_event.canceled:
231
            super(Act, self).save(*args, **kwargs)
232 433b67bb Benjamin Dauvergne
233 76974b6f Benjamin Dauvergne
    def duration(self):
234
        '''Return a displayable duration for this field.'''
235
        hours, remainder = divmod(self._duration, 60)
236
        return '%02d:%02d' % (hours, remainder)
237 c0014064 Mikaël Ates
238 55a8e535 Benjamin Dauvergne
    def __unicode__(self):
239 6635f582 Mikaël Ates
        if self.time:
240
            return u'{0} le {1} à {2} pour {3} avec {4}'.format(
241 dc526631 Mikaël Ates
                    self.act_type, self.date.strftime('%d/%m/%Y'),
242
                    self.time.strftime('%H:%M'), self.patient,
243 6635f582 Mikaël Ates
                    ', '.join(map(unicode, self.doctors.all())))
244 317c2f75 Benjamin Dauvergne
        return u'{0} le {1} pour {2} avec {3}'.format(
245 dc526631 Mikaël Ates
                self.act_type, self.date.strftime('%d/%m/%Y'), self.patient,
246 55a8e535 Benjamin Dauvergne
                ', '.join(map(unicode, self.doctors.all())))
247
248
    def __repr__(self):
249
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
250
251 5c2d0ea2 Benjamin Dauvergne
    def cancel(self):
252
        '''Parent event is canceled completely, or partially, act upon it.
253
        '''
254
        new_act = self.actvalidationstate_set.count() > 1
255
        if self.date <= date.today():
256
            if new_act:
257
                self.set_state('ANNUL_NOUS', get_request().user)
258
            self.parent_event = None
259
            self.save()
260
        else:
261
            self.delete()
262
263 09eb39f7 Mikaël Ates
    def get_invoice_number(self):
264
        try:
265
            if self.is_billed:
266
                return self.invoice_set.order_by('-number')[0].number
267
        except:
268
            pass
269
        return None
270
271 a01d85be Serghei MIHAI
    def delete(self):
272
        obj_id = self.id
273
        super(Act, self).delete()
274
275 55a8e535 Benjamin Dauvergne
    class Meta:
276
        verbose_name = u"Acte"
277
        verbose_name_plural = u"Actes"
278
        ordering = ['-date', 'patient']
279
280 96f613c6 Benjamin Dauvergne
281 0d46dc26 Mikaël Ates
class ValidationMessage(ServiceLinkedAbstractModel):
282
    validation_date = models.DateTimeField()
283
    what = models.CharField(max_length=256)
284
    who = models.ForeignKey(User)
285
    when = models.DateTimeField(auto_now_add=True)