From 62a8fff9a034749c7ec2d1ef8c05b7704c577737 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Mon, 21 Oct 2019 12:03:24 +0200
Subject: [PATCH] wcs: add a cell "forms in your care" (#31989)

---
 .../wcs/migrations/0017_wcscareformscell.py   | 39 ++++++++
 combo/apps/wcs/models.py                      | 11 +++
 .../wcs/templates/combo/wcs/care_forms.html   | 31 +++++++
 tests/test_wcs.py                             | 93 ++++++++++++++++++-
 4 files changed, 173 insertions(+), 1 deletion(-)
 create mode 100644 combo/apps/wcs/migrations/0017_wcscareformscell.py
 create mode 100644 combo/apps/wcs/templates/combo/wcs/care_forms.html

diff --git a/combo/apps/wcs/migrations/0017_wcscareformscell.py b/combo/apps/wcs/migrations/0017_wcscareformscell.py
new file mode 100644
index 0000000..f4e1292
--- /dev/null
+++ b/combo/apps/wcs/migrations/0017_wcscareformscell.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.18 on 2019-10-18 13:48
+from __future__ import unicode_literals
+
+import combo.apps.wcs.models
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('auth', '0008_alter_user_username_max_length'),
+        ('data', '0037_auto_20190701_2118'),
+        ('wcs', '0016_backofficesubmissioncell'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='WcsCareFormsCell',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('placeholder', models.CharField(max_length=20)),
+                ('order', models.PositiveIntegerField()),
+                ('slug', models.SlugField(blank=True, verbose_name='Slug')),
+                ('extra_css_class', models.CharField(blank=True, max_length=100, verbose_name='Extra classes for CSS styling')),
+                ('public', models.BooleanField(default=True, verbose_name='Public')),
+                ('restricted_to_unlogged', models.BooleanField(default=False, verbose_name='Restrict to unlogged users')),
+                ('last_update_timestamp', models.DateTimeField(auto_now=True)),
+                ('wcs_site', models.CharField(blank=True, max_length=50, verbose_name='Site')),
+                ('groups', models.ManyToManyField(blank=True, to='auth.Group', verbose_name='Groups')),
+                ('page', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='data.Page')),
+            ],
+            options={
+                'verbose_name': 'Forms in your care',
+            },
+            bases=(models.Model, combo.apps.wcs.models.WcsBlurpMixin),
+        ),
+    ]
diff --git a/combo/apps/wcs/models.py b/combo/apps/wcs/models.py
index c305336..0666bb8 100644
--- a/combo/apps/wcs/models.py
+++ b/combo/apps/wcs/models.py
@@ -504,6 +504,17 @@ class WcsFormsOfCategoryCell(WcsCommonCategoryCell, WcsBlurpMixin):
                     'text': text}
 
 
+@register_cell_class
+class WcsCareFormsCell(WcsDataBaseCell):
+    api_url = '/api/forms/?limit=10'
+    variable_name = 'care_forms'
+    template_name = 'combo/wcs/care_forms.html'
+    cache_duration = 600
+
+    class Meta:
+        verbose_name = _('Forms in your care')
+
+
 @register_cell_class
 class CategoriesCell(WcsDataBaseCell):
     api_url = '/api/categories/?full=on'
diff --git a/combo/apps/wcs/templates/combo/wcs/care_forms.html b/combo/apps/wcs/templates/combo/wcs/care_forms.html
new file mode 100644
index 0000000..78e9fc5
--- /dev/null
+++ b/combo/apps/wcs/templates/combo/wcs/care_forms.html
@@ -0,0 +1,31 @@
+{% load i18n combo %}
+{% block cell-content %}
+{% for slug, forms in care_forms.items %}
+  <h2>{% trans "Forms in your care" %} - {{ forms.title }}</h2>
+  {% if forms.data %}
+  <table id="listing" class="main">
+    <thead>
+      <tr>
+          <th><span>{% trans "Form" %}</span></th>
+          <th><span>{% trans "Reference" %}</span></th>
+          <th><span>{% trans "Created" %}</span></th>
+          <th><span>{% trans "Last Modified" %}</span></th>
+          <th><span>{% trans "Status" %}</span></th>
+      </tr>
+    </thead>
+    <tbody>
+    {% for data in forms.data|dictsortreversed:"form_receipt_datetime" %}
+    <tr>
+      <td>{{ data.name }} {% if data.form_digest %}<br><small>{{ data.form_digest }}</small>{% endif %}</td>
+      <td><a href="{{ data.form_url_backoffice }}">{{ data.form_number }}</a></td>
+      <td>{{ data.datetime|strptime:"%Y-%m-%d %H:%M:%S" }}</td>
+      <td>{{ data.last_update_time|strptime:"%Y-%m-%d %H:%M:%S" }}</td>
+      <td>{{ data.status }}</td>
+    </tr>
+    {% endfor %}
+    </tbody>
+  </table>
+  {% endif %}
+  <p><a class="pk-button" href="{{ forms.url }}backoffice/management/">{% trans "See all forms" %}</a></p>
+{% endfor %}
+{% endblock %}
diff --git a/tests/test_wcs.py b/tests/test_wcs.py
index 4f03bf9..e0ee1a6 100644
--- a/tests/test_wcs.py
+++ b/tests/test_wcs.py
@@ -20,11 +20,13 @@ from django.test import override_settings
 from django.test.client import RequestFactory
 from django.utils.six.moves.urllib import parse as urlparse
 
