Project

General

Profile

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

calebasse / calebasse / agenda / models.py @ b8a9f824

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

    
3
from datetime import datetime, date, timedelta
4
from copy import copy
5

    
6
from django.utils.translation import ugettext_lazy as _
7
from django.contrib.auth.models import User
8
from django.db import models
9
from django import forms
10

    
11
from calebasse.agenda import managers
12
from calebasse.utils import weeks_since_epoch, weekday_ranks
13
from interval import Interval
14

    
15
__all__ = (
16
    'EventType',
17
    'Event',
18
    'EventWithAct',
19
)
20

    
21
class EventType(models.Model):
22
    '''
23
    Simple ``Event`` classifcation.
24
    '''
25
    class Meta:
26
        verbose_name = u'Type d\'événement'
27
        verbose_name_plural = u'Types d\'événement'
28

    
29
    def __unicode__(self):
30
        return self.label
31

    
32
    label = models.CharField(_('label'), max_length=50)
33
    rank = models.IntegerField(_('Sorting Rank'), null=True, blank=True, default=0)
34

    
35
class Event(models.Model):
36
    '''
37
    Container model for general agenda events
38
    '''
39
    objects = managers.EventManager()
40

    
41
    title = models.CharField(_('Title'), max_length=60, blank=True)
42
    description = models.TextField(_('Description'), max_length=100)
43
    event_type = models.ForeignKey(EventType, verbose_name=u"Type d'événement")
44
    creator = models.ForeignKey(User, verbose_name=_(u'Créateur'), blank=True, null=True)
45
    create_date = models.DateTimeField(_(u'Date de création'), auto_now_add=True)
46

    
47
    services = models.ManyToManyField('ressources.Service',
48
            null=True, blank=True, default=None)
49
    participants = models.ManyToManyField('personnes.People',
50
            null=True, blank=True, default=None)
51
    room = models.ForeignKey('ressources.Room', blank=True, null=True,
52
            verbose_name=u'Salle')
53

    
54
    start_datetime = models.DateTimeField(_('Début'), db_index=True)
55
    end_datetime = models.DateTimeField(_('Fin'), blank=True, null=True)
56
    old_ev_id = models.CharField(max_length=8, blank=True, null=True)
57
    old_rr_id = models.CharField(max_length=8, blank=True, null=True)
58
    # only used when there is no rr id
59
    old_rs_id = models.CharField(max_length=8, blank=True, null=True)
60
    # exception to is mutually exclusive with recurrence_periodicity
61
    # an exception cannot be periodic
62
    exception_to = models.ForeignKey('self', related_name='exceptions',
63
            blank=True, null=True,
64
            verbose_name=u'Exception à')
65
    exception_date = models.DateField(blank=True, null=True,
66
            verbose_name=u'Reporté du', db_index=True)
67
    # canceled can only be used with exception to
68
    canceled = models.BooleanField(_('Annulé'), db_index=True)
69

    
70
    PERIODS = (
71
            (1, u'Toutes les semaines'),
72
            (2, u'Une semaine sur deux'),
73
            (3, u'Une semaine sur trois'),
74
            (4, 'Une semaine sur quatre'),
75
            (5, 'Une semaine sur cinq')
76
    )
77
    OFFSET = range(0,4)
78
    PERIODICITIES = (
79
            (1, u'Toutes les semaines'),
80
            (2, u'Une semaine sur deux'),
81
            (3, u'Une semaine sur trois'),
82
            (4, u'Une semaine sur quatre'),
83
            (5, u'Une semaine sur cinq'),
84
            (6, u'La première semaine du mois'),
85
            (7, u'La deuxième semaine du mois'),
86
            (8, u'La troisième semaine du mois'),
87
            (9, u'La quatrième semaine du mois'),
88
            (10, u'La dernière semaine du mois'),
89
            (11, u'Les semaines paires'),
90
            (12, u'Les semaines impaires')
91
    )
