Project

General

Profile

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

calebasse / calebasse / actes / models.py @ ef86b6e5

1
# -*- coding: utf-8 -*-
2

    
3
from django.db import models
4
from django.contrib.auth.models import User
5

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

    
9
from validation_states import VALIDATION_STATES
10

    
11

    
12
class ActValidationState(models.Model):
13

    
14
    class Meta:
15
        app_label = 'actes'
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)
24
    previous_state = models.ForeignKey('ActValidationState',
25
        verbose_name=u'Etat précédent',
26
        editable=False, blank=True, null=True)
27
    # To record if the validation has be done by the automated validation
28
    auto = models.BooleanField(default=False,
29
            verbose_name=u'Vérouillage')
30

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

    
34

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

    
55
    def is_absent(self):
56
        if self.get_state() in ('ABS_NON_EXC', 'ABS_EXC', 'ANNUL_NOUS',
57
                'ANNUL_FAMILLE', 'ABS_ESS_PPS', 'ENF_HOSP'):
58
            return True
59

    
60
    def get_state(self):
61
        return self.actvalidationstate_set.latest('created')
62

    
63
    def is_state(self, state_name):
64
        state = self.get_state()
65
        if state and state.state_name == state_name:
66
            return True
67
        return False
68

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

    
79
    # START Specific to sessad healthcare
80
    def was_covered_by_notification(self):
81
        notifications = \
82
            SessadHealthCareNotification.objects.filter(patient=self.patient,
83
            start_date__lte=self.date, end_date__gte=self.date)
84
        if notifications:
85
            return True
86
    # END Specific to sessad healthcare
87

    
88
    def __unicode__(self):
89
        return '{0} le {1} pour {2} avec {3}'.format(
90
                self.act_type, self.date, self.patient,
91
                ', '.join(map(unicode, self.doctors.all())))
92

    
93
    def __repr__(self):
94
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
95

    
96
    class Meta:
97
        verbose_name = u"Acte"
98
        verbose_name_plural = u"Actes"
99
        ordering = ['-date', 'patient']
100

    
101

    
102
class HistoryAct(models.Model):
103
    EVENT_CHOICES = (
104
            ('NR', u'Nouveau rendez-vous'),
105
            ('AV', u'Acte validé'),
106
            ('CF', u'En cours de facturation'),
107
            ('AF', u'Acte facturé'),
108
            )
109
    date = models.DateTimeField()
110
    event_type = models.CharField(max_length=2,
111
            choices=EVENT_CHOICES)
112
    description = models.TextField(default='')
113

    
114

    
115
class EventActManager(EventManager):
116

    
117
    def create_patient_appointment(self, creator, title, patient, participants,
118
            act_type, service, start_datetime, end_datetime, description='',
119
            room=None, note=None, **rrule_params):
120
        """
121
        This method allow you to create a new patient appointment quickly
122

    
123
        Args:
124
            title: patient appointment title (str)
125
            patient: Patient object
126
            participants: List of CalebasseUser (therapists)
127
            act_type: ActType object
128
            service: Service object. Use session service by defaut
129
            start_datetime: datetime with the start date and time
130
            end_datetime: datetime with the end date and time
131
            freq, count, until, byweekday, rrule_params:
132
            follow the ``dateutils`` API (see http://labix.org/python-dateutil)
133

    
134
        Example:
135
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
136
            method)
137
        """
138

    
139
        event_type, created = EventType.objects.get_or_create(
140
                label=u"Rendez-vous patient"
141
                )
142

    
143
        history = HistoryAct.objects.create(
144
                date = datetime.now(),
145
                event_type = 'NR')
146
        act_event = EventAct.objects.create(
147
                title=title,
148
                event_type=event_type,
149
                patient=patient,
150
                act_type=act_type,
151
                date=start_datetime,
152
                histories = [history]
153
                )
154
        act_event.doctors = participants
155
        ActValidationState(act=act_event, state_name='NON_VALIDE',
156
            author=creator, previous_state=None).save()
157

    
158
        return self._set_event(act_event, participants, description,
159
                services=[service], start_datetime=start_datetime,
160
                end_datetime=end_datetime,
161
                room=room, note=note, **rrule_params)
162

    
163

    
164
class EventAct(Act, Event):
165
    objects = EventActManager()
166

    
167
    VALIDATION_CODE_CHOICES = (
168
            ('absent', u'Absent'),
169
            ('present', u'Présent'),
170
            )
171
    attendance = models.CharField(max_length=16,
172
            choices=VALIDATION_CODE_CHOICES,
173
            default='absent',
174
            verbose_name=u'Présence')
175
    convocation_sent = models.BooleanField(blank=True,
176
            verbose_name=u'Convoqué')
177

    
178
    def __unicode__(self):
179
        return 'Rdv le {0} de {1} avec {2} pour {3}'.format(
180
                self.occurrence_set.all()[0].start_time, self.patient,
181
                ', '.join(map(unicode, self.participants.all())),
182
                self.act_type)
183

    
184
    def __repr__(self):
185
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self),
186
            self.id)
187

    
188
    class Meta:
189
        verbose_name = 'Rendez-vous patient'
190
        verbose_name_plural = 'Rendez-vous patient'
191
        ordering = ['-date', 'patient']
(4-4/9)