Projet

Général

Profil

Télécharger (7,24 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / agenda / managers.py @ dd986559

1

    
2
from datetime import datetime, timedelta, date, time
3
from interval import IntervalSet
4

    
5
from django.db.models import Q
6
from model_utils.managers import InheritanceManager, PassThroughManager, InheritanceQuerySet
7

    
8
from calebasse.agenda.conf import default
9
from calebasse.utils import weeks_since_epoch, weekday_ranks
10
from calebasse import agenda
11

    
12
__all__ = (
13
    'EventManager',
14
)
15

    
16

    
17
class EventQuerySet(InheritanceQuerySet):
18
    def for_today(self, today=None):
19
        today = today or date.today()
20
        excluded = self.filter(exceptions__exception_date=today).values_list('id', flat=True)
21
        weeks = weeks_since_epoch(today)
22
        filters = [Q(start_datetime__gte=datetime.combine(today, time()),
23
               start_datetime__lte=datetime.combine(today, time(23,59,59)),
24
               recurrence_periodicity__isnull=True,
25
               canceled=False) ]
26
        base_q = Q(start_datetime__lte=datetime.combine(today, time(23,59,59)),
27
                canceled=False,
28
                recurrence_week_day=today.weekday(),
29
                recurrence_periodicity__isnull=False) & \
30
                (Q(recurrence_end_date__gte=today) |
31
                    Q(recurrence_end_date__isnull=True)) & \
32
                ~ Q(id__in=excluded)
33
        # week periods
34
        for period in range(1, 6):
35
            filters.append(base_q & Q(recurrence_week_offset=weeks % period,
36
                recurrence_week_period=period))
37
        # week parity
38
        parity = today.isocalendar()[1] % 2
39
        filters.append(base_q & Q(recurrence_week_parity=parity))
40
        # week ranks
41
        filters.append(base_q & Q(recurrence_week_rank__in=weekday_ranks(today)))
42
        qs = self.filter(reduce(Q.__or__, filters))
43
        qs = qs.distinct()
44
        return qs
45

    
46
    def today_occurrences(self, today=None):
47
        today = today or date.today()
48
        self = self.for_today(today)
49
        occurences = ( e.today_occurrence(today) for e in self )
50
        return sorted(occurences, key=lambda e: e.start_datetime)
51

    
52
    def daily_disponibilities(self, date, events, participants, time_tables,
53
            holidays):
54
        '''Slice the day into quarters between 8:00 and 19:00, and returns the
55
           list of particpants with their status amon free, busy and away for each
56
           hour and quarters.
57

    
58
           date - the date of day we slice
59
           occurences - a dictionnary of iterable of events indexed by participants
60
           participants - an iterable of participants
61
           time_tables - a dictionnaty of timetable applying for this day indexed by participants
62
           holidays - a dictionnary of holidays applying for this day indexed by participants
63
        '''
64
        result = dict()
65
        quarter = 0
66
        events_set = {}
67
        timetables_set = {}
68
        holidays_set = {}
69
        for participant in participants:
70
            events_set[participant.id] = IntervalSet((o.to_interval() for o in events[participant.id] if not o.is_event_absence()))
71
            timetables_set[participant.id] = IntervalSet((t.to_interval(date) for t in time_tables[participant.id]))
72
            holidays_set[participant.id] = IntervalSet((h.to_interval(date) for h in holidays[participant.id]))
73
        start_datetime = datetime(date.year, date.month, date.day, 8, 0)
74
        end_datetime = datetime(date.year, date.month, date.day, 8, 15)
75
        while (start_datetime.hour <= 19):
76
            for participant in participants:
77
                if not result.has_key(start_datetime.hour):
78
                    result[start_datetime.hour] = [[], [], [], []]
79
                    quarter = 0
80
                interval = IntervalSet.between(start_datetime, end_datetime, False)
81
                mins = quarter * 15
82
                if interval.intersection(events_set[participant.id]):
83
                    result[start_datetime.hour][quarter].append((mins, {'id': participant.id, 'dispo': 'busy'}))
84
                elif interval.intersection(holidays_set[participant.id]):
85
                    result[start_datetime.hour][quarter].append((mins, {'id': participant.id, 'dispo': 'busy'}))
86
                elif not interval.intersection(timetables_set[participant.id]):
87
                    result[start_datetime.hour][quarter].append((mins, {'id': participant.id, 'dispo': 'away'}))
88
                else:
89
                    result[start_datetime.hour][quarter].append((mins, {'id': participant.id, 'dispo': 'free'}))
90
            quarter += 1
91
            start_datetime += timedelta(minutes=15)
92
            end_datetime += timedelta(minutes=15)
93
        return result
94

    
95

    
96
class EventManager(PassThroughManager.for_queryset_class(EventQuerySet),
97
        InheritanceManager):
98
    """ This class allows you to manage events, appointment, ...
99
    """
100

    
101
    def create_event(self, creator, title, event_type, participants=[], description='',
102
            services=[], start_datetime=None, end_datetime=None, ressource=None, note=None, periodicity=1, until=False, **kwargs):
103
        """
104
        Convenience function to create an ``Event``, optionally create an
105
        ``EventType``.
106

    
107
        Args:
108
            event_type: can be either an ``EventType`` object or the label
109
            is either created or retrieved.
110
            participants: List of CalebasseUser
111
            start_datetime: will default to the current hour if ``None``
112
            end_datetime: will default to ``start_datetime`` plus
113
            default.DEFAULT_EVENT_DURATION hour if ``None``
114
        Returns:
115
            Event object
116
        """
117
        if isinstance(event_type, str):
118
            event_type, created = agenda.models.EventType.objects.get_or_create(
119
                label=event_type
120
            )
121
        if not start_datetime:
122
            now = datetime.now()
123
            start_datetime = datetime.combine(now.date, time(now.hour))
124
        if not end_datetime:
125
            end_datetime = start_datetime + default.DEFAULT_EVENT_DURATION
126
        if until is False:
127
            until = start_datetime.date()
128
        event = self.create(creator=creator,
129
                title=title, start_datetime=start_datetime,
130
                end_datetime=end_datetime, event_type=event_type,
131
                ressource=ressource, recurrence_periodicity=periodicity,
132
                recurrence_end_date=until, **kwargs)
133
        event.services = services
134
        event.participants = participants
135
        return event
136

    
137
    def next_appointment(self, patient_record):
138
        qs = self.next_appointments(patient_record)
139
        if qs:
140
            return qs[0]
141
        else:
142
            return None
143

    
144
    def next_appointments(self, patient_record, today=None):
145
        from calebasse.actes.models import Act
146
        acts = Act.objects.next_acts(patient_record, today=today) \
147
                .filter(parent_event__isnull=False) \
148
                .select_related()
149
        return [ a.parent_event.today_occurrence(a.date) for a in acts ]
150

    
151
    def last_appointment(self, patient_record):
152
        qs = self.last_appointments(patient_record)
153
        if qs:
154
            return qs[0]
155
        else:
156
            return None
157

    
158
    def last_appointments(self, patient_record, today=None):
159
        from calebasse.actes.models import Act
160
        acts = Act.objects.last_acts(patient_record, today=today) \
161
                .filter(parent_event__isnull=False) \
162
                .select_related()
163
        return [ a.parent_event.today_occurrence(a.date) for a in acts ]
(6-6/10)