92
    WEEK_RANKS = (
93
            (0, u'La première semaine du mois'),
94
            (1, u'La deuxième semaine du mois'),
95
            (2, u'La troisième semaine du mois'),
96
            (3, u'La quatrième semaine du mois'),
97
            (4, u'La dernière semaine du mois')
98
    )
99
    PARITIES = (
100
            (0, u'Les semaines paires'),
101
            (1, u'Les semaines impaires')
102
    )
103
    recurrence_periodicity = models.PositiveIntegerField(
104
            choices=PERIODICITIES,
105
            verbose_name=u"Périodicité",
106
            default=None,
107
            blank=True,
108
            null=True,
109
            db_index=True)
110
    recurrence_week_day = models.PositiveIntegerField(default=0, db_index=True)
111
    recurrence_week_offset = models.PositiveIntegerField(
112
            choices=zip(OFFSET, OFFSET),
113
            verbose_name=u"Décalage en semaines par rapport au 1/1/1970 pour le calcul de période",
114
            default=0,
115
            db_index=True)
116
    recurrence_week_period = models.PositiveIntegerField(
117
            choices=PERIODS,
118
            verbose_name=u"Période en semaines",
119
            default=None,
120
            blank=True,
121
            null=True,
122
            db_index=True)
123
    recurrence_week_rank = models.PositiveIntegerField(
124
            verbose_name=u"Rang de la semaine dans le mois",
125
            choices=WEEK_RANKS,
126
            blank=True, null=True, db_index=True)
127
    recurrence_week_parity = models.PositiveIntegerField(
128
            choices=PARITIES,
129
            verbose_name=u"Parité des semaines",
130
            blank=True,
131
            null=True,
132
            db_index=True)
133
    recurrence_end_date = models.DateField(
134
            verbose_name=_(u'Fin de la récurrence'),
135
            blank=True, null=True,
136
            db_index=True)
137

    
138
    PERIOD_LIST_TO_FIELDS = [(1, None, None),
139
        (2, None, None),
140
        (3, None, None),
141
        (4, None, None),
142
        (5, None, None),
143
        (None, 0, None),
144
        (None, 1, None),
145
        (None, 2, None),
146
        (None, 3, None),
147
        (None, 4, None),
148
        (None, None, 0),
149
        (None, None, 1)
150
    ]
151

    
152
    class Meta:
153
        verbose_name = u'Evénement'
154
        verbose_name_plural = u'Evénements'
155
        ordering = ('start_datetime', 'end_datetime', 'title')
156
        unique_together = (('exception_to', 'exception_date'),)
157

    
158
    def __init__(self, *args, **kwargs):
159
        if kwargs.get('start_datetime') and not kwargs.has_key('recurrence_end_date'):
160
            kwargs['recurrence_end_date'] = kwargs.get('start_datetime').date()
161
        super(Event, self).__init__(*args, **kwargs)
162

    
163
    def clean(self):
164
        '''Initialize recurrence fields if they are not.'''
165
        self.sanitize()
166
        if self.recurrence_periodicity:
167
            if self.recurrence_end_date and self.start_datetime and self.recurrence_end_date < self.start_datetime.date():
168
                raise forms.ValidationError(u'La date de fin de périodicité doit être postérieure à la date de début.')
169
        if self.recurrence_week_parity is not None:
170
            if self.start_datetime:
171
                week = self.start_datetime.date().isocalendar()[1]
172
                start_week_parity = week % 2
173
                if start_week_parity != self.recurrence_week_parity:
174
                    raise forms.ValidationError(u'Le date de départ de la périodicité est en semaine {week}.'.format(week=week))
175
        if self.recurrence_week_rank is not None and self.start_datetime:
176
            start_week_ranks = weekday_ranks(self.start_datetime.date())
177
            if self.recurrence_week_rank not in start_week_ranks:
178
                raise forms.ValidationError('La date de début de périodicité doit faire partie de la bonne semaine dans le mois.')
179

    
180
    def sanitize(self):
181
        if self.recurrence_periodicity:
182
            l = self.PERIOD_LIST_TO_FIELDS[self.recurrence_periodicity-1]
183
        else:
184
            l = None, None, None
185
        self.recurrence_week_period = l[0]
186
        self.recurrence_week_rank = l[1]
187
        self.recurrence_week_parity = l[2]
188
        if self.start_datetime:
189
            if self.recurrence_periodicity:
190
                self.recurrence_week_day = self.start_datetime.weekday()
191
            if self.recurrence_week_period is not None:
192
                self.recurrence_week_offset = weeks_since_epoch(self.start_datetime) % self.recurrence_week_period
193

    
194
    def timedelta(self):
195
        '''Distance between start and end of the event'''
196
        return self.end_datetime - self.start_datetime
197

    
198
    def match_date(self, date):
199
        if self.is_recurring():
200
            # consider exceptions
201
            exception = self.get_exceptions_dict().get(date)
202
            if exception is not None:
203
                return exception if exception.match_date(date) else None
204
            if self.canceled:
205
                return None
206
            if date.weekday() != self.recurrence_week_day:
207
                return None
208
            if self.start_datetime.date() > date:
209
                return None
210
            if self.recurrence_end_date and self.recurrence_end_date < date:
211
                return None
212
            if self.recurrence_week_period is not None:
213
                if weeks_since_epoch(date) % self.recurrence_week_period != self.recurrence_week_offset:
214
                    return None
215
            elif self.recurrence_week_parity is not None:
216
                if date.isocalendar()[1] % 2 != self.recurrence_week_parity:
217
                    return None
218
            elif self.recurrence_week_rank is not None:
219
                if self.recurrence_week_rank not in weekday_ranks(date):
220
                    return None
221
            else:
222
                raise NotImplemented
223
            return self
224
        else:
225
            return self if date == self.start_datetime.date() else None
226

    
227

    
228
    def today_occurrence(self, today=None, match=False, upgrade=True):
229
        '''For a recurring event compute the today 'Event'.
230

    
231
           The computed event is the fake one that you cannot save to the database.
232
        '''
233
        today = today or date.today()
234
        if self.canceled:
235
            return None
236
        if match:
237
            exception = self.get_exceptions_dict().get(today)
238
            if exception:
239
                if exception.start_datetime.date() == today:
240
                    return exception.today_occurrence(today)
241
                else:
242
                    return None
243
        else:
244
            exception_or_self = self.match_date(today)
245
            if exception_or_self is None:
246
                return None
247
            if exception_or_self != self:
248
                return exception_or_self.today_occurrence(today)
249
        if self.event_type_id == 1 and type(self) != EventWithAct and upgrade:
250
           self = self.eventwithact
251
        if self.recurrence_periodicity is None:
252
            return self
253
        start_datetime = datetime.combine(today, self.start_datetime.timetz())
254
        end_datetime = start_datetime + self.timedelta()
255
        event = copy(self)
256
        event.exception_to = self
257
        event.exception_date = today
258
        event.start_datetime = start_datetime
259
        event.end_datetime = end_datetime
260
        event.recurrence_periodicity = None
261
        event.recurrence_week_offset = 0
262
        event.recurrence_week_period = None
263
        event.recurrence_week_parity = None
264
        event.recurrence_week_rank = None
265
        event.recurrence_end_date = None
266
        event.parent = self
267
        # the returned event is "virtual", it must not be saved
268
        old_save = event.save
269
        old_participants = list(self.participants.all())
270
        def save(*args, **kwargs): 
271
            event.id = None
272
            old_save(*args, **kwargs)
273
            event.participants = old_participants
274
        event.save = save
275
        return event
276

    
277
    def next_occurence(self, today=None):
278
        '''Returns the next occurence after today.'''
279
        today = today or date.today()
280
        for occurence in self.all_occurences():
281
            if occurence.start_datetime.date() > today:
282
                return occurence
283

    
284
    def is_recurring(self):
285
        '''Is this event multiple ?'''
286
        return self.recurrence_periodicity is not None
287

    
288
    def get_exceptions_dict(self):
289
        if not hasattr(self, 'exceptions_dict'):
290
            self.exceptions_dict = dict()
