Project

General

Profile

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

calebasse / calebasse / actes / models.py @ 33375338

1
# -*- coding: utf-8 -*-
2
from django.db import models
3
from django.contrib.auth.models import User
4

    
5
from calebasse.agenda.models import Event, EventType
6
from calebasse.agenda.managers import EventManager
7

    
8
from validation_states import VALIDATION_STATES
9

    
10

    
11
class ActValidationState(models.Model):
12

    
13
    class Meta:
14
        app_label = 'actes'
15

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

    
30
    def __unicode__(self):
31
        return self.state_name + ' ' + str(self.created)
32

    
33

    
34
class Act(models.Model):
35
    patient = models.ForeignKey('dossiers.PatientRecord')
36
    date = models.DateTimeField()
37
    act_type = models.ForeignKey('ressources.ActType',
38
            verbose_name=u'Type d\'acte')
39
    validation_locked = models.BooleanField(default=False,
40
            verbose_name=u'Vérouillage')
41
    is_billed = models.BooleanField(default=False,
42
            verbose_name=u'Facturé')
43
    switch_billable = models.BooleanField(default=False,
44
            verbose_name=u'Inverser type facturable')
45
    transport_company = models.ForeignKey('ressources.TransportCompany',
46
            blank=True,
47
            null=True,
48
            verbose_name=u'Compagnie de transport')
49
    transport_type = models.ForeignKey('ressources.TransportType',
50
            blank=True,
51
            null=True,
52
            verbose_name=u'Type de transport')
53
    doctors = models.ManyToManyField('personnes.Worker',
54
            limit_choices_to={'type__intervene': True},
55
            verbose_name=u'Thérapeutes')
56
    histories = models.ManyToManyField('HistoryAct')
57

    
58
    def is_absent(self):
59
        if self.get_state() in ('ABS_NON_EXC', 'ABS_EXC', 'ANNUL_NOUS',
60
                'ANNUL_FAMILLE', 'ABS_ESS_PPS', 'ENF_HOSP'):
61
            return True
62

    
63
    def get_state(self):
64
        return self.actvalidationstate_set.latest('created')
65

    
66
    def is_state(self, state_name):
67
        state = self.get_state()
68
        if state and state.state_name == state_name:
69
            return True
70
        return False
71

    
72
    def set_state(self, state_name, author, auto=False,
73
            change_state_check=True):
74
        if not author:
75
            raise Exception('Missing author to set state')
76
        if not state_name in VALIDATION_STATES.keys():
77
            raise Exception("Etat d'acte non existant %s")
78
        current_state = self.get_state()
79
        ActValidationState(act=self, state_name=state_name,
80
            author=author, previous_state=current_state).save()
81

    
82
    def is_billable(self):
83
        if (self.act_type.billable and not self.switch_billable) or \
84
                (not self.act_type.billable and self.switch_billable):
85
            return True
86

    
87
    # START Specific to sessad healthcare
88
    def was_covered_by_notification(self):
89
        notifications = \
90
            SessadHealthCareNotification.objects.filter(patient=self.patient,
91
            start_date__lte=self.date, end_date__gte=self.date)
92
        if notifications:
93
            return True
94
    # END Specific to sessad healthcare
95

    
96
    def __unicode__(self):
97
        return '{0} le {1} pour {2} avec {3}'.format(
98
                self.act_type, self.date, self.patient,
99
                ', '.join(map(unicode, self.doctors.all())))
100

    
101
    def __repr__(self):
102
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
103

    
104
    class Meta:
105
        verbose_name = u"Acte"
106
        verbose_name_plural = u"Actes"
107
        ordering = ['-date', 'patient']
108

    
109

    
110
class HistoryAct(models.Model):
111
    EVENT_CHOICES = (
112
            ('NR', u'Nouveau rendez-vous'),
113
            ('AV', u'Acte validé'),
114
            ('CF', u'En cours de facturation'),
115
            ('AF', u'Acte facturé'),
116
            )
117
    date = models.DateTimeField()
118
    event_type = models.CharField(max_length=2,
119
            choices=EVENT_CHOICES)
120
    description = models.TextField(default='')
121

    
122

    
123
class EventActManager(EventManager):
124

    
125
    def create_patient_appointment(self, creator, title, patient, participants,
126
            act_type, service, start_datetime, end_datetime, description='',
127
            room=None, note=None, **rrule_params):
128
        """
129
        This method allow you to create a new patient appointment quickly
130

    
131
        Args:
132
            title: patient appointment title (str)
133
            patient: Patient object
134
            participants: List of CalebasseUser (therapists)
135
            act_type: ActType object
136
            service: Service object. Use session service by defaut
137
            start_datetime: datetime with the start date and time
138
            end_datetime: datetime with the end date and time
139
            freq, count, until, byweekday, rrule_params:
140
            follow the ``dateutils`` API (see http://labix.org/python-dateutil)
141

    
142
        Example:
143
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
144
            method)
145
        """
146

    
147
        event_type, created = EventType.objects.get_or_create(
148
                label=u"Rendez-vous patient"
149
                )
150

    
151
        history = HistoryAct.objects.create(
152
                date = datetime.now(),
153
                event_type = 'NR')
154
        act_event = EventAct.objects.create(
155
                title=title,
156
                event_type=event_type,
157
                patient=patient,
158
                act_type=act_type,
159
                date=start_datetime,
160
                histories = [history]
161
                )
162
        act_event.doctors = participants
163
        ActValidationState(act=act_event, state_name='NON_VALIDE',
164
            author=creator, previous_state=None).save()
165

    
166
        return self._set_event(act_event, participants, description,
167
                services=[service], start_datetime=start_datetime,
168
                end_datetime=end_datetime,
169
                room=room, note=note, **rrule_params)
170

    
171

    
172
class EventAct(Act, Event):
173
    objects = EventActManager()
174

    
175
    VALIDATION_CODE_CHOICES = (
176
            ('absent', u'Absent'),
177
            ('present', u'Présent'),
178
            )
179
    attendance = models.CharField(max_length=16,
180
            choices=VALIDATION_CODE_CHOICES,
181
            default='absent',
182
            verbose_name=u'Présence')
183
    convocation_sent = models.BooleanField(blank=True,
184
            verbose_name=u'Convoqué')
185

    
186
    def __unicode__(self):
187
        return 'Rdv le {0} de {1} avec {2} pour {3}'.format(
188
                self.occurrence_set.all()[0].start_time, self.patient,
189
                ', '.join(map(unicode, self.participants.all())),
190
                self.act_type)
191

    
192
    def __repr__(self):
193
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self),
194
            self.id)
195

    
196
    class Meta:
197
        verbose_name = 'Rendez-vous patient'
198
        verbose_name_plural = 'Rendez-vous patient'
199
        ordering = ['-date', 'patient']
(4-4/9)