From 2bcad483e6f983d30c2ebcb4e05853ee43427717 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Thu, 5 Aug 2021 16:39:22 +0200
Subject: [PATCH] api: use custom digest for carddata view if defined (#55173)

---
 tests/api/test_carddef.py    | 52 ++++++++++++++++++++++++++++++++++++
 wcs/backoffice/management.py | 15 ++++++++---
 wcs/carddata.py              |  4 +--
 wcs/formdata.py              | 11 ++++----
 4 files changed, 71 insertions(+), 11 deletions(-)

diff --git a/tests/api/test_carddef.py b/tests/api/test_carddef.py
index 7dbad911..a7636a07 100644
--- a/tests/api/test_carddef.py
+++ b/tests/api/test_carddef.py
@@ -91,6 +91,7 @@ def test_cards(pub, local_user):
     formdata.data = {'0': 'blah'}
     formdata.just_created()
     formdata.store()
+    assert formdata.digests == {'default': 'bla blah xxx'}
 
     custom_view = pub.custom_view_class()
     custom_view.title = 'shared carddef custom view'
@@ -156,6 +157,57 @@ def test_cards(pub, local_user):
     assert resp.json['data'][0]['digest'] == formdata.digests['default']
     assert resp.json['data'][0]['text'] == formdata.digests['default']
 
+    resp = get_app(pub).get(
+        sign_uri(
+            '/api/cards/test/list/datasource-carddef-custom-view?NameID=%s' % local_user.name_identifiers[0]
+        )
+    )
+    assert len(resp.json['data']) == 1
+    assert resp.json['data'][0]['display_id'] == formdata.get_display_id()
+    assert resp.json['data'][0]['display_name'] == formdata.get_display_name()
+    assert resp.json['data'][0]['digest'] == formdata.digests['default']
+    assert resp.json['data'][0]['text'] == formdata.digests['default']
+    resp = get_app(pub).get(
+        sign_uri(
+            '/api/cards/test/list/datasource-carddef-custom-view?NameID=%s&full=on'
+            % local_user.name_identifiers[0]
+        )
+    )
+    assert resp.json['data'][0]['fields']['foo'] == 'blah'
+    assert resp.json['data'][0]['digest'] == formdata.digests['default']
+    assert resp.json['data'][0]['text'] == formdata.digests['default']
+
+    # with custom digest template
+    carddef.digest_templates = {
+        'default': 'bla {{ form_var_foo }} xxx',
+        'custom-view:datasource-carddef-custom-view': '{{ form_var_foo }}',
+    }
+    carddef.store()
+    formdata.store()
+    assert formdata.digests == {
+        'default': 'bla blah xxx',
+        'custom-view:datasource-carddef-custom-view': 'blah',
+    }
+    resp = get_app(pub).get(
+        sign_uri(
+            '/api/cards/test/list/datasource-carddef-custom-view?NameID=%s' % local_user.name_identifiers[0]
+        )
+    )
+    assert len(resp.json['data']) == 1
+    assert resp.json['data'][0]['display_id'] == formdata.get_display_id()
+    assert resp.json['data'][0]['display_name'] == formdata.get_display_name()
+    assert resp.json['data'][0]['digest'] == formdata.digests['custom-view:datasource-carddef-custom-view']
+    assert resp.json['data'][0]['text'] == formdata.digests['custom-view:datasource-carddef-custom-view']
+    resp = get_app(pub).get(
+        sign_uri(
+            '/api/cards/test/list/datasource-carddef-custom-view?NameID=%s&full=on'
+            % local_user.name_identifiers[0]
+        )
+    )
+    assert resp.json['data'][0]['fields']['foo'] == 'blah'
+    assert resp.json['data'][0]['digest'] == formdata.digests['custom-view:datasource-carddef-custom-view']
+    assert resp.json['data'][0]['text'] == formdata.digests['custom-view:datasource-carddef-custom-view']
+
     # get single carddata (as signed request without any user specified, so
     # no check for permissions)
     resp = get_app(pub).get(sign_uri('/api/cards/test/%s/' % formdata.id))
diff --git a/wcs/backoffice/management.py b/wcs/backoffice/management.py
index 3ed37132..71f7227d 100644
--- a/wcs/backoffice/management.py
+++ b/wcs/backoffice/management.py
@@ -2386,12 +2386,19 @@ class FormPage(Directory):
         )[0]
         if get_publisher().is_using_postgresql():
             self.formdef.data_class().load_all_evolutions(items)