291
            if self.exception_to_id is None:
292
                for exception in self.exceptions.all():
293
                    self.exceptions_dict[exception.exception_date] = exception
294
        return self.exceptions_dict
295

    
296
    def all_occurences(self, limit=90):
297
        '''Returns all occurences of this event as virtual Event objects
298

    
299
           limit - compute occurrences until limit days in the future
300

    
301
           Default is to limit to 90 days.
302
        '''
303
        if self.recurrence_periodicity is not None:
304
            day = self.start_datetime.date()
305
            max_end_date = max(date.today(), self.start_datetime.date()) + timedelta(days=limit)
306
            end_date = min(self.recurrence_end_date or max_end_date, max_end_date)
307
            occurrences = []
308
            if self.recurrence_week_period is not None:
309
                delta = timedelta(days=self.recurrence_week_period*7)
310
                while day <= end_date:
311
                    occurrence = self.today_occurrence(day, True)
312
                    if occurrence is not None:
313
                        occurrences.append(occurrence)
314
                    day += delta
315
            elif self.recurrence_week_parity is not None:
316
                delta = timedelta(days=7)
317
                while day <= end_date:
318
                    if day.isocalendar()[1] % 2 == self.recurrence_week_parity:
319
                        occurrence = self.today_occurrence(day, True)
320
                        if occurrence is not None:
321
                            occurrences.append(occurrence)
322
                    day += delta
323
            elif self.recurrence_week_rank is not None:
324
                delta = timedelta(days=7)
325
                while day <= end_date:
326
                    if self.recurrence_week_rank in weekday_ranks(day):
327
                        occurrence = self.today_occurrence(day, True)
328
                        if occurrence is not None:
329
                            occurrences.append(occurrence)
330
                    day += delta
331
            for exception in self.exceptions.all():
332
                if exception.exception_date != exception.start_datetime.date():
333
                    occurrences.append(exception.eventwithact if exception.event_type_id == 1 else exception)
334
            return sorted(occurrences, key=lambda o: o.start_datetime)
335
        else:
336
            return [self]
337

    
338
    def save(self, *args, **kwargs):
339
        assert self.recurrence_periodicity is None or self.exception_to is None
340
        assert self.exception_to is None or self.exception_to.recurrence_periodicity is not None
341
        assert self.start_datetime is not None
342
        self.sanitize() # init periodicity fields
343
        super(Event, self).save(*args, **kwargs)
344

    
345
    def delete(self, *args, **kwargs):
346
        # never delete, only cancel
347
        from ..actes.models import Act
348
        for a in Act.objects.filter(parent_event=self):
349
            if len(a.actvalidationstate_set.all()) > 1:
350
                a.parent_event = None
351
                a.save()
352
            else:
353
                a.delete()
354
        self.canceled = True
355
        self.save()
356

    
357
    def to_interval(self):
358
        return Interval(self.start_datetime, self.end_datetime)
359

    
360
    def is_event_absence(self):
361
        return False
362

    
363
    def __unicode__(self):
364
        return self.title
365

    
366
    def __repr__(self):
367
        return '<Event: on {start_datetime} with {participants}'.format(
368
                start_datetime=self.start_datetime,
369
                participants=self.participants.all() if self.id else '<un-saved>')
370

    
371

    
372
class EventWithActManager(managers.EventManager):
373
    def create_patient_appointment(self, creator, title, patient,
374
            doctors=[], act_type=None, service=None, start_datetime=None, end_datetime=None,
375
            room=None, periodicity=1, until=False):
376
        appointment = self.create_event(creator=creator,
377
                title=title,
378
                event_type=EventType(id=1),
379
                participants=doctors,
380
                services=[service],
381
                start_datetime=start_datetime,
382
                end_datetime=end_datetime,
383
                room=room,
384
                periodicity=periodicity,
385
                until=until,
386
                act_type=act_type,
387
                patient=patient)
388
        return appointment
389

    
390

    
391
class EventWithAct(Event):
392
    '''An event corresponding to an act.'''
393
    objects = EventWithActManager()
