[ADD] docuseal_signing: request Docuseal signatures from Odoo #1

Open
mondot wants to merge 15 commits from docuseal_signing into 18.0
5 changed files with 210 additions and 43 deletions
Showing only changes of commit 87653552b1 - Show all commits

View File

@@ -22,8 +22,11 @@ signatures from partners in a few clicks.
them (empty mappings stay editable by the signer). them (empty mappings stay editable by the signer).
- **One-click signature request**: generate a server action bound to - **One-click signature request**: generate a server action bound to
`res.partner` (contextual *Action* menu entry) that creates a Docuseal `res.partner` (contextual *Action* menu entry) that creates a Docuseal
submission for the selected contacts and emails them the signature submission for the selected contact and emails them the signature
request. A draft mode (`_create_draft_submissions`) creates the 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 pre-filled submission without sending the email, so it can be sent
from Docuseal. from Docuseal.
- **Settings**: configure the Docuseal API URL and API token in - **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 as a comma-joined list of display names, and selection values as
their human-readable label. their human-readable label.
- Both methods return the list of Docuseal API responses (one dict per - 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 ### From a server action
The generated contextual action calls the same entry point on the The generated contextual action calls `_action_request_signature`,
selected records: which refuses a selection of several contacts, then `_create_submissions`
and shows a confirmation notification:
```python ```python
env['docuseal.template'].browse(<template_record_id>)._create_submissions(records) action = env['docuseal.template'].browse(<template_record_id>)._action_request_signature(records)
``` ```
### Configuration ### Configuration

View File

@@ -280,8 +280,8 @@ msgstr "Renseignez d'abord le token API Docuseal dans les Paramètres généraux
#. module: docuseal_signing #. module: docuseal_signing
#. odoo-python #. odoo-python
#: code:addons/docuseal_signing/models/docuseal_template.py:0 #: code:addons/docuseal_signing/models/docuseal_template.py:0
msgid "Docuseal returned an error for template %(template)s: %(code)s %(reason)s" msgid "Docuseal returned an error %(code)s: %(detail)s"
msgstr "Docuseal a renvoyé une erreur pour le template %(template)s : %(code)s %(reason)s" msgstr "Docuseal a renvoyé une erreur %(code)s : %(detail)s"
#. module: docuseal_signing #. module: docuseal_signing
#. odoo-python #. odoo-python
@@ -323,3 +323,21 @@ msgstr ""
"Les champs du nouveau rôle sont chargés sans correspondance. Si vous " "Les champs du nouveau rôle sont chargés sans correspondance. Si vous "
"enregistrez, la correspondance actuelle des champs sera perdue. Ignorez tous " "enregistrez, la correspondance actuelle des champs sera perdue. Ignorez tous "
"les changements pour la conserver." "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."

View File

@@ -8,6 +8,8 @@ from odoo.exceptions import UserError
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
DEFAULT_API_URL = "https://sign.elabore.coop"
class DocusealTemplate(models.Model): class DocusealTemplate(models.Model):
_name = "docuseal.template" _name = "docuseal.template"
@@ -43,32 +45,39 @@ class DocusealTemplate(models.Model):
ondelete="set null", ondelete="set null",
) )
def _fetch_docuseal_template(self): def _docuseal_request(self, path, payload=None):
"""Return the template definition from the Docuseal API.""" """Call the Docuseal API and return the decoded JSON response.
self.ensure_one()
``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() IrParam = self.env["ir.config_parameter"].sudo()
api_token = IrParam.get_param("docuseal.api_token") api_token = IrParam.get_param("docuseal.api_token")
api_url = IrParam.get_param( api_url = (
"docuseal.api_url", "https://sign.elabore.coop" IrParam.get_param("docuseal.api_url") or DEFAULT_API_URL
).rstrip("/") ).rstrip("/")
if not api_token: if not api_token:
raise UserError( raise UserError(
_("Set the Docuseal API token in the General Settings first.") _("Set the Docuseal API token in the General Settings first.")
) )
url = f"{api_url}/api/templates/{self.template_id}" headers = {"X-Auth-Token": api_token}
req = urllib.request.Request(url, 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: try:
with urllib.request.urlopen(req, timeout=10) as resp: with urllib.request.urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode()) return json.loads(resp.read().decode())
except urllib.error.HTTPError as err: except urllib.error.HTTPError as err:
raise UserError( raise UserError(
_( _(
"Docuseal returned an error for template %(template)s: " "Docuseal returned an error %(code)s: %(detail)s",
"%(code)s %(reason)s",
template=self.template_id,
code=err.code, code=err.code,
reason=err.reason, detail=self._docuseal_error_detail(err),
) )
) from err ) from err
except (urllib.error.URLError, TimeoutError) as err: except (urllib.error.URLError, TimeoutError) as err:
@@ -80,6 +89,25 @@ class DocusealTemplate(models.Model):
) )
) from err ) 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 @staticmethod
def _role_field_names(data, role): def _role_field_names(data, role):
"""Names of the Docuseal fields of ``role``, in the API order. """Names of the Docuseal fields of ``role``, in the API order.
@@ -187,8 +215,8 @@ class DocusealTemplate(models.Model):
[("model", "=", "res.partner")], limit=1 [("model", "=", "res.partner")], limit=1
) )
code = ( code = (
f"env['docuseal.template'].browse({self.id})" f"action = env['docuseal.template'].browse({self.id})"
f"._create_submissions(records)" f"._action_request_signature(records)"
) )
vals = { vals = {
"name": f"Request signature ({self.name or self.template_id})", "name": f"Request signature ({self.name or self.template_id})",
@@ -197,6 +225,10 @@ class DocusealTemplate(models.Model):
"code": code, "code": code,
"binding_model_id": partner_model.id, "binding_model_id": partner_model.id,
"binding_type": "action", "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: if self.server_action_id:
self.server_action_id.write(vals) self.server_action_id.write(vals)
@@ -225,6 +257,29 @@ class DocusealTemplate(models.Model):
self.mapped("server_action_id").unlink() self.mapped("server_action_id").unlink()
return super().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): def _create_draft_submissions(self, partners):
"""Create pre-filled submissions without sending the signature request """Create pre-filled submissions without sending the signature request
email: the submission must then be sent from Docuseal.""" 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): def _create_submissions(self, partners, send_email=True):
self.ensure_one() 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 = [] results = []
for partner in partners: for partner in partners:
@@ -267,7 +317,7 @@ class DocusealTemplate(models.Model):
"readonly": bool(value), "readonly": bool(value),
}) })
payload = json.dumps({ payload = {
"template_id": self.template_id, "template_id": self.template_id,
"send_email": send_email, "send_email": send_email,
"submitters": [{ "submitters": [{
@@ -276,8 +326,7 @@ class DocusealTemplate(models.Model):
"email": partner.email or "", "email": partner.email or "",
"fields": submitter_fields, "fields": submitter_fields,
}], }],
}).encode() }
_logger.info( _logger.info(
"Docuseal: creating submission for %s with template %s " "Docuseal: creating submission for %s with template %s "
"(send_email=%s), fields: %s", "(send_email=%s), fields: %s",
@@ -286,16 +335,9 @@ class DocusealTemplate(models.Model):
send_email, send_email,
submitter_fields, submitter_fields,
) )
req = urllib.request.Request( result = self._docuseal_request("/api/submissions", payload)
f"{api_url}/api/submissions", _logger.info(
data=payload, "Docuseal submission created for %s: %s", partner.name, result
headers={
"X-Auth-Token": api_token,
"Content-Type": "application/json",
},
) )
with urllib.request.urlopen(req, timeout=10) as resp: results.append(result)
body = resp.read().decode()
_logger.info("Docuseal submission created for %s: %s", partner.name, body)
results.append(json.loads(body))
return results return results

View File

@@ -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): class TestServerAction(DocusealApiMockMixin, TransactionCase):
"""Lifecycle of the generated contextual server action.""" """Lifecycle and execution of the generated contextual server action."""
def test_unlink_removes_server_action(self): def test_unlink_removes_server_action(self):
"""Deleting a template removes its generated server action, """Deleting a template removes its generated server action,
@@ -36,3 +39,62 @@ class TestServerAction(TransactionCase):
]), ]),
1, 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)

View File

@@ -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.tests import TransactionCase
from odoo.addons.docuseal_signing.models import (
docuseal_template as docuseal_template_module,
)
from .common import DocusealApiMockMixin from .common import DocusealApiMockMixin
@@ -131,3 +141,31 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
self.requests[0]["url"], self.requests[0]["url"],
"https://sign.example.com/api/submissions", "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)