dataviz: add option groups support (#65134)

This commit is contained in:
Valentin Deniaud 2022-05-11 15:51:42 +02:00
parent ccb841e289
commit c909f70ad6
2 changed files with 42 additions and 2 deletions

View File

@ -67,7 +67,16 @@ class ChartFiltersMixin:
fields = OrderedDict()
for filter_ in cell.available_filters:
filter_id = filter_['id']
choices = [(option['id'], option['label']) for option in filter_['options']]
has_option_groups = isinstance(filter_['options'][0], list)
if filter_['options'] and has_option_groups:
choices = [
(group, [(opt['id'], opt['label']) for opt in options])
for group, options in filter_['options']
]
else:
choices = [(option['id'], option['label']) for option in filter_['options']]
initial = cell.filter_params.get(filter_id, filter_.get('default'))
if filter_id == 'time_interval':
@ -81,7 +90,10 @@ class ChartFiltersMixin:
extra_variables = cell.page.get_extra_variables_keys()
variable_choices = [('variable:' + key, key) for key in extra_variables]
possible_choices = {choice[0] for choice in choices}
if has_option_groups:
possible_choices = {choice[0] for _, group_choices in choices for choice in group_choices}
else:
possible_choices = {choice[0] for choice in choices}
for choice in initial if isinstance(initial, list) else [initial]:
if not choice:
continue

View File

@ -457,6 +457,22 @@ STATISTICS_LIST = {
'id': 'with-future-data',
'future_data': True,
},
{
'url': 'https://authentic.example.com/api/statistics/option-groups/',
'name': 'Option groups',
'id': 'option-groups',
"filters": [
{
"id": "form",
"label": "Form",
"options": [
[None, [{'id': 'all', 'label': 'All'}]],
['Category A', [{'id': 'test', 'label': 'Test'}]],
['Category B', [{'id': 'test-2', 'label': 'test 2'}]],
],
}
],
},
]
}
@ -1395,6 +1411,18 @@ def test_chartng_cell_manager_new_api(app, admin_user, new_api_statistics):
cell.refresh_from_db()
assert cell.get_filter_params() == {}
option_groups_stat = Statistic.objects.get(slug='option-groups')
resp.form[field_prefix + 'statistic'] = option_groups_stat.pk
manager_submit_cell(resp.form)
assert resp.form[field_prefix + 'form'].options == [
('', True, '---------'),
('all', False, 'All'),
('test', False, 'Test'),
('test-2', False, 'test 2'),
]
assert resp.pyquery('optgroup[label="Category A"] option').val() == 'test'
assert resp.pyquery('optgroup[label="Category B"] option').val() == 'test-2'
@with_httmock(new_api_mock)
def test_chartng_cell_manager_future_data(app, admin_user, new_api_statistics):