394
    act_type = models.ForeignKey('ressources.ActType',
395
        verbose_name=u'Type d\'acte')
396
    patient = models.ForeignKey('dossiers.PatientRecord')
397
    convocation_sent = models.BooleanField(blank=True,
398
        verbose_name=u'Convoqué', db_index=True)
399

    
400

    
401
    @property
402
    def act(self):
403
        return self.get_or_create_act()
404

    
405
    def get_or_create_act(self, today=None):
406
        from ..actes.models import Act, ActValidationState
407
        today = today or self.start_datetime.date()
408
        act, created = Act.objects.get_or_create(patient=self.patient,
409
                time=self.start_datetime.time(),
410
                _duration=self.timedelta().seconds // 60,
411
                parent_event=getattr(self, 'parent', self),
412
                date=today,
413
                act_type=self.act_type)
414
        self.update_act(act)
415
        if created:
416
            ActValidationState.objects.create(act=act, state_name='NON_VALIDE',
417
                author=self.creator, previous_state=None)
418
        return act
419

    
420
    def update_act(self, act):
421
        '''Update an act to match details of the meeting'''
422
        delta = self.timedelta()
423
        duration = delta.seconds // 60
424
        act._duration = duration
425
        act.doctors = self.participants.select_subclasses()
426
        act.act_type = self.act_type
427
        act.patient = self.patient
428
        act.date = self.start_datetime.date()
429
        act.save()
430

    
431
    def save(self, *args, **kwargs):
432
        '''Force event_type to be patient meeting.'''
433
        self.event_type = EventType(id=1)
434
        super(EventWithAct, self).save(*args, **kwargs)
435
        # list of occurences may have changed
436
        from ..actes.models import Act
437
        occurences = list(self.all_occurences())
438
        acts = Act.objects.filter(parent_event=self)
439
        occurences_by_date = dict((o.start_datetime.date(), o) for o in occurences)
440
        acts_by_date = dict()
441
        for a in acts:
442
            # sanity check
443
            assert a.date not in acts_by_date
444
            acts_by_date[a.date] = a
445
        for a in acts:
446
            o = occurences_by_date.get(a.date)
447
            if o:
448
                o.update_act(a)
449
            else:
450
                if len(a.actvalidationstate_set.all()) > 1:
451
                    a.parent_event = None
452
                    a.save()
453
                else:
454
                    a.delete()
455
        for o in occurences:
456
            if o.start_datetime.date() in acts_by_date:
457
                continue
458
            o.get_or_create_act()
459

    
460
    def today_occurrence(self, today=None, match=False, upgrade=True):
461
        '''For virtual occurrences reset the event_ptr_id'''
462
        occurrence = super(EventWithAct, self).today_occurrence(today, match, upgrade)
463
        if hasattr(occurrence, 'parent'):
464
            old_save = occurrence.save
465
            def save(*args, **kwargs):
466
                occurrence.event_ptr_id = None
467
                old_save(*args, **kwargs)
468
            occurrence.save = save
469
        return occurrence
470

    
471
    def is_event_absence(self):
472
        return self.act.is_absent()
473

    
474
    def __unicode__(self):
475
        kwargs = {
476
                'patient': self.patient,
477
                'start_datetime': self.start_datetime,
478
                'act_type': self.act_type
479
        }
480
        kwargs['doctors'] = ', '.join(map(unicode, self.participants.all())) if self.id else ''
481
        return u'Rdv le {start_datetime} de {patient} avec {doctors} pour ' \
482
            '{act_type} ({act_type.id})'.format(**kwargs)
483

    
484

    
485
from django.db.models.signals import m2m_changed
486
from django.dispatch import receiver
487

    
488

    
489
@receiver(m2m_changed, sender=Event.participants.through)
490
def participants_changed(sender, instance, action, **kwargs):
491
    if action.startswith('post'):
492
        workers = [ p.worker for p in instance.participants.prefetch_related('worker') ]
493
        for act in instance.act_set.all():
494
            act.doctors = workers
(7-7/10)