+        digest_key = 'default'
+        if self.view and isinstance(self.formdef, CardDef):
+            view_digest_key = 'custom-view:%s' % self.view.get_url_slug()
+            if view_digest_key in (self.formdef.digest_templates or {}):
+                digest_key = view_digest_key
         if get_request().form.get('full') == 'on':
             output = []
             for filled in items:
-                data = filled.get_json_export_dict(include_files=False, anonymise=anonymise, user=user)
+                data = filled.get_json_export_dict(
+                    include_files=False, anonymise=anonymise, user=user, digest_key=digest_key
+                )
                 data.pop('digests')
-                data['digest'] = filled.default_digest
+                data['digest'] = (filled.digests or {}).get(digest_key)
                 output.append(data)
         else:
             output = [
@@ -2399,8 +2406,8 @@ class FormPage(Directory):
                     'id': filled.id,
                     'display_id': filled.get_display_id(),
                     'display_name': filled.get_display_name(),
-                    'digest': filled.default_digest,
-                    'text': filled.get_display_label(),
+                    'digest': (filled.digests or {}).get(digest_key),
+                    'text': filled.get_display_label(digest_key=digest_key),
                     'url': filled.get_url(),
                     'receipt_time': datetime.datetime(*filled.receipt_time[:6]),
                     'last_update_time': datetime.datetime(*filled.last_update_time[:6]),
diff --git a/wcs/carddata.py b/wcs/carddata.py
index 2d6067ef..71049209 100644
--- a/wcs/carddata.py
+++ b/wcs/carddata.py
@@ -45,8 +45,8 @@ class CardData(FormData):
                 item[field.varname] = value
         return item
 
-    def get_display_label(self):
-        return self.default_digest or self.get_display_name()
+    def get_display_label(self, digest_key='default'):
+        return (self.digests or {}).get(digest_key) or self.get_display_name()
 
     def get_author_qualification(self):
         return None
diff --git a/wcs/formdata.py b/wcs/formdata.py
index 74cedf4e..be627728 100644
--- a/wcs/formdata.py
+++ b/wcs/formdata.py
@@ -1129,9 +1129,10 @@ class FormData(StorableObject):
     def default_digest(self):
         return (self.digests or {}).get('default')
 
-    def get_display_label(self):
-        if self.default_digest:
-            return '%s (%s)' % (self.get_display_name(), self.default_digest)
+    def get_display_label(self, digest_key='default'):
+        digest = (self.digests or {}).get(digest_key)
+        if digest:
+            return '%s (%s)' % (self.get_display_name(), digest)
         return self.get_display_name()
 
     def get_auto_geoloc(self):
@@ -1182,13 +1183,13 @@ class FormData(StorableObject):
             self.data, fields, formdata=self, include_files=include_files, anonymise=anonymise
         )
 
-    def get_json_export_dict(self, include_files=True, anonymise=False, user=None):
+    def get_json_export_dict(self, include_files=True, anonymise=False, user=None, digest_key='default'):
         data = {}
         data['id'] = str(self.id)
         data['digests'] = self.digests
         data['display_id'] = self.get_display_id()
         data['display_name'] = self.get_display_name()
-        data['text'] = self.get_display_label()
+        data['text'] = self.get_display_label(digest_key=digest_key)
         data['receipt_time'] = datetime.datetime(*self.receipt_time[:6])
         data['last_update_time'] = datetime.datetime(*self.last_update_time[:6])
         data['criticality_level'] = self.criticality_level
-- 
2.30.2

