From c7f3a2dcfe2c6f6633d25c8938962dce0e899180 Mon Sep 17 00:00:00 2001 From: Quentin Mondot Date: Mon, 9 Nov 2026 16:47:05 +0100 Subject: [PATCH] [IMP] docuseal_signing: pick the submitter role from the Docuseal roles The submitter role was a free text field. It is now a dropdown listing only the submitter roles of the Docuseal template (docuseal.template.role), fetched with the Docuseal UUID of each role. - The "Fetch from Docuseal" button, now above the role, syncs the roles (matched by UUID then name, in the Docuseal order, the first one selected by default) and the fields of the selected role only, keeping the existing mappings. - Changing the role fetches the fields of the new role from Docuseal with an empty mapping, and warns that saving loses the current one. - Signature requests only send the fields of the submitter role. - Docuseal API errors and a missing token raise a clear UserError. - Keep the Docuseal field name of new mapping lines on save (force_save on the read-only column). Assisted-By: Claude Opus 5.5 --- docuseal_signing/README.md | 15 +- docuseal_signing/i18n/fr.po | 98 ++++++++- docuseal_signing/models/__init__.py | 1 + docuseal_signing/models/docuseal_template.py | 137 +++++++++++-- .../models/docuseal_template_role.py | 22 +++ docuseal_signing/security/ir.model.access.csv | 1 + docuseal_signing/tests/test_fetch_fields.py | 187 ++++++++++++++---- docuseal_signing/tests/test_submissions.py | 5 +- .../views/docuseal_template_views.xml | 23 ++- 9 files changed, 419 insertions(+), 70 deletions(-) create mode 100644 docuseal_signing/models/docuseal_template_role.py diff --git a/docuseal_signing/README.md b/docuseal_signing/README.md index 95c5b66..bcb8195 100644 --- a/docuseal_signing/README.md +++ b/docuseal_signing/README.md @@ -8,11 +8,16 @@ signatures from partners in a few clicks. ## Features - **Template registry** (`docuseal.template`): reference Docuseal - templates by their ID and submitter role, and fetch their field list - from the Docuseal API with a single click. + templates by their ID; the *Fetch from Docuseal* button loads their + submitter roles and fields from the Docuseal API. The submitter role + is picked from a dropdown listing only the roles of the template + (`docuseal.template.role`); the first one is selected by default. - **Field mapping** (`docuseal.template.field`): map each Docuseal - field to a `res.partner` field. Fields are kept in the order returned - by the Docuseal API (reorderable with drag & drop). Values are + field of the selected role to a `res.partner` field. Fetching again + keeps the existing mappings; changing the role loads the fields of + the new role from Docuseal with an empty mapping. Fields are kept in + the order returned by the Docuseal API (reorderable with drag & + drop). Values are pre-filled at submission time and locked so the signer cannot change them (empty mappings stay editable by the signer). - **One-click signature request**: generate a server action bound to @@ -56,7 +61,7 @@ template._create_draft_submissions(partners) Behavior of both calls: - One Docuseal submission is created per partner, using the template's - Docuseal `template_id` and `submitter_role`; the partner's `name` + Docuseal `template_id` and `submitter_role_id`; the partner's `name` and `email` identify the submitter. - Each mapped Docuseal field is pre-filled from the partner field set in `docuseal.template.field`. Non-empty values are locked diff --git a/docuseal_signing/i18n/fr.po b/docuseal_signing/i18n/fr.po index 37696ba..436fc80 100644 --- a/docuseal_signing/i18n/fr.po +++ b/docuseal_signing/i18n/fr.po @@ -70,12 +70,14 @@ msgstr "Créer l'action contextuelle" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__create_uid #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__create_uid +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__create_uid msgid "Created by" msgstr "Créé par" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__create_date #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__create_date +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__create_date msgid "Created on" msgstr "Créé le" @@ -103,6 +105,7 @@ msgstr "" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__display_name #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__display_name +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__display_name msgid "Display Name" msgstr "Nom affiché" @@ -150,8 +153,8 @@ msgstr "Templates Docuseal" #. module: docuseal_signing #: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form -msgid "Fetch template fields" -msgstr "Rapatrier les champs du template" +msgid "Fetch from Docuseal" +msgstr "Rapatrier depuis Docuseal" #. module: docuseal_signing #: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form @@ -166,18 +169,21 @@ msgstr "Champs" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__id #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__id +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__id msgid "ID" msgstr "ID" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__write_uid #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__write_uid +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__write_uid msgid "Last Updated by" msgstr "Dernière mise à jour par" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__write_date #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__write_date +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__write_date msgid "Last Updated on" msgstr "Dernière mise à jour le" @@ -191,13 +197,9 @@ msgstr "Gérer les templates Docuseal" msgid "Name" msgstr "Nom" -#. module: docuseal_signing -#: model:ir.model.fields,help:docuseal_signing.field_docuseal_template__submitter_role -msgid "Name of the submitter role you have set up in Docuseal." -msgstr "Nom du rôle de signataire défini dans Docuseal." - #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__sequence +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__sequence msgid "Sequence" msgstr "Séquence" @@ -209,17 +211,19 @@ msgstr "Action serveur" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__smart_search #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__smart_search +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__smart_search #: model:ir.model.fields,field_description:docuseal_signing.field_res_config_settings__smart_search msgid "Smart Search" msgstr "Recherche intelligente" #. module: docuseal_signing -#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__submitter_role +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__submitter_role_id msgid "Submitter role" msgstr "Rôle du signataire" #. module: docuseal_signing #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__template_id +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__template_id msgid "Template" msgstr "Template" @@ -241,3 +245,81 @@ msgstr "" #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__partner_field_id msgid "res.partner field" msgstr "Champ res.partner" + +#. module: docuseal_signing +#: model:ir.model,name:docuseal_signing.model_docuseal_template_role +msgid "Docuseal Template Submitter Role" +msgstr "Rôle de signataire du template Docuseal" + +#. module: docuseal_signing +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__uuid +msgid "Docuseal UUID" +msgstr "UUID Docuseal" + +#. module: docuseal_signing +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__name +msgid "Role" +msgstr "Rôle" + +#. module: docuseal_signing +#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template__role_ids +msgid "Submitter roles" +msgstr "Rôles des signataires" + +#. module: docuseal_signing +#: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form +msgid "Fetch from Docuseal to list the roles" +msgstr "Rapatrier depuis Docuseal pour lister les rôles" + +#. module: docuseal_signing +#. odoo-python +#: code:addons/docuseal_signing/models/docuseal_template.py:0 +msgid "Set the Docuseal API token in the General Settings first." +msgstr "Renseignez d'abord le token API Docuseal dans les Paramètres généraux." + +#. module: docuseal_signing +#. odoo-python +#: code:addons/docuseal_signing/models/docuseal_template.py:0 +msgid "Docuseal returned an error for template %(template)s: %(code)s %(reason)s" +msgstr "Docuseal a renvoyé une erreur pour le template %(template)s : %(code)s %(reason)s" + +#. module: docuseal_signing +#. odoo-python +#: code:addons/docuseal_signing/models/docuseal_template.py:0 +msgid "Docuseal could not be reached at %(url)s: %(error)s" +msgstr "Docuseal est injoignable à l'adresse %(url)s : %(error)s" + +#. module: docuseal_signing +#: model:ir.model.fields,help:docuseal_signing.field_docuseal_template__submitter_role_id +msgid "" +"Submitter role of the Docuseal template that the contact signs as. The " +"available roles are fetched from Docuseal." +msgstr "" +"Rôle du template Docuseal sous lequel le contact signe. Les rôles " +"disponibles sont rapatriés depuis Docuseal." + +#. module: docuseal_signing +#: model:ir.model.fields,help:docuseal_signing.field_docuseal_template_role__uuid +msgid "" +"UUID of the submitter in the Docuseal template, used to find the template " +"fields of this role." +msgstr "" +"UUID du signataire dans le template Docuseal, utilisé pour retrouver les " +"champs du template propres à ce rôle." + +#. module: docuseal_signing +#. odoo-python +#: code:addons/docuseal_signing/models/docuseal_template.py:0 +msgid "Field mapping reset" +msgstr "Correspondance des champs réinitialisée" + +#. module: docuseal_signing +#. odoo-python +#: code:addons/docuseal_signing/models/docuseal_template.py:0 +msgid "" +"The fields of the new role are loaded with an empty mapping. If you save, " +"the current field mapping will be lost. Discard the changes to keep it." +msgstr "" +"Les champs du nouveau rôle sont chargés sans correspondance. Si vous " +"enregistrez, la correspondance actuelle des champs sera perdue. Ignorez tous " +"les changements pour la conserver." diff --git a/docuseal_signing/models/__init__.py b/docuseal_signing/models/__init__.py index 406be02..2b528ae 100644 --- a/docuseal_signing/models/__init__.py +++ b/docuseal_signing/models/__init__.py @@ -1,3 +1,4 @@ from . import docuseal_template from . import docuseal_template_field +from . import docuseal_template_role from . import res_config_settings diff --git a/docuseal_signing/models/docuseal_template.py b/docuseal_signing/models/docuseal_template.py index 2a5be7d..d4027e4 100644 --- a/docuseal_signing/models/docuseal_template.py +++ b/docuseal_signing/models/docuseal_template.py @@ -1,8 +1,10 @@ import json import logging +import urllib.error import urllib.request -from odoo import _, fields, models +from odoo import Command, _, api, fields, models +from odoo.exceptions import UserError _logger = logging.getLogger(__name__) @@ -17,9 +19,17 @@ class DocusealTemplate(models.Model): help="You can find the template id in the URL when you have selected the template in Docuseal.", required=True ) - submitter_role = fields.Char( + role_ids = fields.One2many( + comodel_name="docuseal.template.role", + inverse_name="template_id", + string="Submitter roles", + ) + submitter_role_id = fields.Many2one( + comodel_name="docuseal.template.role", string="Submitter role", - help="Name of the submitter role you have set up in Docuseal.", + domain="[('template_id', '=', id)]", + help="Submitter role of the Docuseal template that the contact " + "signs as. The available roles are fetched from Docuseal.", ) field_ids = fields.One2many( comodel_name="docuseal.template.field", @@ -33,33 +43,77 @@ class DocusealTemplate(models.Model): ondelete="set null", ) - def action_fetch_fields(self): + def _fetch_docuseal_template(self): + """Return the template definition from the Docuseal API.""" self.ensure_one() IrParam = self.env["ir.config_parameter"].sudo() api_token = IrParam.get_param("docuseal.api_token") api_url = IrParam.get_param( "docuseal.api_url", "https://sign.elabore.coop" ).rstrip("/") + if not api_token: + raise UserError( + _("Set the Docuseal API token in the General Settings first.") + ) url = f"{api_url}/api/templates/{self.template_id}" req = urllib.request.Request(url, headers={"X-Auth-Token": api_token}) - with urllib.request.urlopen(req, timeout=10) as resp: - data = json.loads(resp.read().decode()) + try: + with urllib.request.urlopen(req, timeout=10) as resp: + return json.loads(resp.read().decode()) + except urllib.error.HTTPError as err: + raise UserError( + _( + "Docuseal returned an error for template %(template)s: " + "%(code)s %(reason)s", + template=self.template_id, + code=err.code, + reason=err.reason, + ) + ) from err + except (urllib.error.URLError, TimeoutError) as err: + raise UserError( + _( + "Docuseal could not be reached at %(url)s: %(error)s", + url=api_url, + error=getattr(err, "reason", err), + ) + ) from err + + @staticmethod + def _role_field_names(data, role): + """Names of the Docuseal fields of ``role``, in the API order. + + Each Docuseal field belongs to a submitter (``submitter_uuid``); + fields without a submitter are kept for every role. + """ + names = [] + for docuseal_field in data.get("fields", []): + name = docuseal_field.get("name") + submitter_uuid = docuseal_field.get("submitter_uuid") + if not name or name in names: + continue + if submitter_uuid and role.uuid and submitter_uuid != role.uuid: + continue + names.append(name) + return names + + def action_fetch_fields(self): + self.ensure_one() + data = self._fetch_docuseal_template() if data.get("name") and not self.name: self.name = data["name"] - if data.get("submitters") and not self.submitter_role: - self.submitter_role = data["submitters"][0].get("name", "") + self._sync_roles(data.get("submitters", [])) - # Reconcile the field mapping with the Docuseal template instead of - # wiping it: existing mappings keep their res.partner field and the - # sequence follows the field order returned by the Docuseal API. + # Reconcile the field mapping of the selected role with the Docuseal + # template instead of wiping it: existing mappings keep their + # res.partner field and the sequence follows the field order + # returned by the Docuseal API. + docuseal_names = self._role_field_names(data, self.submitter_role_id) existing = { field.docuseal_field_name: field for field in self.field_ids } - docuseal_names = [ - f["name"] for f in data.get("fields", []) if f.get("name") - ] for index, name in enumerate(docuseal_names): field = existing.get(name) if field: @@ -74,6 +128,59 @@ class DocusealTemplate(models.Model): lambda field: field.docuseal_field_name not in docuseal_names ).unlink() + @api.onchange("submitter_role_id") + def _onchange_submitter_role_id(self): + """Load the fields of the new role from Docuseal, without mapping.""" + if not self.submitter_role_id or not self.template_id: + return + data = self._fetch_docuseal_template() + names = self._role_field_names(data, self.submitter_role_id) + had_mapping = bool(self.field_ids.partner_field_id) + self.field_ids = [Command.clear()] + [ + Command.create({"docuseal_field_name": name, "sequence": index}) + for index, name in enumerate(names) + ] + if had_mapping: + return { + "warning": { + "title": _("Field mapping reset"), + "message": _( + "The fields of the new role are loaded with an empty " + "mapping. If you save, the current field mapping will " + "be lost. Discard the changes to keep it." + ), + } + } + + def _sync_roles(self, submitters): + """Reconcile the submitter roles with the Docuseal template. + + Existing roles are matched by Docuseal UUID, then by name, so the + selected role survives a re-fetch or a rename in Docuseal. Roles + removed from Docuseal are dropped and the order follows the Docuseal + API. The first role is selected when none is set anymore. + """ + self.ensure_one() + Role = self.env["docuseal.template.role"] + by_uuid = {role.uuid: role for role in self.role_ids if role.uuid} + by_name = {role.name: role for role in self.role_ids} + kept = Role + for submitter in submitters: + name = submitter.get("name") + if not name: + continue + uuid = submitter.get("uuid") or False + role = (uuid and by_uuid.get(uuid)) or by_name.get(name) or Role + vals = {"name": name, "uuid": uuid, "sequence": len(kept)} + if role and role not in kept: + role.write(vals) + else: + role = Role.create(dict(vals, template_id=self.id)) + kept |= role + (self.role_ids - kept).unlink() + if not self.submitter_role_id and kept: + self.submitter_role_id = kept[0] + def action_create_server_action(self): self.ensure_one() partner_model = self.env["ir.model"].search( @@ -165,7 +272,7 @@ class DocusealTemplate(models.Model): "send_email": send_email, "submitters": [{ "name": partner.name, - "role": self.submitter_role or "", + "role": self.submitter_role_id.name or "", "email": partner.email or "", "fields": submitter_fields, }], diff --git a/docuseal_signing/models/docuseal_template_role.py b/docuseal_signing/models/docuseal_template_role.py new file mode 100644 index 0000000..4059123 --- /dev/null +++ b/docuseal_signing/models/docuseal_template_role.py @@ -0,0 +1,22 @@ +from odoo import fields, models + + +class DocusealTemplateRole(models.Model): + _name = "docuseal.template.role" + _description = "Docuseal Template Submitter Role" + _order = "sequence, id" + + sequence = fields.Integer(default=10) + name = fields.Char(string="Role", required=True, readonly=True) + uuid = fields.Char( + string="Docuseal UUID", + readonly=True, + help="UUID of the submitter in the Docuseal template, used to find " + "the template fields of this role.", + ) + template_id = fields.Many2one( + comodel_name="docuseal.template", + string="Template", + required=True, + ondelete="cascade", + ) diff --git a/docuseal_signing/security/ir.model.access.csv b/docuseal_signing/security/ir.model.access.csv index a4d612c..5dea2ca 100644 --- a/docuseal_signing/security/ir.model.access.csv +++ b/docuseal_signing/security/ir.model.access.csv @@ -1,3 +1,4 @@ id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink access_docuseal_template_system,docuseal.template system,model_docuseal_template,base.group_system,1,1,1,1 access_docuseal_template_field_system,docuseal.template.field system,model_docuseal_template_field,base.group_system,1,1,1,1 +access_docuseal_template_role_system,docuseal.template.role system,model_docuseal_template_role,base.group_system,1,1,1,1 diff --git a/docuseal_signing/tests/test_fetch_fields.py b/docuseal_signing/tests/test_fetch_fields.py index 82e6f8d..4331b14 100644 --- a/docuseal_signing/tests/test_fetch_fields.py +++ b/docuseal_signing/tests/test_fetch_fields.py @@ -1,10 +1,18 @@ -from odoo.tests import TransactionCase +import urllib.error +from unittest import mock + +from odoo.exceptions import UserError +from odoo.tests import Form, TransactionCase + +from odoo.addons.docuseal_signing.models import ( + docuseal_template as docuseal_template_module, +) from .common import DocusealApiMockMixin class TestFetchFields(DocusealApiMockMixin, TransactionCase): - """Reconciliation of the field mapping on action_fetch_fields.""" + """Roles and field mapping fetched from the Docuseal API.""" @classmethod def setUpClass(cls): @@ -15,7 +23,11 @@ class TestFetchFields(DocusealApiMockMixin, TransactionCase): cls.template = cls.env["docuseal.template"].create({ "name": "Old name", "template_id": 999, - "submitter_role": "Signer", + }) + cls.template.submitter_role_id = cls.env["docuseal.template.role"].create({ + "template_id": cls.template.id, + "name": "Signer", + "uuid": "uuid-signer", }) cls.env["docuseal.template.field"].create({ "template_id": cls.template.id, @@ -27,78 +39,187 @@ class TestFetchFields(DocusealApiMockMixin, TransactionCase): "docuseal_field_name": "obsolete", }) + def setUp(self): + super().setUp() + self._set_api_config() + + def _field_names(self): + self.template.invalidate_recordset(["field_ids", "role_ids"]) + return self.template.field_ids.mapped("docuseal_field_name") + def test_fetch_fields_reconciles_mapping(self): """Existing mappings keep their partner field; removed Docuseal fields are dropped and new ones are added, in the order returned by the Docuseal API.""" payload = { "name": "Contract", - "submitters": [{"name": "Signer"}], + "submitters": [{"name": "Signer", "uuid": "uuid-signer"}], "fields": [{"name": "phone"}, {"name": "extra"}, {"name": ""}], } with self._mock_api(payload): self.template.action_fetch_fields() - names = { - field.docuseal_field_name for field in self.template.field_ids - } - self.assertEqual(names, {"phone", "extra"}) - - # The mapping order follows the Docuseal API field order. self.assertEqual( - self.template.field_ids.mapped("docuseal_field_name"), - ["phone", "extra"], + self.requests[0]["url"], "https://sign.example.com/api/templates/999" ) - + self.assertEqual(self._field_names(), ["phone", "extra"]) phone_mapping = self.template.field_ids.filtered( lambda field: field.docuseal_field_name == "phone" ) self.assertEqual(phone_mapping.partner_field_id, self.phone_field) - # Name and submitter role are only filled when still empty. + # Name is only filled when still empty; the selected role is kept. self.assertEqual(self.template.name, "Old name") - self.assertEqual(self.template.submitter_role, "Signer") + self.assertEqual(self.template.submitter_role_id.name, "Signer") def test_fetch_fields_fills_empty_name_and_role(self): - """Name and submitter role are set from the API when missing.""" + """Name and submitter role are set from the API when missing; + roles removed from Docuseal are dropped.""" self.template.name = False - self.template.submitter_role = False + self.template.submitter_role_id = False payload = { "name": "Contract", - "submitters": [{"name": "Counterparty"}], + "submitters": [{"name": "Counterparty", "uuid": "uuid-cp"}], "fields": [], } with self._mock_api(payload): self.template.action_fetch_fields() self.assertEqual(self.template.name, "Contract") - self.assertEqual(self.template.submitter_role, "Counterparty") - self.assertFalse(self.template.field_ids) + self.assertEqual(self.template.submitter_role_id.name, "Counterparty") + self.assertEqual(self.template.role_ids.mapped("name"), ["Counterparty"]) + self.assertFalse(self._field_names()) + + def test_fetch_fields_keeps_only_selected_role_fields(self): + """Only the fields of the selected role are mapped.""" + payload = { + "submitters": [ + {"name": "Signer", "uuid": "uuid-signer"}, + {"name": "Witness", "uuid": "uuid-witness"}, + ], + "fields": [ + {"name": "phone", "submitter_uuid": "uuid-signer"}, + {"name": "witness_name", "submitter_uuid": "uuid-witness"}, + {"name": "city", "submitter_uuid": "uuid-signer"}, + ], + } + with self._mock_api(payload): + self.template.action_fetch_fields() + + self.assertEqual(self._field_names(), ["phone", "city"]) + self.assertEqual( + self.template.role_ids.mapped("name"), ["Signer", "Witness"] + ) + + def test_fetch_fields_syncs_roles(self): + """Roles follow the Docuseal order, are matched by UUID (a rename + keeps the selection) and the selection falls back to the first + role when the selected one is removed.""" + payload = { + "submitters": [ + {"name": "Witness", "uuid": "uuid-witness"}, + {"name": "Main signer", "uuid": "uuid-signer"}, + {"name": ""}, + ], + "fields": [], + } + with self._mock_api(payload): + self.template.action_fetch_fields() + self.template.invalidate_recordset(["role_ids"]) + self.assertEqual( + self.template.role_ids.mapped("name"), ["Witness", "Main signer"] + ) + self.assertEqual(self.template.submitter_role_id.uuid, "uuid-signer") + + # The selected role is removed from the Docuseal template. + payload["submitters"] = [ + {"name": "Witness", "uuid": "uuid-witness"}, + {"name": "Buyer", "uuid": "uuid-buyer"}, + ] + with self._mock_api(payload): + self.template.action_fetch_fields() + self.template.invalidate_recordset(["role_ids"]) + self.assertEqual( + self.template.role_ids.mapped("name"), ["Witness", "Buyer"] + ) + self.assertEqual(self.template.submitter_role_id.name, "Witness") + + def test_change_role_loads_its_fields_without_mapping(self): + """Changing the role in the form fetches the fields of that role + from Docuseal and clears the mapping.""" + witness = self.env["docuseal.template.role"].create({ + "template_id": self.template.id, + "name": "Witness", + "uuid": "uuid-witness", + }) + payload = { + "submitters": [ + {"name": "Signer", "uuid": "uuid-signer"}, + {"name": "Witness", "uuid": "uuid-witness"}, + ], + "fields": [ + {"name": "phone", "submitter_uuid": "uuid-signer"}, + {"name": "witness_name", "submitter_uuid": "uuid-witness"}, + {"name": "witness_city", "submitter_uuid": "uuid-witness"}, + ], + } + # The phone mapping of the current role is lost: warn the user. + with self._mock_api(payload), self.assertLogs( + "odoo.tests.form.onchange", level="WARNING" + ) as logs: + with Form(self.template) as form: + form.submitter_role_id = witness + self.assertIn("Field mapping reset", logs.output[0]) + + self.assertEqual(self.template.submitter_role_id, witness) + self.assertEqual(self._field_names(), ["witness_name", "witness_city"]) + self.assertFalse(self.template.field_ids.partner_field_id) + + def test_change_role_without_mapping_does_not_warn(self): + """No warning when there is no mapping to lose.""" + self.template.field_ids.partner_field_id = False + witness = self.env["docuseal.template.role"].create({ + "template_id": self.template.id, + "name": "Witness", + "uuid": "uuid-witness", + }) + payload = {"submitters": [], "fields": [{"name": "witness_name"}]} + with self._mock_api(payload), self.assertNoLogs( + "odoo.tests.form.onchange", level="WARNING" + ): + with Form(self.template) as form: + form.submitter_role_id = witness + self.assertEqual(self._field_names(), ["witness_name"]) def test_fetch_fields_restores_order_after_manual_delete(self): """Deleting the first mapped field then re-fetching from the Docuseal API re-establishes the original field order.""" payload = { - "submitters": [{"name": "Signer"}], + "submitters": [{"name": "Signer", "uuid": "uuid-signer"}], "fields": [{"name": "a"}, {"name": "b"}, {"name": "c"}], } with self._mock_api(payload): self.template.action_fetch_fields() - self.assertEqual( - self.template.field_ids.mapped("docuseal_field_name"), - ["a", "b", "c"], - ) + self.assertEqual(self._field_names(), ["a", "b", "c"]) # The user deletes the first mapping line. self.template.field_ids[0].unlink() - # Re-fetching must restore the Docuseal order. Invalidate the - # one2many cache to read like a fresh request would (the web - # client always re-reads after the action). with self._mock_api(payload): self.template.action_fetch_fields() - self.template.invalidate_recordset(["field_ids"]) - self.assertEqual( - self.template.field_ids.mapped("docuseal_field_name"), - ["a", "b", "c"], - ) + self.assertEqual(self._field_names(), ["a", "b", "c"]) + + def test_fetch_errors_raise_user_error(self): + """A missing token or a Docuseal error is reported to the user.""" + with mock.patch.object( + docuseal_template_module.urllib.request, + "urlopen", + side_effect=urllib.error.HTTPError( + "https://sign.example.com", 401, "Unauthorized", {}, None + ), + ), self.assertRaisesRegex(UserError, "401"): + self.template.action_fetch_fields() + + self.env["ir.config_parameter"].sudo().set_param("docuseal.api_token", "") + with self.assertRaises(UserError): + self.template.action_fetch_fields() diff --git a/docuseal_signing/tests/test_submissions.py b/docuseal_signing/tests/test_submissions.py index 19ec208..22a7c86 100644 --- a/docuseal_signing/tests/test_submissions.py +++ b/docuseal_signing/tests/test_submissions.py @@ -18,7 +18,10 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase): cls.template = cls.env["docuseal.template"].create({ "name": "Onboarding", "template_id": 777, - "submitter_role": "Signer", + }) + cls.template.submitter_role_id = cls.env["docuseal.template.role"].create({ + "template_id": cls.template.id, + "name": "Signer", }) for docuseal_name, fname in [ ("full_name", "name"), diff --git a/docuseal_signing/views/docuseal_template_views.xml b/docuseal_signing/views/docuseal_template_views.xml index 81db6ed..3f91a1f 100644 --- a/docuseal_signing/views/docuseal_template_views.xml +++ b/docuseal_signing/views/docuseal_template_views.xml @@ -8,7 +8,7 @@ - + @@ -40,21 +40,28 @@ - - -
+ + - +