From e3a1b08d72b98989c01b53925494ce805dc233fa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= <fpeters@entrouvert.com>
Date: Tue, 1 Jan 2019 14:08:54 +0100
Subject: [PATCH 2/3] wcs: register search engines for formdata of wcs sites
 (#26260)

---
 combo/apps/search/urls.py  |  2 +-
 combo/apps/wcs/__init__.py | 22 ++++++++++++++-
 tests/test_search.py       | 55 ++++++++++++++++++++++----------------
 tests/test_wcs.py          |  7 +++++
 4 files changed, 61 insertions(+), 25 deletions(-)

diff --git a/combo/apps/search/urls.py b/combo/apps/search/urls.py
index 991c3e51..33f9c4a4 100644
--- a/combo/apps/search/urls.py
+++ b/combo/apps/search/urls.py
@@ -19,6 +19,6 @@ from django.conf.urls import url
 from .models import SearchCell
 
 urlpatterns = [
-    url(r'^ajax/search/(?P<cell_pk>\w+)/(?P<service_slug>[\w-]+)/$', SearchCell.ajax_results_view,
+    url(r'^ajax/search/(?P<cell_pk>\w+)/(?P<service_slug>[\w:-]+)/$', SearchCell.ajax_results_view,
         name='combo-search-ajax-results'),
 ]
diff --git a/combo/apps/wcs/__init__.py b/combo/apps/wcs/__init__.py
index fef8598d..60ca80ad 100644
--- a/combo/apps/wcs/__init__.py
+++ b/combo/apps/wcs/__init__.py
@@ -14,6 +14,8 @@
 # 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 hashlib
+
 import django.apps
 from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext_lazy as _
@@ -28,12 +30,30 @@ class AppConfig(django.apps.AppConfig):
         engines.register(self.get_search_engines)
 
     def get_search_engines(self):
-        return {
+        from .utils import get_wcs_services
+        services = get_wcs_services()
+        if not services:
+            return
+
+        engines = {
             'tracking-code': {
                 'url': reverse('wcs-tracking-code-search') + '?q=%(q)s',
                 'label': _('Tracking Code'),
             }
         }
+        for key, service in services.items():
+            label = _('Forms')
+            if len(services.keys()) > 1:
+                label = _('Forms (%s)') % service['title']
+            engines['formdata:%s' % hashlib.md5(key).hexdigest()[:8]] = {
+                'url': service['url'] + 'api/forms/?NameID={{user_nameid}}&status=all&ignore-roles=on&q=%(q)s',
+                'label': label,
+                'signature': True,
+                'hit_url_template': '{% if readable %}{{ form_url_backoffice }}{% endif %}',
+                'hit_label_template': '{{ title }}',
+                'hit_description_template': '{{ form_digest|default:"" }}',
+            }
+        return engines
 
     def get_before_urls(self):
         from . import urls
diff --git a/tests/test_search.py b/tests/test_search.py
index 633b7939..d65d9788 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -12,6 +12,7 @@ from django.core.urlresolvers import reverse
 
 from haystack.exceptions import SkipDocument
 
+from combo.apps.search.engines import engines
 from combo.apps.search.models import SearchCell
 from combo.data.models import Page, JsonCell, TextCell, MenuCell, LinkCell
 from combo.data.search_indexes import PageIndex
@@ -338,29 +339,37 @@ def test_manager_search_cell(app, admin_user):
     assert len(cells) == 1
     assert isinstance(cells[0], SearchCell)
 
-    resp = app.get('/manage/pages/%s/' % page.id)
-    assert ('data-cell-reference="%s"' % cells[0].get_reference()) in resp.text
-    assert len(resp.form['c%s-_search_services' % cells[0].get_reference()].options) == 2
-
-    with SearchServices(SEARCH_SERVICES):
+    with override_settings(KNOWN_SERVICES={}):
         resp = app.get('/manage/pages/%s/' % page.id)
-        assert len(resp.form['c%s-_search_services' % cells[0].get_reference()].options) == 5
-        # simulate reordering of options
-        resp.form['c%s-_search_services' % cells[0].get_reference()].options = [
-                (u'search_tmpl', False, u'Search with template'),
-                (u'search_alternate_key', False, u'Search with alternate key'),
-                (u'_text', False, u'Page Contents'),
-                (u'search1', False, u'Search 1')]
-        resp.form['c%s-_search_services' % cells[0].get_reference()].value = ['search_tmpl', '_text']
-        resp = resp.form.submit()
-        assert resp.status_int == 302
-
-        # check selected engines are selected and the first items of the list
+        assert ('data-cell-reference="%s"' % cells[0].get_reference()) in resp.text
+        assert len(resp.form['c%s-_search_services' % cells[0].get_reference()].options) == 1
+
+        with SearchServices(SEARCH_SERVICES):
+            resp = app.get('/manage/pages/%s/' % page.id)
+            assert len(resp.form['c%s-_search_services' % cells[0].get_reference()].options) == 4
+            # simulate reordering of options
+            resp.form['c%s-_search_services' % cells[0].get_reference()].options = [
+                    (u'search_tmpl', False, u'Search with template'),
+                    (u'search_alternate_key', False, u'Search with alternate key'),
+                    (u'_text', False, u'Page Contents'),
+                    (u'search1', False, u'Search 1')]
+            resp.form['c%s-_search_services' % cells[0].get_reference()].value = ['search_tmpl', '_text']
+            resp = resp.form.submit()
+            assert resp.status_int == 302
+
+            # check selected engines are selected and the first items of the list
+            resp = app.get('/manage/pages/%s/' % page.id)
+            assert set(resp.form['c%s-_search_services' % cells[0].get_reference()].value) == set(['search_tmpl', '_text'])
+            assert resp.form['c%s-_search_services' % cells[0].get_reference()].options[0][0] == 'search_tmpl'
+            assert resp.form['c%s-_search_services' % cells[0].get_reference()].options[1][0] == '_text'
+
+        # check there's no crash if search engines are removed from config
         resp = app.get('/manage/pages/%s/' % page.id)
-        assert set(resp.form['c%s-_search_services' % cells[0].get_reference()].value) == set(['search_tmpl', '_text'])
-        assert resp.form['c%s-_search_services' % cells[0].get_reference()].options[0][0] == 'search_tmpl'
-        assert resp.form['c%s-_search_services' % cells[0].get_reference()].options[1][0] == '_text'
+        assert resp.form['c%s-_search_services' % cells[0].get_reference()].value == ['_text']
 
-    # check there's no crash if search engines are removed from config
-    resp = app.get('/manage/pages/%s/' % page.id)
-    assert resp.form['c%s-_search_services' % cells[0].get_reference()].value == ['_text']
+
+def test_wcs_search_engines(app):
+    with override_settings(KNOWN_SERVICES={}):
+        search_engines = engines.get_engines()
+        assert 'tracking-code' not in search_engines.keys()
+        assert len([x for x in search_engines.keys() if x.startswith('formdata:')]) == 0
diff --git a/tests/test_wcs.py b/tests/test_wcs.py
index 3fe39c2d..449fe231 100644
--- a/tests/test_wcs.py
+++ b/tests/test_wcs.py
@@ -19,6 +19,7 @@ from django.test.client import RequestFactory
 from django.utils.six.moves.urllib import parse as urlparse
 
 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)
@@ -675,6 +676,12 @@ def test_tracking_code_search(app):
     assert len(app.get('/api/search/tracking-code/?q=CNPHNTFB').json.get('data')) == 1
     assert len(app.get('/api/search/tracking-code/?q=BBCCDDFFG').json.get('data')) == 0
 
+@wcsctl_present
+def test_wcs_search_engines(app):
+    search_engines = engines.get_engines()
+    assert 'tracking-code' in search_engines.keys()
+    assert len([x for x in search_engines.keys() if x.startswith('formdata:')]) == 2
+
 @wcsctl_present
 def test_backoffice_submission_cell_render(context):
     page = Page(title='xxx', slug='test_backoffice_submission_cell_render', template_name='standard')
-- 
2.20.1

