add template tag to compute opening hours badge (#17428)

This commit is contained in:
Frédéric Péters 2017-07-07 08:44:24 +02:00
parent 4e1760b078
commit 684dd71f68
2 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,79 @@
# -*- coding: utf-8 -*-
# combo-plugin-gnm - Combo GNM plugin
# 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/>.
import datetime
import re
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
class TimeSlot(object):
def __init__(self, start, end):
self.start = start
self.end = end
@register.filter
def as_opening_hours_badge(data):
weekdays = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche']
slots = []
today = datetime.date.today()
for i in range(7):
for period in ('am', 'pm'):
hours = data.get('%s_%s' % (weekdays[today.weekday()], period))
if not hours:
continue
try:
parts = re.match('(\d?\d)h(\d\d)-(\d?\d)h(\d\d)', hours).groups()
except AttributeError:
continue
slots.append(TimeSlot(
datetime.datetime(today.year, today.month, today.day, int(parts[0]), int(parts[1])),
datetime.datetime(today.year, today.month, today.day, int(parts[2]), int(parts[3]))))
today = today + datetime.timedelta(days=1)
now = datetime.datetime.now()
# remove past slots
for i, slot in enumerate(slots):
if now > slot.end:
slots[i] = None
slots = [x for x in slots if x]
if now < slots[0].start:
klass = 'closed'
verb = u'Réouvre'
if slots[0].start.weekday() == today.weekday():
day_label = ''
if slots[0].start.hour < 12:
verb = 'Ouvre'
elif slots[0].start.weekday() == (today.weekday() + 1) % 7:
day_label = u'demain'
else:
day_label = weekdays[slots[0].start.weekday()]
label = u'%s %s à %sh%02d' % (verb, day_label, slots[0].start.hour, slots[0].start.minute)
elif now < slots[0].end:
if (slots[0].end - now).seconds < 3600:
klass = 'soon-to-be-closed'
else:
klass = 'open'
label = 'Ouvert jusque %sh%02d' % (slots[0].end.hour, slots[0].end.minute)
return mark_safe('<div class="badge %s"><span>%s</span></div>' % (klass, label))