From cd614671ef9a063d16eb8670c252b8f8065ac155 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Fri, 15 Oct 2021 09:18:17 +0200
Subject: [PATCH] fields: fix live prefill for date fields (#52064)

---
 tests/form_pages/test_live.py        | 65 ++++++++++++++++++++++++++++
 wcs/forms/common.py                  |  7 +++
 wcs/qommon/static/js/qommon.forms.js |  2 +-
 3 files changed, 73 insertions(+), 1 deletion(-)

diff --git a/tests/form_pages/test_live.py b/tests/form_pages/test_live.py
index 774212ea..9e7d2f0e 100644
--- a/tests/form_pages/test_live.py
+++ b/tests/form_pages/test_live.py
@@ -1,3 +1,4 @@
+import datetime
 import io
 import json
 from unittest import mock
@@ -799,6 +800,70 @@ def test_field_live_string_prefill(pub, http_requests):
     live_resp = app.post('/foo/live?modified_field_id=user', params=resp.form.submit_fields(), status=403)
 
 
+def test_field_live_date_prefill(pub, http_requests):
+    pub.cfg['language'] = {'language': 'fr'}
+    pub.write_cfg()
+    CardDef.wipe()
+    carddef = CardDef()
+    carddef.name = 'foo'
+    carddef.digest_templates = {'default': '{{ form_var_foo }}'}
+    carddef.fields = [
+        fields.StringField(id='1', type='string', label='string', varname='foo'),
+        fields.DateField(
+            type='date',
+            id='2',
+            varname='date',
+        ),
+    ]
+    carddef.store()
+    carddef.data_class().wipe()
+    carddata1 = carddef.data_class()()
+    carddata1.data = {
+        '1': 'bar',
+        '2': datetime.date(2021, 10, 1).timetuple(),
+    }
+    carddata1.just_created()
+    carddata1.store()
+    carddata2 = carddef.data_class()()
+    carddata2.data = {
+        '1': 'baz',
+        '2': datetime.date(2021, 10, 30).timetuple(),
+    }
+    carddata2.just_created()
+    carddata2.store()
+    FormDef.wipe()
+    formdef = FormDef()
+    formdef.name = 'Foo'
+    formdef.fields = [
+        fields.ItemField(
+            type='item', id='1', label='foo', varname='foo', data_source={'type': 'carddef:foo'}
+        ),
+        fields.DateField(
+            type='date',
+            id='2',
+            label='date',
+            varname='date',
+            prefill={'type': 'string', 'value': '{{ form_var_foo_live_var_date }}'},
+        ),
+    ]
+    formdef.store()
+    formdef.data_class().wipe()
+
+    app = get_app(pub)
+    resp = app.get('/foo/')
+    assert resp.html.find('div', {'data-field-id': '1'}).attrs['data-live-source'] == 'true'
+    assert resp.pyquery('#var_date.widget-prefilled')  # second field is marked as prefilled
+    assert resp.form['f2'].value == ''
+    resp.form['f1'] = str(carddata1.id)
+    live_resp = app.post('/foo/live?modified_field_id=1&prefilled_2=on', params=resp.form.submit_fields())
+    assert live_resp.json['result']['2'] == {'visible': True, 'content': '2021-10-01'}
+
+    resp.form['f2'] = '2021-10-30'  # manually changed -> widget-prefilled class will be removed
+    resp.form['f1'] = str(carddata2.id)
+    live_resp = app.post('/foo/live?modified_field_id=1', params=resp.form.submit_fields())
+    assert live_resp.json['result']['2'] == {'visible': True}
+
+
 def test_field_live_block_string_prefill(pub, http_requests):
     FormDef.wipe()
     BlockDef.wipe()
diff --git a/wcs/forms/common.py b/wcs/forms/common.py
index 6a98af6c..e9061e06 100644
--- a/wcs/forms/common.py
+++ b/wcs/forms/common.py
@@ -798,6 +798,13 @@ class FormStatusPage(Directory, FormTemplateMixin):
                 update_prefill = bool('prefilled_%s' % field.id in get_request().form)
                 if update_prefill:
                     value = field.get_prefill_value()[0]
+                    if field.key == 'date' and value:
+                        try:
+                            value = field.convert_value_from_anything(value)
+                            # convert date to Y-m-d as expected by the <input type=date> field
+                            value = field.get_json_value(value)
+                        except ValueError:
+                            pass
                     entry['content'] = value
             elif field.prefill and field.prefill.get('type') == 'user':
                 update_prefill = bool(get_request().form.get('modified_field_id') == 'user')
diff --git a/wcs/qommon/static/js/qommon.forms.js b/wcs/qommon/static/js/qommon.forms.js
index e03bf9f0..502d0a27 100644
--- a/wcs/qommon/static/js/qommon.forms.js
+++ b/wcs/qommon/static/js/qommon.forms.js
@@ -479,7 +479,7 @@ $(function() {
               } else {
                 // replace text input value
                 if ($(widget).is('.widget-prefilled') || $(widget).is('.widget-readonly') || data.modified_field == 'user') {
-                  $(widget).find('input[type=text], input[type=tel], input[type=numeric], input[type=email], textarea').val(value.content);
+                  $(widget).find('input[type=text], input[type=tel], input[type=numeric], input[type=email], input[type=date], textarea').val(value.content);
                 }
               }
             });
-- 
2.33.0

