Project

General

Profile

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

calebasse / calebasse / actes / models.py @ e37c8bd1

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

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

    
52
    def is_absent(self):
53
        if self.get_state() in ('ABS_NON_EXC', 'ABS_EXC', 'ANNUL_NOUS',
54
                'ANNUL_FAMILLE', 'ABS_ESS_PPS', 'ENF_HOSP'):
55
            return True
56

    
57
    def get_state(self):
58
        return self.actvalidationstate_set.latest('created')
59

    
60
    def is_state(self, state_name):
61
        state = self.get_state()
62
        if state and state.state_name == state_name:
63
            return True
64
        return False
65

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

    
76
    def __unicode__(self):
77
        return '{0} le {1} pour {2} avec {3}'.format(
78
                self.act_type, self.date, self.patient,
79
                ', '.join(map(unicode, self.doctors.all())))
80

    
81
    def __repr__(self):
82
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self), self.id)
83

    
84
    class Meta:
85
        verbose_name = u"Acte"
86
        verbose_name_plural = u"Actes"
87
        ordering = ['-date', 'patient']
88

    
89

    
90
class HistoryAct(models.Model):
91
    EVENT_CHOICES = (
92
            ('NR', u'Nouveau rendez-vous'),
93
            ('AV', u'Acte validé'),
94
            ('CF', u'En cours de facturation'),
95
            ('AF', u'Acte facturé'),
96
            )
97
    date = models.DateTimeField()
98
    event_type = models.CharField(max_length=2,
99
            choices=EVENT_CHOICES)
100
    description = models.TextField(default='')
101

    
102

    
103
class EventActManager(EventManager):
104

    
105
    def create_patient_appointment(self, creator, title, patient, participants,
106
            act_type, service, start_datetime, end_datetime, description='',
107
            room=None, note=None, **rrule_params):
108
        """
109
        This method allow you to create a new patient appointment quickly
110

    
111
        Args:
112
            title: patient appointment title (str)
113
            patient: Patient object
114
            participants: List of CalebasseUser (therapists)
115
            act_type: ActType object
116
            service: Service object. Use session service by defaut
117
            start_datetime: datetime with the start date and time
118
            end_datetime: datetime with the end date and time
119
            freq, count, until, byweekday, rrule_params:
120
            follow the ``dateutils`` API (see http://labix.org/python-dateutil)
121

    
122
        Example:
123
            Look at calebasse.agenda.tests.EventTest (test_create_appointments
124
            method)
125
        """
126

    
127
        event_type, created = EventType.objects.get_or_create(
128
                label=u"Rendez-vous patient"
129
                )
130

    
131
        history = HistoryAct.objects.create(
132
                date = datetime.now(),
133
                event_type = 'NR')
134
        act_event = EventAct.objects.create(
135
                title=title,
136
                event_type=event_type,
137
                patient=patient,
138
                act_type=act_type,
139
                date=start_datetime,
140
                histories = [history]
141
                )
142
        act_event.doctors = participants
143
        ActValidationState(act=act_event, state_name='NON_VALIDE',
144
            author=creator, previous_state=None).save()
145

    
146

    
147
        return self._set_event(act_event, participants, description,
148
                services=[service], start_datetime=start_datetime,
149
                end_datetime=end_datetime,
150
                room=room, note=note, **rrule_params)
151

    
152

    
153
class EventAct(Act, Event):
154
    objects = EventActManager()
155

    
156
    VALIDATION_CODE_CHOICES = (
157
            ('absent', u'Absent'),
158
            ('present', u'Présent'),
159
            )
160
    attendance = models.CharField(max_length=16,
161
            choices=VALIDATION_CODE_CHOICES,
162
            default='absent',
163
            verbose_name=u'Présence')
164
    convocation_sent = models.BooleanField(blank=True,
165
            verbose_name=u'Convoqué')
166

    
167
    def __unicode__(self):
168
        return 'Rdv le {0} de {1} avec {2} pour {3}'.format(
169
                self.occurrence_set.all()[0].start_time, self.patient,
170
                ', '.join(map(unicode, self.participants.all())),
171
                self.act_type)
172

    
173
    def __repr__(self):
174
        return '<%s %r %r>' % (self.__class__.__name__, unicode(self),
175
            self.id)
176

    
177
    class Meta:
178
        verbose_name = 'Rendez-vous patient'
179
        verbose_name_plural = 'Rendez-vous patient'
180
        ordering = ['-date', 'patient']
(4-4/9)