combo/combo/apps/calendar/forms.py

84 lines
3.1 KiB
Python

# combo - content management system
# Copyright (C) 2017 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 django import forms
from django.utils.dateparse import parse_datetime, parse_time
from django.utils.translation import gettext_lazy as _
from combo.apps.wcs.utils import get_wcs_options
from .models import BookingCalendar
from .utils import get_agendas
class BookingCalendarForm(forms.ModelForm):
class Meta:
model = BookingCalendar
fields = (
'title',
'agenda_reference',
'formdef_reference',
'slot_duration',
'minimal_booking_duration',
'days_displayed',
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
agenda_references = get_agendas()
formdef_references = get_wcs_options('/api/formdefs/')
self.fields['agenda_reference'].widget = forms.Select(choices=agenda_references)
self.fields['formdef_reference'].widget = forms.Select(choices=formdef_references)
class BookingForm(forms.Form):
def __init__(self, *args, **kwargs):
self.cell = kwargs.pop('cell')
super().__init__(*args, **kwargs)
self.cleaned_data = {}
def is_valid(self):
slots = getattr(self.data, 'getlist', lambda x: [])('slots')
# check that at least one slot if selected
if not slots:
raise ValueError(_('Please select slots'))
offset = self.cell.slot_duration
start_dt = parse_datetime(slots[0])
end_dt = parse_datetime(slots[-1]) + offset
slots.append(end_dt.isoformat())
# check that all slots are part of the same day
for slot in slots:
if parse_datetime(slot).date() != start_dt.date():
raise ValueError(_('Please select slots of the same day'))
# check that slots datetime are contiguous
start = start_dt
while start <= end_dt:
if start.isoformat() not in slots:
raise ValueError(_('Please select contiguous slots'))
start = start + offset
# check that event booking duration >= minimal booking duration
min_duration = self.cell.minimal_booking_duration
if not (end_dt - start_dt) >= min_duration:
str_min_duration = parse_time(str(min_duration)).strftime('%H:%M')
message = _("Minimal booking duration is %s") % str_min_duration
raise ValueError(message)
self.cleaned_data['start'] = start_dt
self.cleaned_data['end'] = end_dt
return True