From 4d9b11a7bced75f02dc5e35bac45a42a4d821b43 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= <fpeters@entrouvert.com>
Date: Sat, 18 Jan 2020 23:00:55 +0100
Subject: [PATCH] misc: remove obsolete parameters cell (#39087)

---
 combo/data/forms.py                           | 36 +-------
 .../migrations/0040_auto_20200119_1017.py     | 26 ++++++
 combo/data/models.py                          | 90 -------------------
 .../templates/combo/parameters-cell.html      | 14 ---
 4 files changed, 27 insertions(+), 139 deletions(-)
 create mode 100644 combo/data/migrations/0040_auto_20200119_1017.py
 delete mode 100644 combo/public/templates/combo/parameters-cell.html

diff --git a/combo/data/forms.py b/combo/data/forms.py
index 5ca614f2..364f94b3 100644
--- a/combo/data/forms.py
+++ b/combo/data/forms.py
@@ -18,45 +18,11 @@ import copy
 
 from django import forms
 
-from .models import Page, ParametersCell, MenuCell, LinkCell, LinkListCell, ConfigJsonCell
-from jsonfield.widgets import JSONWidget
+from .models import Page, MenuCell, LinkCell, LinkListCell, ConfigJsonCell
 
 from combo.utils import cache_during_request
 
 
-class ParametersForm(forms.Form):
-    choice = forms.ChoiceField(choices=[])
-
-    def __init__(self, *args, **kwargs):
-        self.parameters = kwargs.pop('parameters')
-        empty_label = kwargs.pop('empty_label')
-        super(ParametersForm, self).__init__(*args, **kwargs)
-        self.fields['choice'].choices = [('', empty_label)] + [(x['name'], x['name']) for x in self.parameters]
-
-    def clean(self):
-        choice = self.cleaned_data.get('choice')
-        for parameter in self.parameters:
-            if parameter['name'] == choice:
-                self.cleaned_data['choice'] = parameter['value']
-                break
-        return self.cleaned_data
-
-
-class ParametersCellForm(forms.ModelForm):
-    class Meta:
-        model = ParametersCell
-        fields = ('title', 'url', 'empty_label', 'parameters',)
-        widgets = {
-            # XXX: replace with a more ergonomic widget
-            'parameters': JSONWidget(
-                attrs={
-                    'rows': 30,
-                    'cols': 100,
-                    'style': 'resize: none'
-                })
-        }
-
-
 @cache_during_request
 def get_page_choices():
     pages = Page.get_as_reordered_flat_hierarchy(Page.objects.all())
diff --git a/combo/data/migrations/0040_auto_20200119_1017.py b/combo/data/migrations/0040_auto_20200119_1017.py
new file mode 100644
index 00000000..b1cf7492
--- /dev/null
+++ b/combo/data/migrations/0040_auto_20200119_1017.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.17 on 2020-01-19 09:17
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('data', '0039_link_list_cell'),
+    ]
+
+    operations = [
+        migrations.RemoveField(
+            model_name='parameterscell',
+            name='groups',
+        ),
+        migrations.RemoveField(
+            model_name='parameterscell',
+            name='page',
+        ),
+        migrations.DeleteModel(
+            name='ParametersCell',
+        ),
+    ]
diff --git a/combo/data/models.py b/combo/data/models.py
index bd84afe4..25d5e3aa 100644
--- a/combo/data/models.py
+++ b/combo/data/models.py
@@ -1080,96 +1080,6 @@ class FeedCell(CellBase):
         return super(FeedCell, self).render(context)
 
 
