trivial: apply black

This commit is contained in:
Frédéric Péters 2021-01-11 21:31:40 +01:00
parent 153c136804
commit 2d00832fc2
10 changed files with 776 additions and 858 deletions

View File

@ -29,6 +29,8 @@ class AppConfig(django.apps.AppConfig):
def get_before_urls(self): def get_before_urls(self):
from . import urls from . import urls
return urls.urlpatterns return urls.urlpatterns
default_app_config = __name__ + '.AppConfig' default_app_config = __name__ + '.AppConfig'

View File

@ -19,7 +19,9 @@ from django.utils.timezone import now, timedelta
from combo.data.models import ConfigJsonCell from combo.data.models import ConfigJsonCell
class Command(BaseCommand): class Command(BaseCommand):
def handle(self, *args, **options): def handle(self, *args, **options):
ConfigJsonCell.objects.filter(placeholder='_auto_tile', ConfigJsonCell.objects.filter(
last_update_timestamp__lte=now() - timedelta(days=2)).delete() placeholder='_auto_tile', last_update_timestamp__lte=now() - timedelta(days=2)
).delete()

View File

@ -34,13 +34,14 @@ class Command(BaseCommand):
continue continue
cell_form_keys = [x['varname'] for x in json_cell_type.get('form')] cell_form_keys = [x['varname'] for x in json_cell_type.get('form')]
parent_page, created = Page.objects.get_or_create( parent_page, created = Page.objects.get_or_create(
parent__id=places_page.id, parent__id=places_page.id,
slug=layer.slug, slug=layer.slug,
defaults={ defaults={
'title': layer.label, 'title': layer.label,
'redirect_url': '..', 'redirect_url': '..',
'parent': places_page, 'parent': places_page,
}) },
)
parent_page.title = layer.label parent_page.title = layer.label
parent_page.save() parent_page.save()
layer.properties = None # get all properties layer.properties = None # get all properties
@ -50,18 +51,18 @@ class Command(BaseCommand):
self.stderr.write('error in layer %s: %r\n' % (layer, resp['features'])) self.stderr.write('error in layer %s: %r\n' % (layer, resp['features']))
continue continue
for feature in resp['features']: for feature in resp['features']:
cell_parameters = dict([ cell_parameters = dict(
(x, feature['properties'][x]) for x in feature['properties'] if x in cell_form_keys]) [(x, feature['properties'][x]) for x in feature['properties'] if x in cell_form_keys]
)
try: try:
cell = ConfigJsonCell.objects.get( cell = ConfigJsonCell.objects.get(
key=layer.slug, key=layer.slug, parameters=cell_parameters, page__template_name='place'
parameters=cell_parameters, )
page__template_name='place')
except ConfigJsonCell.DoesNotExist: except ConfigJsonCell.DoesNotExist:
page = Page() page = Page()
page_title_template = json_cell_type.get( page_title_template = json_cell_type.get(
'toodego:page-title-template', 'toodego:page-title-template', '{{ properties.nom|safe }}'
'{{ properties.nom|safe }}') )
ctx = Context({'properties': feature['properties']}) ctx = Context({'properties': feature['properties']})
page.title = Template(page_title_template).render(ctx) page.title = Template(page_title_template).render(ctx)
if not page.title: if not page.title:

View File

@ -42,13 +42,20 @@ class Command(BaseCommand):
sheets = [] sheets = []
for url in re.findall('href="(.*?)"', cell.text): for url in re.findall('href="(.*?)"', cell.text):
url = html.unescape(url) url = html.unescape(url)
url = re.sub(r'/backoffice/management/([a-z0-9_-]+)(/[a-z0-9_-]+)?/?(\?)?', r'/api/forms/\1/ods\2\3', url) url = re.sub(
r'/backoffice/management/([a-z0-9_-]+)(/[a-z0-9_-]+)?/?(\?)?',
r'/api/forms/\1/ods\2\3',
url,
)
resp = requests.get(url, remote_service='auto', user=reporting_user) resp = requests.get(url, remote_service='auto', user=reporting_user)
if not resp.ok: if not resp.ok:
continue continue
zipf = zipfile.ZipFile(BytesIO(resp.content)) zipf = zipfile.ZipFile(BytesIO(resp.content))
sheets.append(ET.parse(zipf.open('content.xml')).findall( sheets.append(
'.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table')[0]) ET.parse(zipf.open('content.xml')).findall(
'.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table'
)[0]
)
if sheets: if sheets:
if not os.path.exists(default_storage.path('reporting')): if not os.path.exists(default_storage.path('reporting')):
os.mkdir(default_storage.path('reporting')) os.mkdir(default_storage.path('reporting'))

View File