+import mock
+
 from combo.data.models import Page
 from combo.apps.search.engines import engines
 from combo.apps.wcs.models import (WcsFormCell, WcsCurrentFormsCell,
         WcsFormsOfCategoryCell, WcsCurrentDraftsCell, WcsCategoryCell,
-        TrackingCodeInputCell, BackofficeSubmissionCell)
+        TrackingCodeInputCell, BackofficeSubmissionCell, WcsCareFormsCell)
 
 from combo.utils import NothingInCacheException
 
@@ -464,6 +466,95 @@ def test_current_forms_unknown_name_id(caplog, context):
     assert 'http://127.0.0.1:8999/' not in result
     assert len(caplog.records) == 0
 
+
+@wcs_present
+def test_care_forms_cell_setup():
+    cell = WcsCareFormsCell()
+    form_class = cell.get_default_form_class()
+    form = form_class()
+    assert form.fields['wcs_site'].widget.choices == [
+            ('', 'All'), (u'default', u'test'), (u'other', u'test2')]
+    assert cell.get_additional_label() == 'All Sites'
+    cell.wcs_site = 'default'
+    assert cell.get_additional_label() == 'test'
+
+
+@wcs_present
+def test_care_forms_cell_render(context):
+    page = Page(title='xxx', slug='test_care_forms_cell_render', template_name='standard')
+    page.save()
+    cell = WcsCareFormsCell(page=page, placeholder='content', order=0)
+    cell.save()
+
+    context['request'].user = MockUser()
+
+    # query should fail as nothing is cached
+    cache.clear()
+    with pytest.raises(NothingInCacheException):
+        result = cell.render(context)
+
+    context['synchronous'] = True  # to get fresh content
+
+    with mock.patch('combo.apps.wcs.models.requests.get') as requests_get:
+        response1 = {'err': 0, 'data': [
+            {
+                'form_receipt_datetime': '2019-10-17T16:46:03',
+                'form_url_backoffice': 'http://127.0.0.1:8999/backoffice/management/foobar/1/',
+            },
+            {
+                'form_receipt_datetime': '2019-10-17T16:46:04',
+                'form_url_backoffice': 'http://127.0.0.1:8999/backoffice/management/foobar/2/',
+            },
+        ]}
+        response2 = {'err': 0, 'data': [
+            {
+                'form_receipt_datetime': '2019-10-17T16:46:05',
+                'form_url_backoffice': 'http://127.0.0.2:8999/backoffice/management/foobar/42/',
+            },
+        ]}
+        mock_json = mock.Mock(status_code=200)
+        mock_json.json.side_effect = [response1, response2]
+        requests_get.return_value = mock_json
+
+        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' in result
+    assert '"http://127.0.0.1:8999/backoffice/management/"' in result
+    assert 'http://127.0.0.2:8999/backoffice/management/foobar/42' in result
+    assert '"http://127.0.0.2:8999/backoffice/management/"' in result
+
+    data = cell.get_data(context)
+    assert 'default' in data
+    assert 'other' in data
+
+
+@wcs_present
+def test_care_forms_cell_render_single_site(context):
+    page = Page(title='xxx', slug='test_care_forms_cell_render', template_name='standard')
+    page.save()
+    cell = WcsCareFormsCell(page=page, placeholder='content', order=0)
+    cell.wcs_site = 'default'
+    cell.save()
+
+    context['request'].user = MockUser()
+
+    # query should fail as nothing is cached
+    cache.clear()
+    with pytest.raises(NothingInCacheException):
+        result = cell.render(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
+
+    data = cell.get_data(context)
+    assert 'default' in data
+    assert 'other' not in data
+
+
 @wcs_present
 def test_forms_of_category_cell_setup():
     cell = WcsFormsOfCategoryCell()
-- 
2.20.1

