combo/combo/apps/dataviz/forms.py

131 lines
4.8 KiB
Python

# combo - content management system
# Copyright (C) 2015 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 sys
from collections import OrderedDict
from django import forms
from django.conf import settings
from django.db import transaction, connection
from django.db.models import Q
from combo.utils import requests, cache_during_request
from .models import ChartCell, ChartNgCell
class ChartForm(forms.ModelForm):
class Meta:
model = ChartCell
fields = ('title', 'url')
def __init__(self, *args, **kwargs):
super(ChartForm, self).__init__(*args, **kwargs)
available_charts = []
for site_key, site_dict in settings.KNOWN_SERVICES.get('bijoe').items():
result = requests.get(
'/visualization/json/',
remote_service=site_dict,
without_user=True,
headers={'accept': 'application/json'},
).json()
available_charts.extend([(x['path'], x['name']) for x in result])
available_charts.sort(key=lambda x: x[1])
self.fields['url'].widget = forms.Select(choices=available_charts)
@cache_during_request
def trigger_statistics_list_refresh():
if 'uwsgi' in sys.modules:
from combo.utils.spooler import refresh_statistics_list
tenant = getattr(connection, 'tenant', None)
transaction.on_commit(
lambda: refresh_statistics_list.spool(domain=getattr(tenant, 'domain_url', None))
)
class ChartNgForm(forms.ModelForm):
blank_choice = ('', '---------')
class Meta:
model = ChartNgCell
fields = (
'title',
'statistic',
'time_range',
'time_range_start',
'time_range_end',
'chart_type',
'height',
'sort_order',
'hide_null_values',
)
widgets = {
'time_range_start': forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),
'time_range_end': forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),
}
def __init__(self, *args, **kwargs):
trigger_statistics_list_refresh()
super().__init__(*args, **kwargs)
field_ids = list(self._meta.fields)
if not self.instance.statistic or self.instance.statistic.service_slug == 'bijoe':
field_ids = [
x for x in field_ids if x not in ('time_range', 'time_range_start', 'time_range_end')
]
stat_field = self.fields['statistic']
if not self.instance.statistic:
stat_field.queryset = stat_field.queryset.filter(available=True)
else:
# display current statistic in choices even if unavailable
stat_field.queryset = stat_field.queryset.filter(
Q(available=True) | Q(pk=self.instance.statistic.pk)
)
field_insert_index = field_ids.index('statistic') + 1
for filter_ in reversed(self.instance.statistic.filters):
filter_id = filter_['id']
choices = [(option['id'], option['label']) for option in filter_['options']]
initial = self.instance.filter_params.get(filter_id) or filter_.get('default')
required = filter_.get('required', False)
if not required:
choices.insert(0, self.blank_choice)
self.fields[filter_id] = forms.ChoiceField(
label=filter_['label'], choices=choices, required=required, initial=initial
)
field_ids.insert(field_insert_index, filter_id)
self.fields = OrderedDict((field_id, self.fields[field_id]) for field_id in field_ids)
def save(self, *args, **kwargs):
if 'statistic' in self.changed_data:
self.instance.filter_params.clear()
self.instance.time_range = ''
else:
for filter_ in self.instance.statistic.filters:
field = filter_['id']
value = self.cleaned_data.get(field)
if value:
self.instance.filter_params[field] = value
else:
self.instance.filter_params.pop(field, None)
return super().save(*args, **kwargs)