291 lines
9.2 KiB
Python
291 lines
9.2 KiB
Python
# chrono - agendas system
|
|
# Copyright (C) 2016 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
import csv
|
|
import datetime
|
|
|
|
from django import forms
|
|
from django.contrib.auth.models import Group
|
|
from django.forms import ValidationError
|
|
from django.utils.encoding import force_text
|
|
from django.utils.timezone import make_aware
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
from chrono.agendas.models import (
|
|
Agenda,
|
|
Event,
|
|
MeetingType,
|
|
TimePeriod,
|
|
Desk,
|
|
TimePeriodException,
|
|
TimePeriodExceptionSource,
|
|
WEEKDAYS_LIST,
|
|
)
|
|
|
|
from . import widgets
|
|
from .widgets import DateTimeWidget
|
|
|
|
|
|
class AgendaAddForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Agenda
|
|
fields = ['label', 'kind', 'edit_role', 'view_role']
|
|
|
|
edit_role = forms.ModelChoiceField(
|
|
label=_('Edit Role'), required=False, queryset=Group.objects.all().order_by('name')
|
|
)
|
|
view_role = forms.ModelChoiceField(
|
|
label=_('View Role'), required=False, queryset=Group.objects.all().order_by('name')
|
|
)
|
|
|
|
|
|
class AgendaEditForm(AgendaAddForm):
|
|
class Meta:
|
|
model = Agenda
|
|
fields = ['label', 'slug', 'edit_role', 'view_role', 'minimal_booking_delay', 'maximal_booking_delay']
|
|
|
|
|
|
class NewEventForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Event
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
'start_datetime': DateTimeWidget(),
|
|
}
|
|
exclude = ['full', 'meeting_type', 'desk', 'slug']
|
|
|
|
|
|
class EventForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Event
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
'start_datetime': DateTimeWidget(),
|
|
}
|
|
exclude = ['full', 'meeting_type', 'desk']
|
|
|
|
|
|
class NewMeetingTypeForm(forms.ModelForm):
|
|
class Meta:
|
|
model = MeetingType
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
}
|
|
exclude = ['slug']
|
|
|
|
|
|
class MeetingTypeForm(forms.ModelForm):
|
|
class Meta:
|
|
model = MeetingType
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
}
|
|
exclude = []
|
|
|
|
|
|
class TimePeriodAddForm(forms.Form):
|
|
weekdays = forms.MultipleChoiceField(
|
|
label=_('Days'), widget=widgets.WeekdaysWidget(), choices=WEEKDAYS_LIST
|
|
)
|
|
start_time = forms.TimeField(label=_('Start Time'), widget=widgets.TimeWidget())
|
|
end_time = forms.TimeField(label=_('End Time'), widget=widgets.TimeWidget())
|
|
|
|
def clean_end_time(self):
|
|
if self.cleaned_data['end_time'] <= self.cleaned_data['start_time']:
|
|
raise ValidationError(_('End time must come after start time.'))
|
|
return self.cleaned_data['end_time']
|
|
|
|
|
|
class TimePeriodForm(forms.ModelForm):
|
|
class Meta:
|
|
model = TimePeriod
|
|
widgets = {
|
|
'start_time': widgets.TimeWidget(),
|
|
'end_time': widgets.TimeWidget(),
|
|
'desk': forms.HiddenInput(),
|
|
}
|
|
exclude = []
|
|
|
|
def clean_end_time(self):
|
|
if self.cleaned_data['end_time'] <= self.cleaned_data['start_time']:
|
|
raise ValidationError(_('End time must come after start time.'))
|
|
return self.cleaned_data['end_time']
|
|
|
|
|
|
class NewDeskForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Desk
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
}
|
|
exclude = ['slug']
|
|
|
|
|
|
class DeskForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Desk
|
|
widgets = {
|
|
'agenda': forms.HiddenInput(),
|
|
}
|
|
exclude = []
|
|
|
|
|
|
class TimePeriodExceptionForm(forms.ModelForm):
|
|
class Meta:
|
|
model = TimePeriodException
|
|
fields = ['desk', 'start_datetime', 'end_datetime', 'label']
|
|
widgets = {
|
|
'desk': forms.HiddenInput(),
|
|
'start_datetime': DateTimeWidget(),
|
|
'end_datetime': DateTimeWidget(),
|
|
}
|
|
|
|
def clean_end_datetime(self):
|
|
if self.cleaned_data['end_datetime'] <= self.cleaned_data['start_datetime']:
|
|
raise ValidationError(_('End datetime must be greater than start datetime.'))
|
|
return self.cleaned_data['end_datetime']
|
|
|
|
|
|
class ImportEventsForm(forms.Form):
|
|
events_csv_file = forms.FileField(
|
|
label=_('Events File'),
|
|
required=True,
|
|
help_text=_(
|
|
'CSV file with date, time, number of places, '
|
|
'number of places in waiting list, and label '
|
|
'as columns.'
|
|
),
|
|
)
|
|
events = None
|
|
|
|
def __init__(self, agenda_pk, **kwargs):
|
|
self.agenda_pk = agenda_pk
|
|
super(ImportEventsForm, self).__init__(**kwargs)
|
|
|
|
def clean_events_csv_file(self):
|
|
content = self.cleaned_data['events_csv_file'].read()
|
|
if b'\0' in content:
|
|
raise ValidationError(_('Invalid file format.'))
|
|
|
|
for charset in ('utf-8', 'iso-8859-15'):
|
|
try:
|
|
content = content.decode(charset)
|
|
break
|
|
except UnicodeDecodeError:
|
|
continue
|
|
# all byte-sequences are ok for iso-8859-15 so we will always reach
|
|
# this line with content being a unicode string.
|
|
|
|
try:
|
|
dialect = csv.Sniffer().sniff(content)
|
|
except csv.Error:
|
|
dialect = None
|
|
|
|
events = []
|
|
for i, csvline in enumerate(csv.reader(content.splitlines(), dialect=dialect)):
|
|
if not csvline:
|
|
continue
|
|
if len(csvline) < 3:
|
|
raise ValidationError(_('Invalid file format. (line %d)') % (i + 1))
|
|
if i == 0 and csvline[0].strip('#') in ('date', 'Date', _('date'), _('Date')):
|
|
continue
|
|
event = Event()
|
|
event.agenda_id = self.agenda_pk
|
|
for datetime_fmt in (
|
|
'%Y-%m-%d %H:%M',
|
|
'%d/%m/%Y %H:%M',
|
|
'%d/%m/%Y %Hh%M',
|
|
'%Y-%m-%d %H:%M:%S',
|
|
'%d/%m/%Y %H:%M:%S',
|
|
):
|
|
try:
|
|
event_datetime = datetime.datetime.strptime('%s %s' % tuple(csvline[:2]), datetime_fmt)
|
|
except ValueError:
|
|
continue
|
|
event.start_datetime = make_aware(event_datetime)
|
|
break
|
|
else:
|
|
raise ValidationError(_('Invalid file format. (date/time format, line %d)') % (i + 1))
|
|
try:
|
|
event.places = int(csvline[2])
|
|
except ValueError:
|
|
raise ValidationError(_('Invalid file format. (number of places, line %d)') % (i + 1))
|
|
if len(csvline) >= 4:
|
|
try:
|
|
event.waiting_list_places = int(csvline[3])
|
|
except ValueError:
|
|
raise ValidationError(
|
|
_('Invalid file format. (number of places in waiting list, line %d)') % (i + 1)
|
|
)
|
|
if len(csvline) >= 5:
|
|
event.label = force_text(csvline[4])
|
|
exclude = ['desk', 'meeting_type']
|
|
if len(csvline) >= 6:
|
|
event.slug = ' '.join([force_text(x) for x in csvline[5:]])
|
|
else:
|
|
exclude += ['slug']
|
|
try:
|
|
event.full_clean(exclude=exclude)
|
|
except ValidationError as e:
|
|
errors = [
|
|
_('Invalid file format. (%(label)s: %(errors)s, line %(line)d)')
|
|
% {'label': label, 'errors': u', '.join(field_errors), 'line': i + 1}
|
|
for label, field_errors in e.message_dict.items()
|
|
]
|
|
raise ValidationError(errors)
|
|
events.append(event)
|
|
self.events = events
|
|
|
|
|
|
class ExceptionsImportForm(forms.ModelForm):
|
|
ics_file = forms.FileField(
|
|
label=_('ICS File'),
|
|
required=False,
|
|
help_text=_('ICS file containing events which will be considered as exceptions.'),
|
|
)
|
|
ics_url = forms.URLField(
|
|
label=_('URL'),
|
|
required=False,
|
|
help_text=_('URL to remote calendar which will be synchronised hourly.'),
|
|
)
|
|
|
|
class Meta:
|
|
model = Desk
|
|
fields = []
|
|
|
|
def clean(self, *args, **kwargs):
|
|
cleaned_data = super().clean(*args, **kwargs)
|
|
if not cleaned_data.get('ics_file') and not cleaned_data.get('ics_url'):
|
|
raise forms.ValidationError(_('Please provide an ICS File or an URL.'))
|
|
|
|
|
|
class TimePeriodExceptionSourceReplaceForm(forms.ModelForm):
|
|
ics_file = forms.FileField(
|
|
label=_('ICS File'),
|
|
required=False,
|
|
help_text=_('ICS file containing events which will be considered as exceptions.'),
|
|
)
|
|
|
|
class Meta:
|
|
model = TimePeriodExceptionSource
|
|
fields = []
|
|
|
|
|
|
class AgendasImportForm(forms.Form):
|
|
agendas_json = forms.FileField(label=_('Agendas Export File'))
|