From 2d48329580f687920749e2103b4f8049c3fc912a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Fri, 23 Apr 2021 15:20:59 +0200
Subject: [PATCH] wcs: add categories field to CareForms cell (#53213)

---
 combo/apps/wcs/forms.py                       | 12 ++++
 .../migrations/0027_careforms_categories.py   | 17 +++++
 combo/apps/wcs/models.py                      | 30 +++++++-
 .../wcs/templates/combo/wcs/care_forms.html   |  2 +-
 tests/test_wcs.py                             | 69 +++++++++++++++++--
 5 files changed, 123 insertions(+), 7 deletions(-)
 create mode 100644 combo/apps/wcs/migrations/0027_careforms_categories.py

diff --git a/combo/apps/wcs/forms.py b/combo/apps/wcs/forms.py
index f4acaa5e..a9dc3f6b 100644
--- a/combo/apps/wcs/forms.py
+++ b/combo/apps/wcs/forms.py
@@ -23,6 +23,7 @@ from combo.utils.forms import MultiSortWidget
 from .models import (
     WcsCardInfosCell,
     WcsCardsCell,
+    WcsCareFormsCell,
     WcsCategoryCell,
     WcsCurrentDraftsCell,
     WcsCurrentFormsCell,
@@ -153,6 +154,17 @@ class WcsCurrentDraftsCellForm(WcsFormsMixin, forms.ModelForm):
         self._init_categories()
 
 
+class WcsCareFormsCellForm(WcsFormsMixin, forms.ModelForm):
+    class Meta:
+        model = WcsCareFormsCell
+        fields = ['wcs_site', 'categories']
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self._init_wcs_site()
+        self._init_categories()
+
+
 class BackofficeSubmissionCellForm(WcsFormsMixin, forms.ModelForm):
     class Meta:
         model = WcsCurrentDraftsCell
diff --git a/combo/apps/wcs/migrations/0027_careforms_categories.py b/combo/apps/wcs/migrations/0027_careforms_categories.py
new file mode 100644
index 00000000..07cd3910
--- /dev/null
+++ b/combo/apps/wcs/migrations/0027_careforms_categories.py
@@ -0,0 +1,17 @@
+import jsonfield.fields
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('wcs', '0026_text_to_jsonb'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='wcscareformscell',
+            name='categories',
+            field=jsonfield.fields.JSONField(blank=True, default=dict, verbose_name='Categories'),
+        ),
+    ]
diff --git a/combo/apps/wcs/models.py b/combo/apps/wcs/models.py
index 67b312b8..ece53e49 100644
--- a/combo/apps/wcs/models.py
+++ b/combo/apps/wcs/models.py
@@ -693,7 +693,9 @@ class WcsFormsOfCategoryCell(WcsCommonCategoryCell, WcsBlurpMixin):
 
 
 @register_cell_class
-class WcsCareFormsCell(WcsDataBaseCell):
+class WcsCareFormsCell(WcsDataBaseCell, CategoriesValidityMixin):
+    categories = JSONField(_('Categories'), blank=True)
+
     api_url = '/api/forms/?limit=10'
     variable_name = 'care_forms'
     template_name = 'combo/wcs/care_forms.html'
@@ -703,6 +705,32 @@ class WcsCareFormsCell(WcsDataBaseCell):
     class Meta:
         verbose_name = _('Forms to process')
 
+    def get_default_form_class(self):
+        from .forms import WcsCareFormsCellForm
+
+        return WcsCareFormsCellForm
+
+    def get_cell_extra_context(self, context):
+        context = super().get_cell_extra_context(context)
+
+        categories_filter = []
+        if self.categories:
+            for category in self.categories.get('data', []):
+                categories_filter.append(tuple(category.split(':')))
+
+        for wcs_site in context['care_forms']:
+            if not context['care_forms'].get(wcs_site):
+                continue
+            if not context['care_forms'][wcs_site].get('data'):
+                continue
+            forms = context['care_forms'][wcs_site]['data']
+            if categories_filter:
+                forms = [x for x in forms if (wcs_site, x.get('category_slug')) in categories_filter]
+            context['care_forms'][wcs_site]['data'] = forms  # put it back
+            context['care_forms'][wcs_site]['categories'] = [v for k, v in categories_filter if k == wcs_site]
+
+        return context
+
 
 @register_cell_class
 class CategoriesCell(WcsDataBaseCell):
diff --git a/combo/apps/wcs/templates/combo/wcs/care_forms.html b/combo/apps/wcs/templates/combo/wcs/care_forms.html
index ec8b14ea..48414899 100644
--- a/combo/apps/wcs/templates/combo/wcs/care_forms.html
+++ b/combo/apps/wcs/templates/combo/wcs/care_forms.html
@@ -26,6 +26,6 @@
     </tbody>
   </table>
   {% endif %}
-  <p><a class="pk-button" href="{{ forms.url }}backoffice/management/">{% trans "See all forms" %}</a></p>
+  <p><a class="pk-button" href="{{ forms.url }}backoffice/management/listing{% if forms.categories %}?category_slugs={{ forms.categories|join:"," }}{% endif %}">{% trans "See all forms" %}</a></p>
 {% endfor %}
 {% endblock %}
diff --git a/tests/test_wcs.py b/tests/test_wcs.py
index 95835eae..ba92b0b8 100644
--- a/tests/test_wcs.py
+++ b/tests/test_wcs.py
@@ -96,10 +96,12 @@ WCS_FORMS_DATA = [
     {
         'form_receipt_datetime': '2019-10-17T16:46:03',
         'form_url_backoffice': '/backoffice/management/foobar/1/',
+        'category_slug': 'test-3',
     },
     {
         'form_receipt_datetime': '2019-10-17T16:46:04',
         'form_url_backoffice': '/backoffice/management/foobar/2/',
+        'category_slug': 'test-4',
     },
 ]
 
@@ -719,15 +721,26 @@ def test_care_forms_cell_render(mock_send, context):
 
     assert 'http://127.0.0.1:8999/backoffice/management/foobar/1' in result
     assert 'http://127.0.0.1:8999/backoffice/management/foobar/2' in result
-    assert '"http://127.0.0.1:8999/backoffice/management/"' in result
+    assert '"http://127.0.0.1:8999/backoffice/management/listing"' in result
     assert 'http://127.0.0.2:8999/backoffice/management/foobar/1' in result
     assert 'http://127.0.0.2:8999/backoffice/management/foobar/2' in result
-    assert '"http://127.0.0.2:8999/backoffice/management/"' in result
+    assert '"http://127.0.0.2:8999/backoffice/management/listing"' in result
 
     data = cell.get_data(context)
     assert 'default' in data
     assert 'other' in data
 
+    # limit to a category
+    cell.categories = {'data': ['default:test-3', 'other:test-4']}
+
+    result = cell.render(context)
+    assert 'http://127.0.0.1:8999/backoffice/management/foobar/1' in result
+    assert 'http://127.0.0.1:8999/backoffice/management/foobar/2' not in result
+    assert '"http://127.0.0.1:8999/backoffice/management/listing?category_slugs=test-3"' in result
+    assert 'http://127.0.0.2:8999/backoffice/management/foobar/1' not in result
+    assert 'http://127.0.0.2:8999/backoffice/management/foobar/2' in result
+    assert '"http://127.0.0.2:8999/backoffice/management/listing?category_slugs=test-4"' in result
+
 
 def test_care_forms_cell_validity(context):
     page = Page.objects.create(title='xxx', slug='test_care_forms_cell_render', template_name='standard')
@@ -767,6 +780,50 @@ def test_care_forms_cell_validity(context):
     assert validity_info.invalid_since is not None
 
 
+@mock.patch('combo.apps.wcs.utils.requests.send', side_effect=mocked_requests_send)
+def test_care_forms_cell_check_validity(mock_send, context):
+    page = Page.objects.create(title='xxx', slug='test_care_forms_cell_render', template_name='standard')
+    cell = WcsCareFormsCell.objects.create(page=page, placeholder='content', order=0)
+
+    # no category
+    cell.check_validity()
+    assert ValidityInfo.objects.exists() is False
+
+    # valid categories
+    cell.categories = {'data': ['default:test-3', 'default:test-9']}
+    cell.save()
+    cell.check_validity()
+    assert ValidityInfo.objects.exists() is False
+
+    # can not retrieve data, don't set cell as invalid
+    with mock.patch('combo.apps.wcs.models.requests.get') as requests_get:
+        mock_resp = Response()
+        mock_resp.status_code = 500
+        requests_get.return_value = mock_resp
+        cell.check_validity()
+    assert ValidityInfo.objects.exists() is False
+    with mock.patch('combo.apps.wcs.models.requests.get') as requests_get:
+        requests_get.side_effect = ConnectionError()
+        cell.check_validity()
+    assert ValidityInfo.objects.exists() is False
+
+    # can not retrieve categories, don't set cell as invalid
+    with mock.patch('combo.apps.wcs.models.requests.get') as requests_get:
+        mock_resp = Response()
+        mock_resp.status_code = 404
+        requests_get.return_value = mock_resp
+        cell.check_validity()
+    assert ValidityInfo.objects.exists() is False
+
+    # invalid category
+    cell.categories = {'data': ['default:foobar', 'default:test-9']}
+    cell.save()
+    cell.check_validity()
+    validity_info = ValidityInfo.objects.latest('pk')
+    assert validity_info.invalid_reason_code == 'wcs_category_not_found'
+    assert validity_info.invalid_since is not None
+
+
 @mock.patch('combo.apps.wcs.utils.requests.send', side_effect=mocked_requests_send)
 def test_care_forms_cell_render_single_site(mock_send, context):
     page = Page(title='xxx', slug='test_care_forms_cell_render', template_name='standard')
@@ -785,8 +842,8 @@ def test_care_forms_cell_render_single_site(mock_send, context):
     context['synchronous'] = True  # to get fresh content
 
     result = cell.render(context)
-    assert '"http://127.0.0.1:8999/backoffice/management/"' in result
-    assert '"http://127.0.0.2:8999/backoffice/management/"' not in result
+    assert '"http://127.0.0.1:8999/backoffice/management/listing"' in result
+    assert '"http://127.0.0.2:8999/backoffice/management/listing"' not in result
 
     data = cell.get_data(context)
     assert 'default' in data
@@ -1065,7 +1122,8 @@ def test_manager_forms_of_category_cell(mock_send, app, admin_user):
     assert resp.status_int == 302
 
 
-def test_manager_current_forms(app, admin_user):
+@mock.patch('combo.apps.wcs.utils.requests.send', side_effect=mocked_requests_send)
+def test_manager_current_forms(mock_send, app, admin_user):
     page = Page(title='One', slug='one', template_name='standard')
     page.save()
     app = login(app)
@@ -2017,6 +2075,7 @@ def test_hourly():
         klass.objects.create(page=page, placeholder='content', order=0)
     for klass in cell_classes:
         if klass in [
+            WcsCareFormsCell,
             WcsCurrentFormsCell,
             WcsCurrentDraftsCell,
             WcsFormsOfCategoryCell,
-- 
2.30.2