@ -46,15 +46,17 @@ from combo.utils import requests
register = template.Library() register = template.Library()
FR_WEEKDAYS = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'] FR_WEEKDAYS = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche']
EN_ABBREV_WEEKDAYS = OrderedDict([ EN_ABBREV_WEEKDAYS = OrderedDict(
('mo', 'Monday'), [
('tu', 'Tuesday'), ('mo', 'Monday'),
('we', 'Wednesday'), ('tu', 'Tuesday'),
('th', 'Thursday'), ('we', 'Wednesday'),
('fr', 'Friday'), ('th', 'Thursday'),
('sa', 'Saturday'), ('fr', 'Friday'),
('su', 'Sunday') ('sa', 'Saturday'),
]) ('su', 'Sunday'),
]
)
EN_ABBREV_WEEKDAYS_LIST = list(EN_ABBREV_WEEKDAYS.keys()) EN_ABBREV_WEEKDAYS_LIST = list(EN_ABBREV_WEEKDAYS.keys())
EN_FULL_WEEKDAYS_LIST = list(EN_ABBREV_WEEKDAYS.values()) EN_FULL_WEEKDAYS_LIST = list(EN_ABBREV_WEEKDAYS.values())
FR_ABBREV_WEEKDAYS_LIST = OrderedDict(zip(EN_ABBREV_WEEKDAYS_LIST, FR_WEEKDAYS)) FR_ABBREV_WEEKDAYS_LIST = OrderedDict(zip(EN_ABBREV_WEEKDAYS_LIST, FR_WEEKDAYS))
@ -79,7 +81,7 @@ def openinghours_to_datetime(day_number, hour, minute, base_datetime):
""" """
day_number = day_number % 7 # ease operations using this parameter day_number = day_number % 7 # ease operations using this parameter
#get next weekday # get next weekday
days = (7 + day_number - base_datetime.weekday()) % 7 days = (7 + day_number - base_datetime.weekday()) % 7
datetime_obj = base_datetime + datetime.timedelta(days=days) datetime_obj = base_datetime + datetime.timedelta(days=days)
if is_naive(datetime_obj): if is_naive(datetime_obj):
@ -107,8 +109,13 @@ def get_slot(day_number, time_table, base_datetime):
# hours may belongs on next day # hours may belongs on next day
end_day_number = day_number end_day_number = day_number
if (end_hour < start_hour or end_hour == start_hour and end_minute < start_minute if (
or end_hour == start_hour == 0 and end_minute == start_minute == 0): # 24h/24 end_hour < start_hour
or end_hour == start_hour
and end_minute < start_minute
or end_hour == start_hour == 0
and end_minute == start_minute == 0
): # 24h/24
end_day_number += 1 end_day_number += 1
end = openinghours_to_datetime(end_day_number, end_hour, end_minute, base_datetime) end = openinghours_to_datetime(end_day_number, end_hour, end_minute, base_datetime)
@ -123,8 +130,7 @@ def get_slot(day_number, time_table, base_datetime):
def get_time_table_from_specification(specification): def get_time_table_from_specification(specification):
"""Parse an openinghoursspecification data block """Parse an openinghoursspecification data block"""
"""
if not isinstance(specification['dayOfWeek'], str): if not isinstance(specification['dayOfWeek'], str):
raise ValueError raise ValueError
day_of_week = specification.get('dayOfWeek') day_of_week = specification.get('dayOfWeek')
@ -141,8 +147,7 @@ def get_time_table_from_specification(specification):
def get_period_from_data(time_table): def get_period_from_data(time_table):
"""Return am or pm and all_day_hours from opening_time and closing_time """Return am or pm and all_day_hours from opening_time and closing_time"""
"""
start_hour = int(time_table['start_hour']) start_hour = int(time_table['start_hour'])
start_minute = int(time_table['start_minute']) start_minute = int(time_table['start_minute'])
end_hour = int(time_table['end_hour']) end_hour = int(time_table['end_hour'])
@ -155,8 +160,7 @@ def get_period_from_data(time_table):
opening_time = datetime.time(hour=start_hour, minute=start_minute) opening_time = datetime.time(hour=start_hour, minute=start_minute)
all_day_hours = False all_day_hours = False
if (opening_time < closing_time # closing_time may last on the night if opening_time < closing_time and closing_time.hour <= 12: # closing_time may last on the night
and closing_time.hour <= 12):
period = 'am' period = 'am'
elif opening_time.hour <= 12: elif opening_time.hour <= 12:
period = 'am' period = 'am'
@ -206,34 +210,48 @@ def get_slots_from_mdr_format(data, base_datetime):
def parse_opening_hours_data(mairie_data): def parse_opening_hours_data(mairie_data):
"""Parse every known openinghours data formats """Parse every known openinghours data formats"""
"""
for openinghours in mairie_data.get('openinghours', []): for openinghours in mairie_data.get('openinghours', []):
# format is comma-separated days and/or intervals, or only one day # format is comma-separated days and/or intervals, or only one day
try: try:
groups = re.match(r'(\w\w(?:(?:,|\-)?\w\w)*) (\d\d?):(\d\d?)-(\d\d?):(\d\d?)', openinghours).groups() groups = re.match(
r'(\w\w(?:(?:,|\-)?\w\w)*) (\d\d?):(\d\d?)-(\d\d?):(\d\d?)', openinghours
).groups()
except AttributeError: # invalid input data except AttributeError: # invalid input data
continue continue
for day in groups[0].split(','): for day in groups[0].split(','):
if '-' in day: if '-' in day:
# interval # interval
parts = re.match(r'(\w\w)-(\w\w)', day).groups() + groups[1:] parts = re.match(r'(\w\w)-(\w\w)', day).groups() + groups[1:]
time_table = dict(zip(('start_day', 'end_day', 'start_hour', 'start_minute', 'end_hour', 'end_minute'), parts)) time_table = dict(
zip(
('start_day', 'end_day', 'start_hour', 'start_minute', 'end_hour', 'end_minute'),
parts,
)
)
days_list = EN_ABBREV_WEEKDAYS_LIST[ days_list = EN_ABBREV_WEEKDAYS_LIST[
EN_ABBREV_WEEKDAYS_LIST.index(time_table['start_day'].lower()): EN_ABBREV_WEEKDAYS_LIST.index(
EN_ABBREV_WEEKDAYS_LIST.index(time_table['end_day'].lower()) + 1] time_table['start_day'].lower()
) : EN_ABBREV_WEEKDAYS_LIST.index(time_table['end_day'].lower())
+ 1
]
else: else:
# one day # one day
time_table = dict(zip(('start_day', 'start_hour', 'start_minute', 'end_hour', 'end_minute'), (day,) + groups[1:])) time_table = dict(
days_list = [EN_ABBREV_WEEKDAYS_LIST[ zip(
EN_ABBREV_WEEKDAYS_LIST.index(time_table['start_day'].lower())]] ('start_day', 'start_hour', 'start_minute', 'end_hour', 'end_minute'),
(day,) + groups[1:],
)
)
days_list = [
EN_ABBREV_WEEKDAYS_LIST[EN_ABBREV_WEEKDAYS_LIST.index(time_table['start_day'].lower())]
]
yield (days_list, time_table) yield (days_list, time_table)
def get_slots_from_mairie_format(data, base_datetime): def get_slots_from_mairie_format(data, base_datetime):
"""Process mairie json and return slots the opening hours in chronological order beginning today """Process mairie json and return slots the opening hours in chronological order beginning today"""
"""
if 'properties' in data: if 'properties' in data:
data = data['properties'] data = data['properties']
@ -276,8 +294,10 @@ def get_slots_from_mairie_format(data, base_datetime):
# order slots and cycle the list beginning with 'base_datetime' # order slots and cycle the list beginning with 'base_datetime'
slots = sorted(slots, key=operator.attrgetter('start')) slots = sorted(slots, key=operator.attrgetter('start'))
if len(slots): if len(slots):
def timedelta_key_func(slot): def timedelta_key_func(slot):
return slot.start - base_datetime return slot.start - base_datetime
nearest_slot_index = slots.index(min(slots, key=timedelta_key_func)) nearest_slot_index = slots.index(min(slots, key=timedelta_key_func))
slots = slots[nearest_slot_index:] + slots[:nearest_slot_index] slots = slots[nearest_slot_index:] + slots[:nearest_slot_index]
return (slots, exclusion_slots, known_format) return (slots, exclusion_slots, known_format)
@ -293,14 +313,15 @@ def parse_valid_from(spec):
def parse_valid_through(spec): def parse_valid_through(spec):
valid_through = parse_datetime(spec.get('validThrough')) or parse_date(spec.get('validThrough')) valid_through = parse_datetime(spec.get('validThrough')) or parse_date(spec.get('validThrough'))
if not isinstance(valid_through, datetime.datetime): if not isinstance(valid_through, datetime.datetime):
valid_through = make_aware(datetime.datetime(valid_through.year, valid_through.month, valid_through.day, 23, 59)) valid_through = make_aware(
datetime.datetime(valid_through.year, valid_through.month, valid_through.day, 23, 59)
)
return valid_through return valid_through
@register.simple_tag @register.simple_tag
def get_mairie_opening_hours(mairie_data): def get_mairie_opening_hours(mairie_data):
"""Process Mairie Geojson to extract data of each day's opening hours """Process Mairie Geojson to extract data of each day's opening hours"""
"""
if not mairie_data: if not mairie_data:
return '' return ''
@ -309,17 +330,20 @@ def get_mairie_opening_hours(mairie_data):
base_datetime = now() base_datetime = now()
days_list = [] days_list = []
opening_hours_dict = OrderedDict(zip(EN_ABBREV_WEEKDAYS_LIST, [{ opening_hours_dict = OrderedDict(
'am': None, 'pm': None zip(EN_ABBREV_WEEKDAYS_LIST, [{'am': None, 'pm': None} for i in range(7)])
} for i in range(7)])) )
def update_opening_hours(weekday, time_table): def update_opening_hours(weekday, time_table):
period, all_day_hours = get_period_from_data(time_table) period, all_day_hours = get_period_from_data(time_table)
if all_day_hours and period == 'am': if all_day_hours and period == 'am':
opening_hours_dict[weekday]['pm'] = '' # empty string to avoid displaying fermé opening_hours_dict[weekday]['pm'] = '' # empty string to avoid displaying fermé
opening_hours_dict[weekday][period] = "%sh%s-%sh%s" % ( opening_hours_dict[weekday][period] = "%sh%s-%sh%s" % (
time_table['start_hour'], time_table['start_minute'], time_table['start_hour'],
time_table['end_hour'], time_table['end_minute']) time_table['start_minute'],
time_table['end_hour'],
time_table['end_minute'],
)
known_format = False known_format = False
for days_list, time_table in parse_opening_hours_data(mairie_data): for days_list, time_table in parse_opening_hours_data(mairie_data):
@ -348,8 +372,10 @@ def get_mairie_opening_hours(mairie_data):
weekday = EN_ABBREV_WEEKDAYS_LIST[day_number] weekday = EN_ABBREV_WEEKDAYS_LIST[day_number]
update_opening_hours(weekday, time_table) update_opening_hours(weekday, time_table)
if not (any([x['am'] for x in opening_hours_dict.values()]) or if not (
any([x['pm'] for x in opening_hours_dict.values()])): any([x['am'] for x in opening_hours_dict.values()])
or any([x['pm'] for x in opening_hours_dict.values()])
):
# always closed, returns None if the format is unknown so it can be # always closed, returns None if the format is unknown so it can be
# displayed as "unavailable". # displayed as "unavailable".
if not known_format: if not known_format:
@ -358,9 +384,10 @@ def get_mairie_opening_hours(mairie_data):
return [(weekday, {'am': None, 'pm': ''}) for weekday in FR_WEEKDAYS] return [(weekday, {'am': None, 'pm': ''}) for weekday in FR_WEEKDAYS]
return [ return [
(FR_ABBREV_WEEKDAYS_LIST[weekday], hours) for weekday, hours in opening_hours_dict.items() (FR_ABBREV_WEEKDAYS_LIST[weekday], hours)
if not (weekday in ['sa', 'su'] and not hours['am'] and not hours['pm']) for weekday, hours in opening_hours_dict.items()
] if not (weekday in ['sa', 'su'] and not hours['am'] and not hours['pm'])
]
@register.filter @register.filter
@ -455,9 +482,8 @@ def onlymoov_duration(string):
def place_page(cell): def place_page(cell):
try: try:
fixed_place_cell = ConfigJsonCell.objects.get( fixed_place_cell = ConfigJsonCell.objects.get(
key=cell.key, key=cell.key, parameters=cell.parameters, page__template_name='place'
parameters=cell.parameters, )
page__template_name='place')
except ConfigJsonCell.DoesNotExist: except ConfigJsonCell.DoesNotExist:
return None return None
return fixed_place_cell.page return fixed_place_cell.page
@ -510,7 +536,7 @@ def as_producer(slug, default_slug=None):
slug = slug.get('site_slug') slug = slug.get('site_slug')
producer = None producer = None
if ':' in slug: # formdef_reference if ':' in slug: # formdef_reference
slug = slug.split(':')[0] slug = slug.split(':')[0]
if slug.startswith('_'): if slug.startswith('_'):
@ -524,8 +550,7 @@ def as_producer(slug, default_slug=None):
# variable. # variable.
producer = settings.TEMPLATE_VARS.get('gnm_commune', 'grandlyon') producer = settings.TEMPLATE_VARS.get('gnm_commune', 'grandlyon')
if producer and settings.TEMPLATE_VARS.get('gnm_commune_name'): if producer and settings.TEMPLATE_VARS.get('gnm_commune_name'):
return {'slug': producer, return {'slug': producer, 'label': settings.TEMPLATE_VARS.get('gnm_commune_name')}
'label': settings.TEMPLATE_VARS.get('gnm_commune_name')}
try: try:
producer = re.search(r'(^|\W)producer-([\w-]*)(\W|$)', producer).group(2).strip() producer = re.search(r'(^|\W)producer-([\w-]*)(\W|$)', producer).group(2).strip()
@ -538,11 +563,17 @@ def as_producer(slug, default_slug=None):
producer_slug = slugify(producer) producer_slug = slugify(producer)
if settings.KNOWN_SERVICES['hobo'].get('hobo-%s' % producer): if settings.KNOWN_SERVICES['hobo'].get('hobo-%s' % producer):
return {'slug': producer, return {
'label': settings.KNOWN_SERVICES['hobo'].get('hobo-%s' % producer, {'title': ''})['title']} 'slug': producer,
'label': settings.KNOWN_SERVICES['hobo'].get('hobo-%s' % producer, {'title': ''})['title'],
}
elif settings.KNOWN_SERVICES['hobo'].get('_interco_hobo-%s' % producer): elif settings.KNOWN_SERVICES['hobo'].get('_interco_hobo-%s' % producer):
return {'slug': producer, return {
'label': settings.KNOWN_SERVICES['hobo'].get('_interco_hobo-%s' % producer, {'title': ''})['title']} 'slug': producer,
'label': settings.KNOWN_SERVICES['hobo'].get('_interco_hobo-%s' % producer, {'title': ''})[
'title'
],
}
elif producer in settings.PRODUCER_LABELS: elif producer in settings.PRODUCER_LABELS:
return {'slug': producer, 'label': settings.PRODUCER_LABELS[producer]} return {'slug': producer, 'label': settings.PRODUCER_LABELS[producer]}
elif producer in settings.COLLECTIVITY_LABELS.values(): elif producer in settings.COLLECTIVITY_LABELS.values():
@ -556,6 +587,7 @@ def as_producer(slug, default_slug=None):
else: else:
return {'slug': 'toodego', 'label': 'Toodego'} return {'slug': 'toodego', 'label': 'Toodego'}
@register.filter @register.filter
def as_commune(user_data): def as_commune(user_data):
if not user_data: if not user_data:
@ -583,8 +615,9 @@ def as_commune(user_data):
'gnm': True, 'gnm': True,
} }
# if not found look in mairie pages # if not found look in mairie pages
pages = Page.objects.filter(parent__slug='mairie', pages = Page.objects.filter(parent__slug='mairie', slug__icontains=slugify(city)).exclude(
slug__icontains=slugify(city)).exclude(slug__icontains='annexe') slug__icontains='annexe'
)
if pages.exists(): if pages.exists():
return { return {
'label': city, 'label': city,
@ -630,8 +663,9 @@ def get_suggestions(request, user_data, places_data):
# get commune tile for the user city # get commune tile for the user city
maplayer = MapLayer.objects.get(slug='mairie') maplayer = MapLayer.objects.get(slug='mairie')
try: try:
data_result = requests.get(maplayer.geojson_url, timeout=2, data_result = requests.get(
without_user=True, cache_duration=300).json() maplayer.geojson_url, timeout=2, without_user=True, cache_duration=300
).json()
except RequestException: except RequestException:
pass pass
else: else:
@ -663,11 +697,12 @@ def get_suggestions(request, user_data, places_data):
if address: if address:
nominatim_url = settings.COMBO_GEOCODING_SERVICE nominatim_url = settings.COMBO_GEOCODING_SERVICE
url = '%s/search?q=%s&accept-language=fr&format=json' % ( url = '%s/search?q=%s&accept-language=fr&format=json' % (
nominatim_url, quote(address.encode('utf-8'))) nominatim_url,
quote(address.encode('utf-8')),
)
search_result = None search_result = None
try: try:
search_result = requests.get(url, timeout=2, without_user=True, search_result = requests.get(url, timeout=2, without_user=True, cache_duration=300).json()
cache_duration=300).json()
except RequestException: except RequestException:
pass pass
if search_result: if search_result:
@ -682,8 +717,7 @@ def get_suggestions(request, user_data, places_data):
for maplayer in MapLayer.objects.filter(slug__in=('velov', 'piscine', 'tcl', 'bibliotheque', 'mdr')): for maplayer in MapLayer.objects.filter(slug__in=('velov', 'piscine', 'tcl', 'bibliotheque', 'mdr')):
url = maplayer.geojson_url + '&BBOX=%s,%s,%s,%s' % (lat1, lon1, lat2, lon2) url = maplayer.geojson_url + '&BBOX=%s,%s,%s,%s' % (lat1, lon1, lat2, lon2)
try: try:
data_result = requests.get(url, timeout=2, without_user=True, data_result = requests.get(url, timeout=2, without_user=True, cache_duration=300).json()
cache_duration=300).json()
except RequestException: except RequestException:
continue continue
features = data_result.get('features') features = data_result.get('features')
@ -691,10 +725,11 @@ def get_suggestions(request, user_data, places_data):
continue continue
for feature in features: for feature in features:
feature['distance'] = geod.inv( feature['distance'] = geod.inv(
float(coords['lon']), float(coords['lon']),
float(coords['lat']), float(coords['lat']),
float(feature['geometry']['coordinates'][0]), float(feature['geometry']['coordinates'][0]),
float(feature['geometry']['coordinates'][1]))[2] float(feature['geometry']['coordinates'][1]),
)[2]
features.sort(key=lambda x: x['distance']) features.sort(key=lambda x: x['distance'])
# take closest feature # take closest feature
if features: if features:
@ -717,33 +752,34 @@ def get_suggestions(request, user_data, places_data):
for i, tile_data in enumerate(tiles): for i, tile_data in enumerate(tiles):
if 'properties' in tile_data: if 'properties' in tile_data:
cell_form_keys = [x['varname'] for x in settings.JSON_CELL_TYPES[tile_data['key']].get('form') or {}] cell_form_keys = [
x['varname'] for x in settings.JSON_CELL_TYPES[tile_data['key']].get('form') or {}
]
tile_data['parameters'] = {} tile_data['parameters'] = {}
for key in cell_form_keys: for key in cell_form_keys:
tile_data['parameters'][key] = tile_data['properties'].get(key) tile_data['parameters'][key] = tile_data['properties'].get(key)
cell = ConfigJsonCell( cell = ConfigJsonCell(
key=tile_data['key'], key=tile_data['key'],
parameters=tile_data.get('parameters', {}), parameters=tile_data.get('parameters', {}),
order=0, order=0,
page_id=dashboard.page_id, page_id=dashboard.page_id,
placeholder='_suggested_tile') placeholder='_suggested_tile',
)
cell.save() cell.save()
tile = Tile( tile = Tile(dashboard=dashboard, cell=cell, user=request.user, order=i + 1)
dashboard=dashboard,
cell=cell,
user=request.user,
order=i+1)
tile.save() tile.save()
return tiles return tiles
@register.simple_tag @register.simple_tag
def get_gnm_portal_url(): def get_gnm_portal_url():
if '_interco_portal' in settings.KNOWN_SERVICES['combo']: if '_interco_portal' in settings.KNOWN_SERVICES['combo']:
return settings.KNOWN_SERVICES['combo']['_interco_portal'].get('url') return settings.KNOWN_SERVICES['combo']['_interco_portal'].get('url')
return settings.KNOWN_SERVICES['combo']['portal'].get('url') return settings.KNOWN_SERVICES['combo']['portal'].get('url')
@register.simple_tag @register.simple_tag
def get_gnm_collectivities(): def get_gnm_collectivities():
collectivities = [] collectivities = []
@ -753,13 +789,14 @@ def get_gnm_collectivities():
matching_hobo = settings.KNOWN_SERVICES['hobo'].get(key.split('_portal')[0][1:]) matching_hobo = settings.KNOWN_SERVICES['hobo'].get(key.split('_portal')[0][1:])
if not matching_hobo: if not matching_hobo:
continue continue
if matching_hobo['title'] in ('SAU', 'Villeurbanne'): # blacklist if matching_hobo['title'] in ('SAU', 'Villeurbanne'): # blacklist
continue continue
service = settings.KNOWN_SERVICES['combo'][key] service = settings.KNOWN_SERVICES['combo'][key]
collectivities.append({'url': service.get('url'), 'label': matching_hobo['title']}) collectivities.append({'url': service.get('url'), 'label': matching_hobo['title']})
collectivities.sort(key=lambda x: x['label']) collectivities.sort(key=lambda x: x['label'])
return collectivities return collectivities
@register.inclusion_tag('combo/gnm/place_map.html') @register.inclusion_tag('combo/gnm/place_map.html')
def gnm_place_map(lat, lng): def gnm_place_map(lat, lng):
map_cell = Map() map_cell = Map()
@ -771,6 +808,7 @@ def gnm_place_map(lat, lng):
context['init_lng'] = lng context['init_lng'] = lng
return context return context
@register.inclusion_tag('combo/gnm/airquality_map.html', takes_context=True) @register.inclusion_tag('combo/gnm/airquality_map.html', takes_context=True)
def gnm_airquality_map(context): def gnm_airquality_map(context):
map_cell = Map() map_cell = Map()
@ -781,20 +819,20 @@ def gnm_airquality_map(context):
context.push(map_cell.get_cell_extra_context({})) context.push(map_cell.get_cell_extra_context({}))
return context return context
_json_script_escapes = { _json_script_escapes = {
ord('>'): '\\u003E', ord('>'): '\\u003E',
ord('<'): '\\u003C', ord('<'): '\\u003C',
ord('&'): '\\u0026', ord('&'): '\\u0026',
} }
@register.filter(is_safe=True) @register.filter(is_safe=True)
def json_script(value, element_id): def json_script(value, element_id):
json_str = json.dumps(value, cls=DjangoJSONEncoder) json_str = json.dumps(value, cls=DjangoJSONEncoder)
json_str = json_str.replace('>', '\\u003E').replace('<', '\\u003C').replace('&', '\\u0026') json_str = json_str.replace('>', '\\u003E').replace('<', '\\u003C').replace('&', '\\u0026')
return format_html( return format_html('<script id="{}" type="application/json">{}</script>', element_id, mark_safe(json_str))
'<script id="{}" type="application/json">{}</script>',
element_id, mark_safe(json_str)
)
@register.simple_tag @register.simple_tag
def get_goto_cell(page, request): def get_goto_cell(page, request):
@ -811,16 +849,19 @@ def get_goto_cell(page, request):
cell.save() cell.save()
return cell return cell
@register.simple_tag @register.simple_tag
def get_collectivity_slugs(): def get_collectivity_slugs():
return list(settings.COLLECTIVITY_LABELS.keys()) return list(settings.COLLECTIVITY_LABELS.keys())
@register.filter @register.filter
def indice_values(indices): def indice_values(indices):
for key in ('indice_j-1', 'indice_j', 'indice_j+1'): for key in ('indice_j-1', 'indice_j', 'indice_j+1'):
if indices.get(key): if indices.get(key):
yield indices.get(key) yield indices.get(key)
@register.filter @register.filter
def airquality_hack(cell, request): def airquality_hack(cell, request):
if cell.key == 'airquality' and not cell.parameters: if cell.key == 'airquality' and not cell.parameters:

View File

@ -27,6 +27,7 @@ from combo.apps.dashboard.models import Tile
from combo.data.models import ConfigJsonCell from combo.data.models import ConfigJsonCell
from combo.utils import requests, get_templated_url from combo.utils import requests, get_templated_url
def plusone(request, *args, **kwargs): def plusone(request, *args, **kwargs):
# add reference to a jsondatastore with slug "plus1" # add reference to a jsondatastore with slug "plus1"
reference = request.GET.get('ref') reference = request.GET.get('ref')
@ -37,11 +38,14 @@ def plusone(request, *args, **kwargs):
passerelle_url += '?name_id=[user_nameid]' passerelle_url += '?name_id=[user_nameid]'
passerelle_url = get_templated_url(passerelle_url, context) passerelle_url = get_templated_url(passerelle_url, context)
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
requests.post(passerelle_url, remote_service='auto', requests.post(
without_user=True, passerelle_url,
headers={'Accept': 'application/json'}, remote_service='auto',
json={'reference': reference}, without_user=True,
timeout=2) headers={'Accept': 'application/json'},
json={'reference': reference},
timeout=2,
)
messages.info(request, u'Merci, votre confirmation nous est utile.') messages.info(request, u'Merci, votre confirmation nous est utile.')
if request.user and request.user.is_authenticated(): if request.user and request.user.is_authenticated():
@ -49,6 +53,7 @@ def plusone(request, *args, **kwargs):
else: else:
return HttpResponseRedirect('/services/') return HttpResponseRedirect('/services/')
def share(request, *args, **kwargs): def share(request, *args, **kwargs):
subject_template = 'gnm/share_email_subject.txt' subject_template = 'gnm/share_email_subject.txt'
text_body_template = 'gnm/share_email_body.txt' text_body_template = 'gnm/share_email_body.txt'
@ -130,7 +135,9 @@ def cartads_unsubscribe(request, *args, **kwargs):
if numero_dossier: if numero_dossier:
context = RequestContext(request, {'request': request}) context = RequestContext(request, {'request': request})
context.update(cell.get_cell_extra_context(context)) context.update(cell.get_cell_extra_context(context))
action_url = get_templated_url(settings.JSON_CELL_TYPES['cartads-dossiers']['actions']['unsubscribe']['url'], context) action_url = get_templated_url(
settings.JSON_CELL_TYPES['cartads-dossiers']['actions']['unsubscribe']['url'], context
)
action_url += '&dossier_number=' + numero_dossier action_url += '&dossier_number=' + numero_dossier
response = requests.get(action_url, remote_service='auto', without_user=True) response = requests.get(action_url, remote_service='auto', without_user=True)
if response.ok: if response.ok:

1138
debian/50gnm.py vendored

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ from distutils.command.sdist import sdist
from distutils.cmd import Command from distutils.cmd import Command
from setuptools import setup, find_packages from setuptools import setup, find_packages
class eo_sdist(sdist): class eo_sdist(sdist):
def run(self): def run(self):
if os.path.exists('VERSION'): if os.path.exists('VERSION'):
@ -24,26 +25,28 @@ class eo_sdist(sdist):
if os.path.exists('VERSION'): if os.path.exists('VERSION'):
os.remove('VERSION') os.remove('VERSION')
def get_version(): def get_version():
if os.path.exists('VERSION'): if os.path.exists('VERSION'):
with open('VERSION', 'r') as v: with open('VERSION', 'r') as v:
return v.read() return v.read()
if os.path.exists('.git'): if os.path.exists('.git'):
p = subprocess.Popen(['git','describe','--dirty=.dirty','--match=v*'], p = subprocess.Popen(
stdout=subprocess.PIPE, stderr=subprocess.PIPE) ['git', 'describe', '--dirty=.dirty', '--match=v*'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
result = p.communicate()[0] result = p.communicate()[0]
if p.returncode == 0: if p.returncode == 0:
result = result.decode('ascii').strip()[1:] # strip spaces/newlines and initial v result = result.decode('ascii').strip()[1:] # strip spaces/newlines and initial v
if '-' in result: # not a tagged version if '-' in result: # not a tagged version
real_number, commit_count, commit_hash = result.split('-', 2) real_number, commit_count, commit_hash = result.split('-', 2)
version = '%s.post%s+%s' % (real_number, commit_count, commit_hash) version = '%s.post%s+%s' % (real_number, commit_count, commit_hash)
else: else:
version = result version = result
return version return version
else: else:
return '0.0.post%s' % len( return '0.0.post%s' % len(subprocess.check_output(['git', 'rev-list', 'HEAD']).splitlines())
subprocess.check_output(
['git', 'rev-list', 'HEAD']).splitlines())
return '0.0' return '0.0'
@ -60,6 +63,7 @@ class compile_translations(Command):
def run(self): def run(self):
try: try:
from django.core.management import call_command from django.core.management import call_command
for path, dirs, files in os.walk('combo_plugin_gnm'): for path, dirs, files in os.walk('combo_plugin_gnm'):
if 'locale' not in dirs: if 'locale' not in dirs:
continue continue
@ -113,5 +117,5 @@ setup(
'compile_translations': compile_translations, 'compile_translations': compile_translations,
'install_lib': install_lib, 'install_lib': install_lib,
'sdist': eo_sdist, 'sdist': eo_sdist,
} },
) )

View File

@ -9,14 +9,14 @@ from combo_plugin_gnm.templatetags.gnm import as_opening_hours_badge
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
GEOJSON = json.load(open(os.path.join( GEOJSON = json.load(open(os.path.join(BASE_DIR, 'tests/data/mairie-geojson.json')))['features']
BASE_DIR, 'tests/data/mairie-geojson.json')))['features'] MDR_GEOJSON = json.load(open(os.path.join(BASE_DIR, 'tests/data/mdr-geojson.json')))['features']
MDR_GEOJSON = json.load(open(os.path.join(
BASE_DIR, 'tests/data/mdr-geojson.json')))['features']
TZOFFSETS = {"Europe/Paris": 3600} TZOFFSETS = {"Europe/Paris": 3600}
@pytest.mark.freeze_time("2018-03-04 23:00:00",) @pytest.mark.freeze_time(
"2018-03-04 23:00:00",
)
def test_every_mairie_closed(): def test_every_mairie_closed():
"""every mairie is closed at mignight""" """every mairie is closed at mignight"""
opening_hours = [as_opening_hours_badge(x) for x in GEOJSON] opening_hours = [as_opening_hours_badge(x) for x in GEOJSON]
@ -25,8 +25,11 @@ def test_every_mairie_closed():
def test_all_mairie_data_parsed_correct(): def test_all_mairie_data_parsed_correct():
"""everything got parsed correctly""" """everything got parsed correctly"""
opening_hours = [as_opening_hours_badge(x) for x in GEOJSON opening_hours = [
if x['properties'].get('openinghours') or x['properties'].get('openinghoursspecification')] as_opening_hours_badge(x)
for x in GEOJSON
if x['properties'].get('openinghours') or x['properties'].get('openinghoursspecification')
]
assert opening_hours.count('') == 0 assert opening_hours.count('') == 0
@ -88,7 +91,9 @@ def test_mairie_bron_saturday():
@pytest.mark.freeze_time("2018-03-05 09:59:13") @pytest.mark.freeze_time("2018-03-05 09:59:13")
def test_jonage_open(): def test_jonage_open():
"Jonage is defined only by openinghoursspecification data" "Jonage is defined only by openinghoursspecification data"
test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][0] test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][
0
]
klass, label = 'open', u"Ouvert jusqu'à 12h30" klass, label = 'open', u"Ouvert jusqu'à 12h30"
assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label)) assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label))
@ -96,7 +101,9 @@ def test_jonage_open():
@pytest.mark.freeze_time("2018-03-05 11:32:00") @pytest.mark.freeze_time("2018-03-05 11:32:00")
def test_jonage_soon_to_be_closed(): def test_jonage_soon_to_be_closed():
"Jonage is defined only by openinghoursspecification data" "Jonage is defined only by openinghoursspecification data"
test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][0] test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][
0
]
klass, label = 'soon-to-be-closed', u"Ouvert jusqu'à 12h30" klass, label = 'soon-to-be-closed', u"Ouvert jusqu'à 12h30"
assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label)) assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label))
@ -104,7 +111,9 @@ def test_jonage_soon_to_be_closed():
@pytest.mark.freeze_time("2018-03-10 17:30:00") @pytest.mark.freeze_time("2018-03-10 17:30:00")
def test_jonage_closed(): def test_jonage_closed():
"Jonage is defined only by openinghoursspecification data" "Jonage is defined only by openinghoursspecification data"
test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][0] test_html = [as_opening_hours_badge(x) for x in GEOJSON if x['properties']['nom'] == 'Mairie de Jonage'][
0
]
klass, label = 'closed', u"Réouvre lundi à 8h30" klass, label = 'closed', u"Réouvre lundi à 8h30"
assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label)) assert test_html == mark_safe(u'<div class="badge %s"><span>%s</span></div>' % (klass, label))
@ -168,18 +177,21 @@ def test_mairie_holiday():
@pytest.mark.freeze_time("2018-03-05 00:30:00") @pytest.mark.freeze_time("2018-03-05 00:30:00")
@pytest.mark.parametrize('day, hours, badge, text', [ @pytest.mark.parametrize(
('mercredi_pm', '14h30-17h45', 'closed', 'Réouvre mercredi à 14h30'), 'day, hours, badge, text',
('mercredi_pm', '00h00-24h00', 'closed', 'Réouvre mercredi 24h/24'), [
('mardi_pm', '14h30-17h45', 'closed', 'Réouvre demain à 14h30'), ('mercredi_pm', '14h30-17h45', 'closed', 'Réouvre mercredi à 14h30'),
('mardi_pm', '14h30-00h15', 'closed', 'Réouvre demain à 14h30'), ('mercredi_pm', '00h00-24h00', 'closed', 'Réouvre mercredi 24h/24'),
('lundi_pm', '14h30-17h45', 'closed', 'Réouvre à 14h30'), ('mardi_pm', '14h30-17h45', 'closed', 'Réouvre demain à 14h30'),
('lundi_am', '08h30-11h45', 'closed', 'Ouvre à 8h30'), ('mardi_pm', '14h30-00h15', 'closed', 'Réouvre demain à 14h30'),
('lundi_am', '00h00-00h45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('lundi_pm', '14h30-17h45', 'closed', 'Réouvre à 14h30'),
('dimanche_pm', '20h30-00h45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('lundi_am', '08h30-11h45', 'closed', 'Ouvre à 8h30'),
('lundi_am', '00h15-24h00', 'open', "Ouvert jusqu'à minuit"), ('lundi_am', '00h00-00h45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
('lundi_am', '00h00-24h00', 'open', "Ouvert 24h/24"), ('dimanche_pm', '20h30-00h45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
]) ('lundi_am', '00h15-24h00', 'open', "Ouvert jusqu'à minuit"),
('lundi_am', '00h00-24h00', 'open', "Ouvert 24h/24"),
],
)
def test_mdr_format(day, hours, badge, text): def test_mdr_format(day, hours, badge, text):
geojson = """ geojson = """
{ {
@ -187,49 +199,61 @@ def test_mdr_format(day, hours, badge, text):
"%s" : "%s" "%s" : "%s"
} }
} }
""" % (day, hours) """ % (
day,
hours,
)
html = as_opening_hours_badge(json.loads(geojson)) html = as_opening_hours_badge(json.loads(geojson))
assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text) assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text)
@pytest.mark.freeze_time("2018-03-05 00:30:00") @pytest.mark.freeze_time("2018-03-05 00:30:00")
@pytest.mark.parametrize('openinghour, badge, text', [ @pytest.mark.parametrize(
('We 14:30-17:45', 'closed', 'Réouvre mercredi à 14h30'), 'openinghour, badge, text',
('We 00:00-24:00', 'closed', 'Réouvre mercredi 24h/24'), [
('Tu 14:30-17:45', 'closed', 'Réouvre demain à 14h30'), ('We 14:30-17:45', 'closed', 'Réouvre mercredi à 14h30'),
('Tu 14:30-00:15', 'closed', 'Réouvre demain à 14h30'), ('We 00:00-24:00', 'closed', 'Réouvre mercredi 24h/24'),
('Mo 14:30-17:45', 'closed', 'Réouvre à 14h30'), ('Tu 14:30-17:45', 'closed', 'Réouvre demain à 14h30'),
('Mo 08:30-11:45', 'closed', 'Ouvre à 8h30'), ('Tu 14:30-00:15', 'closed', 'Réouvre demain à 14h30'),
('Mo 00:00-00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('Mo 14:30-17:45', 'closed', 'Réouvre à 14h30'),
('Su 20:30-00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('Mo 08:30-11:45', 'closed', 'Ouvre à 8h30'),
('Mo 00:15-24:00', 'open', "Ouvert jusqu'à minuit"), ('Mo 00:00-00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
('Mo 00:00-24:00', 'open', "Ouvert 24h/24"), ('Su 20:30-00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
]) ('Mo 00:15-24:00', 'open', "Ouvert jusqu'à minuit"),
('Mo 00:00-24:00', 'open', "Ouvert 24h/24"),
],
)
def test_mairie_format_openinghours(openinghour, badge, text): def test_mairie_format_openinghours(openinghour, badge, text):
geojson = """ geojson = (
"""
{ {
"properties": { "properties": {
"openinghours": ["%s"] "openinghours": ["%s"]
} }
} }
""" % openinghour """
% openinghour
)
html = as_opening_hours_badge(json.loads(geojson)) html = as_opening_hours_badge(json.loads(geojson))
assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text) assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text)
@pytest.mark.freeze_time("2018-03-05 00:30:00") @pytest.mark.freeze_time("2018-03-05 00:30:00")
@pytest.mark.parametrize('day, opens, closes, badge, text', [ @pytest.mark.parametrize(
('Wednesday', '14:30', '17:45', 'closed', 'Réouvre mercredi à 14h30'), 'day, opens, closes, badge, text',
('Wednesday', '00:00', '24:00', 'closed', 'Réouvre mercredi 24h/24'), [
('Tuesday', '14:30', '17:45', 'closed', 'Réouvre demain à 14h30'), ('Wednesday', '14:30', '17:45', 'closed', 'Réouvre mercredi à 14h30'),
('Tuesday', '14:30', '00:15', 'closed', 'Réouvre demain à 14h30'), ('Wednesday', '00:00', '24:00', 'closed', 'Réouvre mercredi 24h/24'),
('Monday', '14:30', '17:45', 'closed', 'Réouvre à 14h30'), ('Tuesday', '14:30', '17:45', 'closed', 'Réouvre demain à 14h30'),
('Monday', '08:30', '11:45', 'closed', 'Ouvre à 8h30'), ('Tuesday', '14:30', '00:15', 'closed', 'Réouvre demain à 14h30'),
('Monday', '00:00', '00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('Monday', '14:30', '17:45', 'closed', 'Réouvre à 14h30'),
('Sunday', '20:30', '00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"), ('Monday', '08:30', '11:45', 'closed', 'Ouvre à 8h30'),
('Monday', '00:15', '24:00', 'open', "Ouvert jusqu'à minuit"), ('Monday', '00:00', '00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
('Monday', '00:00', '24:00', 'open', "Ouvert 24h/24"), ('Sunday', '20:30', '00:45', 'soon-to-be-closed', "Ouvert jusqu'à 0h45"),
]) ('Monday', '00:15', '24:00', 'open', "Ouvert jusqu'à minuit"),
('Monday', '00:00', '24:00', 'open', "Ouvert 24h/24"),
],
)
def test_mairie_format_openinghoursspecification(day, opens, closes, badge, text): def test_mairie_format_openinghoursspecification(day, opens, closes, badge, text):
geojson = """ geojson = """
{ {
@ -243,6 +267,10 @@ def test_mairie_format_openinghoursspecification(day, opens, closes, badge, text
}] }]
} }
} }
""" % (opens, closes, day) """ % (
opens,
closes,
day,
)
html = as_opening_hours_badge(json.loads(geojson)) html = as_opening_hours_badge(json.loads(geojson))
assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text) assert html == '<div class="badge %s"><span>%s</span></div>' % (badge, text)

View File

@ -8,8 +8,7 @@ from combo_plugin_gnm.templatetags.gnm import get_mairie_opening_hours
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
GEOJSON = json.load(open(os.path.join( GEOJSON = json.load(open(os.path.join(BASE_DIR, 'tests/data/mairie-geojson.json')))['features']
BASE_DIR, 'tests/data/mairie-geojson.json')))['features']
TZOFFSETS = {"Europe/Paris": 3600} TZOFFSETS = {"Europe/Paris": 3600}
@ -30,15 +29,35 @@ def test_mairie_hours_special_data():
for x in GEOJSON: for x in GEOJSON:
if x['properties']['identifiant'] == 'S1376': if x['properties']['identifiant'] == 'S1376':
# La Mulatière # La Mulatière
assert get_mairie_opening_hours(x) == [('lundi', {'am': u'08h30-12h00', 'pm': None}), ('mardi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}), ('mercredi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}), ('jeudi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}), ('vendredi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}), ('samedi', {'am': u'09h00-11h45', 'pm': None})] assert get_mairie_opening_hours(x) == [
('lundi', {'am': u'08h30-12h00', 'pm': None}),
('mardi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}),
('mercredi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}),
('jeudi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}),
('vendredi', {'am': u'08h30-12h30', 'pm': u'13h30-17h00'}),
('samedi', {'am': u'09h00-11h45', 'pm': None}),
]
if x['properties']['identifiant'] == 'S1437': if x['properties']['identifiant'] == 'S1437':
# special openinghours format with days intervals, comma-separated list and one day definition with a saturday # special openinghours format with days intervals, comma-separated list and one day definition with a saturday
assert get_mairie_opening_hours(x) == [('lundi', {'am': u'08h45-12h30', 'pm': u'14h00-16h45'}), ('mardi', {'am': u'08h45-16h45', 'pm': ''}), ('mercredi', {'am': u'08h45-16h45', 'pm': ''}), ('jeudi', {'am': u'08h45-18h00', 'pm': ''}), ('vendredi', {'am': u'08h45-16h45', 'pm': ''}), ('samedi', {'am': u'09h00-12h00', 'pm': None})] assert get_mairie_opening_hours(x) == [
('lundi', {'am': u'08h45-12h30', 'pm': u'14h00-16h45'}),
('mardi', {'am': u'08h45-16h45', 'pm': ''}),
('mercredi', {'am': u'08h45-16h45', 'pm': ''}),
('jeudi', {'am': u'08h45-18h00', 'pm': ''}),
('vendredi', {'am': u'08h45-16h45', 'pm': ''}),
('samedi', {'am': u'09h00-12h00', 'pm': None}),
]
if x['properties']['identifiant'] == 'S5564': if x['properties']['identifiant'] == 'S5564':
# classic openinghours days interval for am and pm # classic openinghours days interval for am and pm
assert get_mairie_opening_hours(x) == [('lundi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}), ('mardi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}), ('mercredi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}), ('jeudi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}), ('vendredi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'})] assert get_mairie_opening_hours(x) == [
('lundi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}),
('mardi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}),
('mercredi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}),
('jeudi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}),
('vendredi', {'am': u'08h30-12h15', 'pm': u'13h15-17h00'}),
]
@pytest.mark.freeze_time("2018-03-05 15:59:00") @pytest.mark.freeze_time("2018-03-05 15:59:00")
@ -46,7 +65,14 @@ def test_mairie_openinghoursspecification_period_valid():
"""Test valid periods of openinghoursspecification timetables""" """Test valid periods of openinghoursspecification timetables"""
for x in GEOJSON: for x in GEOJSON:
if x['properties']['nom'] == 'Mairie de Jonage': if x['properties']['nom'] == 'Mairie de Jonage':
assert get_mairie_opening_hours(x) == [('lundi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}), ('mardi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}), ('mercredi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}), ('jeudi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}), ('vendredi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}), ('samedi', {'am': '09h00-12h00', 'pm': '14h00-17h00'})] assert get_mairie_opening_hours(x) == [
('lundi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}),
('mardi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}),
('mercredi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}),
('jeudi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}),
('vendredi', {'am': '08h30-12h30', 'pm': '14h00-17h00'}),
('samedi', {'am': '09h00-12h00', 'pm': '14h00-17h00'}),
]
return return
@ -55,20 +81,46 @@ def test_mairie_openinghoursspecification_period_all_closed():
# display known format but no opening hours as all closed # display known format but no opening hours as all closed
for x in GEOJSON: for x in GEOJSON:
if x['properties']['nom'] == 'Mairie de Jonage': if x['properties']['nom'] == 'Mairie de Jonage':
assert get_mairie_opening_hours(x) == [('lundi', {'am': None, 'pm': ''}), ('mardi', {'am': None, 'pm': ''}), ('mercredi', {'am': None, 'pm': ''}), ('jeudi', {'am': None, 'pm': ''}), ('vendredi', {'am': None, 'pm': ''}), ('samedi', {'am': None, 'pm': ''}), ('dimanche', {'am': None, 'pm': ''})] assert get_mairie_opening_hours(x) == [
('lundi', {'am': None, 'pm': ''}),
('mardi', {'am': None, 'pm': ''}),
('mercredi', {'am': None, 'pm': ''}),
('jeudi', {'am': None, 'pm': ''}),
('vendredi', {'am': None, 'pm': ''}),
('samedi', {'am': None, 'pm': ''}),
('dimanche', {'am': None, 'pm': ''}),
]
return return
def test_mairie_sathonay_timetable(): def test_mairie_sathonay_timetable():
"""Sathonay-Village S1415""" """Sathonay-Village S1415"""
test_time_table = [get_mairie_opening_hours(x) for x in GEOJSON if x['properties']['identifiant'] == 'S1415'][0] test_time_table = [
assert test_time_table == [('lundi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}), ('mardi', {'am': u'08h30-12h00', 'pm': u'13h30-17h00'}), ('mercredi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}), ('jeudi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}), ('vendredi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}), ('samedi', {'am': u'08h30-12h00', 'pm': None})] get_mairie_opening_hours(x) for x in GEOJSON if x['properties']['identifiant'] == 'S1415'
][0]
assert test_time_table == [
('lundi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}),
('mardi', {'am': u'08h30-12h00', 'pm': u'13h30-17h00'}),
('mercredi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}),
('jeudi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}),
('vendredi', {'am': u'08h30-12h00', 'pm': u'14h00-17h00'}),
('samedi', {'am': u'08h30-12h00', 'pm': None}),
]
def test_mairie_saint_priest(): def test_mairie_saint_priest():
"S1406" "S1406"
test_time_table = [get_mairie_opening_hours(x) for x in GEOJSON if x['properties']['identifiant'] == 'S1406'][0] test_time_table = [
assert test_time_table == [('lundi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}), ('mardi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}), ('mercredi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}), ('jeudi', {'am': u'08h15-11h15', 'pm': u'13h30-17h30'}), ('vendredi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}), ('samedi', {'am': u'09h00-11h30', 'pm': None})] get_mairie_opening_hours(x) for x in GEOJSON if x['properties']['identifiant'] == 'S1406'
][0]
assert test_time_table == [
('lundi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}),
('mardi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}),
('mercredi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}),
('jeudi', {'am': u'08h15-11h15', 'pm': u'13h30-17h30'}),
('vendredi', {'am': u'08h15-12h15', 'pm': u'13h30-17h30'}),
('samedi', {'am': u'09h00-11h30', 'pm': None}),
]
def test_mairie_format_openinghours(): def test_mairie_format_openinghours():