chrono/chrono/manager/forms.py

175 lines
5.5 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/>.
import csv
import datetime
from django import forms
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _
from chrono.agendas.models import (Event, MeetingType, TimePeriod, Desk,
TimePeriodException)
from . import widgets
DATETIME_OPTIONS = {
'weekStart': 1,
'autoclose': True,
}
class DateTimeWidget(widgets.DateTimeWidget):
def __init__(self, *args, **kwargs):
super(DateTimeWidget, self).__init__(*args, options=DATETIME_OPTIONS, **kwargs)
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 TimePeriodForm(forms.ModelForm):
class Meta:
model = TimePeriod
widgets = {
'start_time': widgets.TimeWidget(),
'end_time': widgets.TimeWidget(),
'desk': forms.HiddenInput(),
}
exclude = []
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 clean_events_csv_file(self):
content = self.cleaned_data['events_csv_file'].read()
if '\0' in content:
raise ValidationError(_('Invalid file format.'))
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()
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 = 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 = ' '.join(csvline[4:])
events.append(event)
self.events = events
class ExceptionsImportForm(forms.ModelForm):
class Meta:
model = Desk
fields = []
ics_file = forms.FileField(label=_('ICS File'),
help_text=_('ICS file containing events which will be considered as exceptions'))