[FIX] docuseal_signing: restrict signature requests and report API errors
- Reserve the generated "Request signature" action to administrators (base.group_system), who are the only ones able to read the Docuseal templates, instead of letting other users hit an AccessError. - Request the signature of a single contact from the contextual action (_action_request_signature): with several contacts, a failure could leave some of them already emailed while the action reports an error. A notification confirms the request. - Share the Docuseal API call in _docuseal_request: a missing token or a Docuseal error (with the explanation it sends) now raises a readable UserError when sending submissions too, not only when fetching. Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,8 +22,11 @@ signatures from partners in a few clicks.
|
||||
them (empty mappings stay editable by the signer).
|
||||
- **One-click signature request**: generate a server action bound to
|
||||
`res.partner` (contextual *Action* menu entry) that creates a Docuseal
|
||||
submission for the selected contacts and emails them the signature
|
||||
request. A draft mode (`_create_draft_submissions`) creates the
|
||||
submission for the selected contact and emails them the signature
|
||||
request. It is reserved to administrators (`base.group_system`, who
|
||||
manage the Docuseal templates), and only runs on a
|
||||
single contact so that a failure never leaves some contacts already
|
||||
emailed. A draft mode (`_create_draft_submissions`) creates the
|
||||
pre-filled submission without sending the email, so it can be sent
|
||||
from Docuseal.
|
||||
- **Settings**: configure the Docuseal API URL and API token in
|
||||
@@ -71,15 +74,19 @@ Behavior of both calls:
|
||||
as a comma-joined list of display names, and selection values as
|
||||
their human-readable label.
|
||||
- Both methods return the list of Docuseal API responses (one dict per
|
||||
submission); errors bubble up as exceptions if the API call fails.
|
||||
submission). A missing API token or a Docuseal error (with the
|
||||
explanation sent by Docuseal) raises a `UserError`; with several
|
||||
partners, the submissions created before the error are not rolled
|
||||
back in Docuseal.
|
||||
|
||||
### From a server action
|
||||
|
||||
The generated contextual action calls the same entry point on the
|
||||
selected records:
|
||||
The generated contextual action calls `_action_request_signature`,
|
||||
which refuses a selection of several contacts, then `_create_submissions`
|
||||
and shows a confirmation notification:
|
||||
|
||||
```python
|
||||
env['docuseal.template'].browse(<template_record_id>)._create_submissions(records)
|
||||
action = env['docuseal.template'].browse(<template_record_id>)._action_request_signature(records)
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
@@ -280,8 +280,8 @@ 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"
|
||||
msgid "Docuseal returned an error %(code)s: %(detail)s"
|
||||
msgstr "Docuseal a renvoyé une erreur %(code)s : %(detail)s"
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
@@ -323,3 +323,21 @@ 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."
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid "Select a single contact to request a signature."
|
||||
msgstr "Sélectionnez un seul contact pour demander une signature."
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid "Signature requested"
|
||||
msgstr "Signature demandée"
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid "The signature request has been sent to %(partner)s."
|
||||
msgstr "La demande de signature a été envoyée à %(partner)s."
|
||||
|
||||
@@ -8,6 +8,8 @@ from odoo.exceptions import UserError
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_API_URL = "https://sign.elabore.coop"
|
||||
|
||||
|
||||
class DocusealTemplate(models.Model):
|
||||
_name = "docuseal.template"
|
||||
@@ -43,32 +45,39 @@ class DocusealTemplate(models.Model):
|
||||
ondelete="set null",
|
||||
)
|
||||
|
||||
def _fetch_docuseal_template(self):
|
||||
"""Return the template definition from the Docuseal API."""
|
||||
self.ensure_one()
|
||||
def _docuseal_request(self, path, payload=None):
|
||||
"""Call the Docuseal API and return the decoded JSON response.
|
||||
|
||||
``payload``, when given, is sent as a JSON POST body. Configuration
|
||||
and API errors are raised as UserError with a readable message.
|
||||
"""
|
||||
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"
|
||||
api_url = (
|
||||
IrParam.get_param("docuseal.api_url") or DEFAULT_API_URL
|
||||
).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})
|
||||
headers = {"X-Auth-Token": api_token}
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(
|
||||
f"{api_url}{path}", data=data, headers=headers
|
||||
)
|
||||
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,
|
||||
"Docuseal returned an error %(code)s: %(detail)s",
|
||||
code=err.code,
|
||||
reason=err.reason,
|
||||
detail=self._docuseal_error_detail(err),
|
||||
)
|
||||
) from err
|
||||
except (urllib.error.URLError, TimeoutError) as err:
|
||||
@@ -80,6 +89,25 @@ class DocusealTemplate(models.Model):
|
||||
)
|
||||
) from err
|
||||
|
||||
@staticmethod
|
||||
def _docuseal_error_detail(err):
|
||||
"""Explanation sent by Docuseal with an HTTP error, if any."""
|
||||
try:
|
||||
body = err.read().decode(errors="replace").strip()
|
||||
except (OSError, AttributeError, ValueError):
|
||||
# No readable body: the HTTP reason is enough.
|
||||
body = ""
|
||||
try:
|
||||
detail = json.loads(body).get("error")
|
||||
except (ValueError, AttributeError):
|
||||
detail = body[:500]
|
||||
return detail or err.reason
|
||||
|
||||
def _fetch_docuseal_template(self):
|
||||
"""Return the template definition from the Docuseal API."""
|
||||
self.ensure_one()
|
||||
return self._docuseal_request(f"/api/templates/{self.template_id}")
|
||||
|
||||
@staticmethod
|
||||
def _role_field_names(data, role):
|
||||
"""Names of the Docuseal fields of ``role``, in the API order.
|
||||
@@ -187,8 +215,8 @@ class DocusealTemplate(models.Model):
|
||||
[("model", "=", "res.partner")], limit=1
|
||||
)
|
||||
code = (
|
||||
f"env['docuseal.template'].browse({self.id})"
|
||||
f"._create_submissions(records)"
|
||||
f"action = env['docuseal.template'].browse({self.id})"
|
||||
f"._action_request_signature(records)"
|
||||
)
|
||||
vals = {
|
||||
"name": f"Request signature ({self.name or self.template_id})",
|
||||
@@ -197,6 +225,10 @@ class DocusealTemplate(models.Model):
|
||||
"code": code,
|
||||
"binding_model_id": partner_model.id,
|
||||
"binding_type": "action",
|
||||
# Docuseal templates are managed by administrators only: hide
|
||||
# the action from the other users instead of letting them hit
|
||||
# an access error.
|
||||
"groups_id": [Command.set(self.env.ref("base.group_system").ids)],
|
||||
}
|
||||
if self.server_action_id:
|
||||
self.server_action_id.write(vals)
|
||||
@@ -225,6 +257,29 @@ class DocusealTemplate(models.Model):
|
||||
self.mapped("server_action_id").unlink()
|
||||
return super().unlink()
|
||||
|
||||
def _action_request_signature(self, partners):
|
||||
"""Entry point of the contextual action: request the signature of a
|
||||
single contact, so that a failure cannot leave some contacts
|
||||
already emailed while the action reports an error."""
|
||||
self.ensure_one()
|
||||
if len(partners) != 1:
|
||||
raise UserError(
|
||||
_("Select a single contact to request a signature.")
|
||||
)
|
||||
self._create_submissions(partners)
|
||||
return {
|
||||
"type": "ir.actions.client",
|
||||
"tag": "display_notification",
|
||||
"params": {
|
||||
"title": _("Signature requested"),
|
||||
"message": _(
|
||||
"The signature request has been sent to %(partner)s.",
|
||||
partner=partners.display_name,
|
||||
),
|
||||
"type": "success",
|
||||
},
|
||||
}
|
||||
|
||||
def _create_draft_submissions(self, partners):
|
||||
"""Create pre-filled submissions without sending the signature request
|
||||
email: the submission must then be sent from Docuseal."""
|
||||
@@ -232,11 +287,6 @@ class DocusealTemplate(models.Model):
|
||||
|
||||
def _create_submissions(self, partners, send_email=True):
|
||||
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("/")
|
||||
|
||||
results = []
|
||||
for partner in partners:
|
||||
@@ -267,7 +317,7 @@ class DocusealTemplate(models.Model):
|
||||
"readonly": bool(value),
|
||||
})
|
||||
|
||||
payload = json.dumps({
|
||||
payload = {
|
||||
"template_id": self.template_id,
|
||||
"send_email": send_email,
|
||||
"submitters": [{
|
||||
@@ -276,8 +326,7 @@ class DocusealTemplate(models.Model):
|
||||
"email": partner.email or "",
|
||||
"fields": submitter_fields,
|
||||
}],
|
||||
}).encode()
|
||||
|
||||
}
|
||||
_logger.info(
|
||||
"Docuseal: creating submission for %s with template %s "
|
||||
"(send_email=%s), fields: %s",
|
||||
@@ -286,16 +335,9 @@ class DocusealTemplate(models.Model):
|
||||
send_email,
|
||||
submitter_fields,
|
||||
)
|
||||
req = urllib.request.Request(
|
||||
f"{api_url}/api/submissions",
|
||||
data=payload,
|
||||
headers={
|
||||
"X-Auth-Token": api_token,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
result = self._docuseal_request("/api/submissions", payload)
|
||||
_logger.info(
|
||||
"Docuseal submission created for %s: %s", partner.name, result
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
body = resp.read().decode()
|
||||
_logger.info("Docuseal submission created for %s: %s", partner.name, body)
|
||||
results.append(json.loads(body))
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from odoo.tests import TransactionCase
|
||||
from odoo.exceptions import AccessError, UserError
|
||||
from odoo.tests import TransactionCase, new_test_user
|
||||
|
||||
from .common import DocusealApiMockMixin
|
||||
|
||||
|
||||
class TestServerAction(TransactionCase):
|
||||
"""Lifecycle of the generated contextual server action."""
|
||||
class TestServerAction(DocusealApiMockMixin, TransactionCase):
|
||||
"""Lifecycle and execution of the generated contextual server action."""
|
||||
|
||||
def test_unlink_removes_server_action(self):
|
||||
"""Deleting a template removes its generated server action,
|
||||
@@ -36,3 +39,62 @@ class TestServerAction(TransactionCase):
|
||||
]),
|
||||
1,
|
||||
)
|
||||
|
||||
def _run_action(self, template, partners, user):
|
||||
return template.server_action_id.with_user(user).with_context(
|
||||
active_model="res.partner",
|
||||
active_ids=partners.ids,
|
||||
active_id=partners[:1].id,
|
||||
).run()
|
||||
|
||||
def test_request_signature_is_restricted_to_administrators(self):
|
||||
"""The contextual action is reserved to administrators, who can
|
||||
read the Docuseal templates; other users neither see nor run it."""
|
||||
self._set_api_config()
|
||||
template = self.env["docuseal.template"].create({
|
||||
"name": "Contract",
|
||||
"template_id": 789,
|
||||
})
|
||||
template.action_create_server_action()
|
||||
self.assertEqual(
|
||||
template.server_action_id.groups_id,
|
||||
self.env.ref("base.group_system"),
|
||||
)
|
||||
partner = self.env["res.partner"].create({
|
||||
"name": "Camille Dupont",
|
||||
"email": "camille@example.com",
|
||||
})
|
||||
user = new_test_user(
|
||||
self.env,
|
||||
login="docuseal_user",
|
||||
groups="base.group_user,base.group_partner_manager",
|
||||
)
|
||||
|
||||
with self._mock_api({"id": 60}), self.assertRaises(AccessError):
|
||||
self._run_action(template, partner, user)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
with self._mock_api({"id": 60}):
|
||||
result = self._run_action(template, partner, self.env.user)
|
||||
self.assertEqual(len(self.requests), 1)
|
||||
self.assertEqual(self.requests[0]["payload"]["template_id"], 789)
|
||||
self.assertEqual(result["params"]["type"], "success")
|
||||
|
||||
def test_request_signature_requires_a_single_contact(self):
|
||||
"""Selecting several contacts is refused before any API call, so
|
||||
that no contact is emailed when the action fails."""
|
||||
self._set_api_config()
|
||||
template = self.env["docuseal.template"].create({
|
||||
"name": "Contract",
|
||||
"template_id": 790,
|
||||
})
|
||||
template.action_create_server_action()
|
||||
partners = self.env["res.partner"].create([
|
||||
{"name": "Camille Dupont"}, {"name": "Alex Martin"},
|
||||
])
|
||||
|
||||
with self._mock_api({"id": 61}), self.assertRaisesRegex(
|
||||
UserError, "single contact"
|
||||
):
|
||||
self._run_action(template, partners, self.env.user)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import io
|
||||
import json
|
||||
import urllib.error
|
||||
from unittest import mock
|
||||
|
||||
from odoo.exceptions import UserError
|
||||
from odoo.tests import TransactionCase
|
||||
|
||||
from odoo.addons.docuseal_signing.models import (
|
||||
docuseal_template as docuseal_template_module,
|
||||
)
|
||||
|
||||
from .common import DocusealApiMockMixin
|
||||
|
||||
|
||||
@@ -131,3 +141,31 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
|
||||
self.requests[0]["url"],
|
||||
"https://sign.example.com/api/submissions",
|
||||
)
|
||||
|
||||
def test_missing_token_raises_user_error(self):
|
||||
"""Without API token, the user is told to configure it instead of
|
||||
getting a technical error."""
|
||||
self._set_api_config()
|
||||
self.env["ir.config_parameter"].sudo().set_param("docuseal.api_token", "")
|
||||
with self._mock_api({"id": 59}), self.assertRaisesRegex(
|
||||
UserError, "API token"
|
||||
):
|
||||
self.template._create_submissions(self.partner)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
def test_docuseal_error_raises_user_error_with_detail(self):
|
||||
"""A Docuseal rejection is reported with the explanation it sent."""
|
||||
self._set_api_config()
|
||||
error = urllib.error.HTTPError(
|
||||
"https://sign.example.com/api/submissions",
|
||||
422,
|
||||
"Unprocessable Entity",
|
||||
{},
|
||||
io.BytesIO(json.dumps({"error": "Role not found"}).encode()),
|
||||
)
|
||||
with mock.patch.object(
|
||||
docuseal_template_module.urllib.request,
|
||||
"urlopen",
|
||||
side_effect=error,
|
||||
), self.assertRaisesRegex(UserError, "422: Role not found"):
|
||||
self.template._create_submissions(self.partner)
|
||||
|
||||
Reference in New Issue
Block a user