-@register_cell_class
-class ParametersCell(CellBase):
-    title = models.CharField(_('Title'), max_length=150, blank=True)
-    url = models.URLField(_('URL'), blank=True)
-    empty_label = models.CharField(_('Empty label'), max_length=64, default='---')
-    parameters = JSONField(_('Parameters'), blank=True,
-                           help_text=_('Must be a JSON list, containing dictionaries with 3 keys: '
-                                       'name, value and optionnally roles; name must be a string, '
-                                       'value must be a dictionary and roles must a list of role '
-                                       'names. Role names limit the visibility of the choice.'))
-
-    template_name = 'combo/parameters-cell.html'
-
-    class Meta:
-        verbose_name = _('Parameters')
-
-    def get_additional_label(self):
-        return self.title
-
-    def is_visible(self, user=None):
-        return bool(self.parameters) and super(ParametersCell, self).is_visible(user=user)
-
-    def validate_schema(self, value):
-        if not isinstance(value, list):
-            return False, _('it must be a list')
-        if not all(isinstance(x, dict) for x in value):
-            return False, _('it must be a list of dictionaries')
-        if not all(set(x.keys()) <= set(['roles', 'name', 'value']) for x in value):
-            return False, _('permitted keys in the dictionaries are name, roles and value')
-        for x in value:
-            if 'roles' not in x:
-                continue
-            if not isinstance(x['roles'], list):
-                return False, _('roles must be a list')
-            if not all(isinstance(y, unicode) for y in x['roles']):
-                return False, _('roles must be a list of strings')
-            if len(set(x['roles'])) != len(x['roles']):
-                return False, _('role\'s names must be unique in a list of roles')
-            existing = Group.objects.filter(name__in=x['roles']).values_list('name', flat=True)
-            if len(existing) != len(x['roles']):
-                l = u', '.join(set(x['roles']) - set(existing))
-                return False, _('role(s) %s do(es) not exist') % l
-        if not all(isinstance(x['name'], unicode) for x in value):
-            return False, _('name must be a string')
-        if not all(isinstance(x['value'], dict) for x in value):
-            return False, ('value must be a dictionary')
-        if not len(set(x['name'] for x in value)) == len(value):
-            return False, _('names must be unique')
-        return True, ''
-
-    def clean(self):
-        validated, msg = self.validate_schema(self.parameters)
-        if not validated:
-            raise ValidationError(_('Parameters does not validate the expected schema: %s') % msg)
-
-    def get_form(self, request):
-        from .forms import ParametersForm
-        if not request.user.is_anonymous:
-            groups = set(request.user.groups.values_list('name', flat=True))
-        else:
-            groups = set()
-        parameters = [param for param in self.parameters
-                      if not param.get('roles') or set(param['roles']) & groups]
-        return ParametersForm(request.GET, parameters=parameters,
-                              empty_label=self.empty_label,
-                              prefix='parameters-cells-' + str(self.pk))
-
-    def modify_global_context(self, context, request):
-        if not bool(self.parameters):
-            return
-        # Store form for later use by get_cell_extra_context
-        self._form = self.get_form(request)
-        if self._form.is_valid():
-            parameters = context['parameters'] if 'parameters' in context else {}
-            context['parameters'] = parameters
-            parameters.update(self._form.cleaned_data['choice'])
-
-    def get_cell_extra_context(self, context):
-        ctx = super(ParametersCell, self).get_cell_extra_context(context)
-        if hasattr(self, '_form'):
-            ctx['form'] = self._form
-        ctx['title'] = self.title
-        ctx['url'] = utils.get_templated_url(self.url)
-        return ctx
-
-    def get_default_form_class(self):
-        from .forms import ParametersCellForm
-        return ParametersCellForm
-
-
 @register_cell_class
 class ParentContentCell(CellBase):
     class Meta:
diff --git a/combo/public/templates/combo/parameters-cell.html b/combo/public/templates/combo/parameters-cell.html
deleted file mode 100644
index 4b7bc9a5..00000000
--- a/combo/public/templates/combo/parameters-cell.html
+++ /dev/null
@@ -1,14 +0,0 @@
-{% block cell-content %}
-{% if form %}
-    {% if title %}
-    <h2>{% if url %}<a href="{{url}}">{% endif %}{{title}}{% if url %}</a>{% endif %}</h2>
-    {% endif %}
-    <form class="combo-parameters-cell-form" method="get">
-      {{ form.choice }}
-    </form>
-    <!--
-      Parameters: {{ parameters|pprint }}
-      Choice: {{ form.cleaned_data.choice|pprint }}
-    -->
-{% endif %}
-{% endblock %}
-- 
2.25.0

