Source

django-swingcms / swingcms / agenda / code.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime, calendar

from django.utils.translation import ugettext as _
from django.utils.datastructures import SortedDict

import settings



WEEK_DAYS = (
    _('monday'),
    _('tuesday'),
    _('wednesday'),
    _('thursday'),
    _('friday'),
    _('saturday'),
    _('sunday')
)


def build_month(year, month, events):
    """
    Return a list of lists of lists, each with date and
    event list,that represent a calendar's month.
    """
    month_events = []
    for week in calendar.Calendar(0).monthdatescalendar(year, month):
        week_events = []
        for dt_day in week:
            day_events = []
            for e in events:
                if (e.dt_start.year,e.dt_start.month,e.dt_start.day) == (dt_day.year,dt_day.month,dt_day.day):
                    day_events.append(e)
            week_events.append((dt_day, day_events))
        month_events.append(week_events)
    return month_events


def get_agenda_as_calendar(events, now):
    
    agenda_as_calendar = SortedDict()
    dt_month = None
    for delta in range(settings.AGENDA_FROM_DELTA_DAY, settings.AGENDA_TO_DELTA_DAY):
        dt = now + datetime.timedelta(delta)
        if dt_month and (dt.year, dt.month) == (dt_month.year, dt_month.month):
            continue
        agenda_as_calendar[dt] = build_month(dt.year, dt.month, events)
        dt_month = dt
    return agenda_as_calendar


def get_agenda_as_list(events, now):
    
    dt_from = now + datetime.timedelta(settings.AGENDA_FROM_DELTA_DAY)
    dt_to = now + datetime.timedelta(settings.AGENDA_TO_DELTA_DAY)
    agenda_as_list = events.filter(dt_stop__gt=dt_from, dt_stop__lt=dt_to)
    return agenda_as_list