Compare commits

...

3 Commits

Author SHA1 Message Date
fddc2e5c4b [FIX] docuseal_signing: harden template copies, API errors and emails
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 52s
- Do not copy the contextual action nor the submitter role with a
  template: a copy sharing the action would rewrite or delete the
  original's.
- Make the template ID read-only once fetched from Docuseal: another
  Docuseal template needs a new entry.
- Report an invalid API URL or token, an unexpected (non-JSON) response
  and a connection dropped mid-response as a readable UserError.
- Refuse to email a signature request to contacts without a valid email
  address (email_normalize), before any call to Docuseal.
- Stop logging the field values and the Docuseal response, which hold
  personal data and the signing links.
- Prevent adding mapping lines by hand: they come from Docuseal only.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:35:19 +01:00
87653552b1 [FIX] docuseal_signing: restrict signature requests and report API errors
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 50s
- 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>
2026-11-09 17:04:23 +01:00
c7f3a2dcfe [IMP] docuseal_signing: pick the submitter role from the Docuseal roles
Some checks failed
tests / test (pull_request) Successful in 56s
pre-commit / pre-commit (pull_request) Failing after 1m34s
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 <noreply@anthropic.com>
2026-11-09 16:47:05 +01:00
10 changed files with 849 additions and 122 deletions

View File

@@ -8,17 +8,27 @@ signatures from partners in a few clicks.
## Features ## Features
- **Template registry** (`docuseal.template`): reference Docuseal - **Template registry** (`docuseal.template`): reference Docuseal
templates by their ID and submitter role, and fetch their field list templates by their ID; the *Fetch from Docuseal* button loads their
from the Docuseal API with a single click. 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 mapping** (`docuseal.template.field`): map each Docuseal
field to a `res.partner` field. Fields are kept in the order returned field of the selected role to a `res.partner` field. Fetching again
by the Docuseal API (reorderable with drag & drop). Values are keeps the existing mappings; changing the role loads the fields of
the new role from Docuseal with an empty mapping (with a warning in
the form). Once fetched, the template ID is read-only: another
Docuseal template needs a new entry. 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 pre-filled at submission time and locked so the signer cannot change
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
@@ -56,8 +66,9 @@ template._create_draft_submissions(partners)
Behavior of both calls: Behavior of both calls:
- One Docuseal submission is created per partner, using the template's - 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. and `email` identify the submitter. When the request is emailed, every
partner must have an email address: otherwise nothing is sent.
- Each mapped Docuseal field is pre-filled from the partner field set - Each mapped Docuseal field is pre-filled from the partner field set
in `docuseal.template.field`. Non-empty values are locked in `docuseal.template.field`. Non-empty values are locked
(`readonly=True`) so the signer cannot change them; empty values (`readonly=True`) so the signer cannot change them; empty values
@@ -66,15 +77,20 @@ 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), an invalid API URL or an unreachable
instance 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

@@ -70,12 +70,14 @@ msgstr "Créer l'action contextuelle"
#. module: docuseal_signing #. 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__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_field__create_uid
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__create_uid
msgid "Created by" msgid "Created by"
msgstr "Créé par" msgstr "Créé par"
#. module: docuseal_signing #. 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__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_field__create_date
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__create_date
msgid "Created on" msgid "Created on"
msgstr "Créé le" msgstr "Créé le"
@@ -103,6 +105,7 @@ msgstr ""
#. module: docuseal_signing #. 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__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_field__display_name
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__display_name
msgid "Display Name" msgid "Display Name"
msgstr "Nom affiché" msgstr "Nom affiché"
@@ -150,8 +153,8 @@ msgstr "Templates Docuseal"
#. module: docuseal_signing #. module: docuseal_signing
#: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form #: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form
msgid "Fetch template fields" msgid "Fetch from Docuseal"
msgstr "Rapatrier les champs du template" msgstr "Rapatrier depuis Docuseal"
#. module: docuseal_signing #. module: docuseal_signing
#: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form #: model_terms:ir.ui.view,arch_db:docuseal_signing.docuseal_template_view_form
@@ -166,18 +169,21 @@ msgstr "Champs"
#. module: docuseal_signing #. 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__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_field__id
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__id
msgid "ID" msgid "ID"
msgstr "ID" msgstr "ID"
#. module: docuseal_signing #. 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__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_field__write_uid
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__write_uid
msgid "Last Updated by" msgid "Last Updated by"
msgstr "Dernière mise à jour par" msgstr "Dernière mise à jour par"
#. module: docuseal_signing #. 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__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_field__write_date
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__write_date
msgid "Last Updated on" msgid "Last Updated on"
msgstr "Dernière mise à jour le" msgstr "Dernière mise à jour le"
@@ -191,13 +197,9 @@ msgstr "Gérer les templates Docuseal"
msgid "Name" msgid "Name"
msgstr "Nom" 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 #. 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_field__sequence
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__sequence
msgid "Sequence" msgid "Sequence"
msgstr "Séquence" msgstr "Séquence"
@@ -209,17 +211,19 @@ msgstr "Action serveur"
#. module: docuseal_signing #. 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__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_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 #: model:ir.model.fields,field_description:docuseal_signing.field_res_config_settings__smart_search
msgid "Smart Search" msgid "Smart Search"
msgstr "Recherche intelligente" msgstr "Recherche intelligente"
#. module: docuseal_signing #. 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" msgid "Submitter role"
msgstr "Rôle du signataire" msgstr "Rôle du signataire"
#. module: docuseal_signing #. 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_field__template_id
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_role__template_id
msgid "Template" msgid "Template"
msgstr "Template" msgstr "Template"
@@ -231,13 +235,148 @@ msgstr "ID du template"
#. module: docuseal_signing #. module: docuseal_signing
#: model:ir.model.fields,help:docuseal_signing.field_docuseal_template__template_id #: model:ir.model.fields,help:docuseal_signing.field_docuseal_template__template_id
msgid "" msgid ""
"You can find the template id in the URL when you have selected the template " "You can find the template id in the URL when you have selected the "
"in Docuseal." "template in Docuseal. It cannot be changed once fetched from Docuseal: to "
"use another template, create a new entry."
msgstr "" msgstr ""
"Vous trouverez l'identifiant du template dans l'URL après avoir sélectionné " "Vous trouverez l'identifiant du template dans l'URL après avoir sélectionné "
"le template dans Docuseal." "le template dans Docuseal. Il ne peut plus être modifié une fois rapatrié "
"depuis Docuseal : pour utiliser un autre template, veuillez créer une "
"nouvelle entrée."
#. module: docuseal_signing #. module: docuseal_signing
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__partner_field_id #: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__partner_field_id
msgid "res.partner field" msgid "res.partner field"
msgstr "Champ res.partner" 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 %(code)s: %(detail)s"
msgstr "Docuseal a renvoyé une erreur %(code)s : %(detail)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."
#. 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."
#. module: docuseal_signing
#. odoo-python
#: code:addons/docuseal_signing/models/docuseal_template.py:0
msgid "The Docuseal API URL %(url)s is invalid: %(error)s"
msgstr "L'URL de l'API Docuseal %(url)s est invalide : %(error)s"
#. module: docuseal_signing
#. odoo-python
#: code:addons/docuseal_signing/models/docuseal_template.py:0
msgid ""
"Docuseal returned an unexpected response from %(url)s. "
"Check the Docuseal API URL in the General Settings."
msgstr ""
"Docuseal a renvoyé une réponse inattendue depuis %(url)s. Vérifiez "
"l'URL de l'API Docuseal dans les Paramètres généraux."
#. module: docuseal_signing
#. odoo-python
#: code:addons/docuseal_signing/models/docuseal_template.py:0
msgid ""
"The signature request cannot be emailed to contacts "
"without a valid email address: %(partners)s"
msgstr ""
"La demande de signature ne peut pas être envoyée par e-mail aux contacts "
"sans adresse e-mail valide : %(partners)s"
#. module: docuseal_signing
#. odoo-python
#: code:addons/docuseal_signing/models/docuseal_template.py:0
msgid ""
"The request to Docuseal could not be sent: %(error)s. "
"Check the Docuseal API token in the General Settings."
msgstr ""
"La requête vers Docuseal n'a pas pu être envoyée : %(error)s. "
"Vérifiez le token API Docuseal dans les Paramètres généraux."

View File

@@ -1,3 +1,4 @@
from . import docuseal_template from . import docuseal_template
from . import docuseal_template_field from . import docuseal_template_field
from . import docuseal_template_role
from . import res_config_settings from . import res_config_settings

View File

@@ -1,11 +1,17 @@
import http.client
import json import json
import logging import logging
import urllib.error
import urllib.request import urllib.request
from odoo import _, fields, models from odoo import Command, _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.mail import email_normalize
_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"
@@ -14,12 +20,24 @@ class DocusealTemplate(models.Model):
name = fields.Char(string="Name") name = fields.Char(string="Name")
template_id = fields.Integer( template_id = fields.Integer(
string="Template ID", string="Template ID",
help="You can find the template id in the URL when you have selected the template in Docuseal.", help="You can find the template id in the URL when you have selected "
required=True "the template in Docuseal. It cannot be changed once fetched from "
"Docuseal: to use another template, create a new entry.",
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", string="Submitter role",
help="Name of the submitter role you have set up in Docuseal.", domain="[('template_id', '=', id)]",
# Roles belong to their template and are not copied with it.
copy=False,
help="Submitter role of the Docuseal template that the contact "
"signs as. The available roles are fetched from Docuseal.",
) )
field_ids = fields.One2many( field_ids = fields.One2many(
comodel_name="docuseal.template.field", comodel_name="docuseal.template.field",
@@ -31,35 +49,138 @@ class DocusealTemplate(models.Model):
string="Server action", string="Server action",
readonly=True, readonly=True,
ondelete="set null", ondelete="set null",
# A copy sharing the action would rewrite or delete the original's.
copy=False,
) )
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") or DEFAULT_API_URL
).rstrip("/")
if not api_token:
raise UserError(
_("Set the Docuseal API token in the General Settings first.")
)
headers = {"X-Auth-Token": api_token}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
try:
req = urllib.request.Request(
f"{api_url}{path}", data=data, headers=headers
)
except ValueError as err:
# Raised by urllib for a URL without scheme or host.
raise UserError(
_(
"The Docuseal API URL %(url)s is invalid: %(error)s",
url=api_url,
error=err,
)
) from err
try:
with urllib.request.urlopen(req, timeout=10) as resp:
body = resp.read()
except urllib.error.HTTPError as err:
raise UserError(
_(
"Docuseal returned an error %(code)s: %(detail)s",
code=err.code,
detail=self._docuseal_error_detail(err),
)
) from err
except ValueError as err:
# Raised by http.client for an invalid header value, such as an
# API token pasted with a line break or a non-latin-1 character.
raise UserError(
_(
"The request to Docuseal could not be sent: %(error)s. "
"Check the Docuseal API token in the General Settings.",
error=err,
)
) from err
except (OSError, http.client.HTTPException) as err:
# URLError, timeouts and connections dropped mid-response.
raise UserError(
_(
"Docuseal could not be reached at %(url)s: %(error)s",
url=api_url,
error=str(getattr(err, "reason", err)) or type(err).__name__,
)
) from err
try:
return json.loads(body.decode())
except ValueError as err:
raise UserError(
_(
"Docuseal returned an unexpected response from %(url)s. "
"Check the Docuseal API URL in the General Settings.",
url=api_url,
)
) 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.
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): def action_fetch_fields(self):
self.ensure_one() self.ensure_one()
IrParam = self.env["ir.config_parameter"].sudo() data = self._fetch_docuseal_template()
api_token = IrParam.get_param("docuseal.api_token")
api_url = IrParam.get_param(
"docuseal.api_url", "https://sign.elabore.coop"
).rstrip("/")
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())
if data.get("name") and not self.name: if data.get("name") and not self.name:
self.name = data["name"] self.name = data["name"]
if data.get("submitters") and not self.submitter_role: self._sync_roles(data.get("submitters", []))
self.submitter_role = data["submitters"][0].get("name", "")
# Reconcile the field mapping with the Docuseal template instead of # Reconcile the field mapping of the selected role with the Docuseal
# wiping it: existing mappings keep their res.partner field and the # template instead of wiping it: existing mappings keep their
# sequence follows the field order returned by the Docuseal API. # 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 = { existing = {
field.docuseal_field_name: field for field in self.field_ids 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): for index, name in enumerate(docuseal_names):
field = existing.get(name) field = existing.get(name)
if field: if field:
@@ -74,14 +195,67 @@ class DocusealTemplate(models.Model):
lambda field: field.docuseal_field_name not in docuseal_names lambda field: field.docuseal_field_name not in docuseal_names
).unlink() ).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): def action_create_server_action(self):
self.ensure_one() self.ensure_one()
partner_model = self.env["ir.model"].search( partner_model = self.env["ir.model"].search(
[("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})",
@@ -90,6 +264,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)
@@ -118,6 +296,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."""
@@ -125,11 +326,21 @@ 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() if send_email:
api_token = IrParam.get_param("docuseal.api_token") # Check every partner before the first call, so that no request
api_url = IrParam.get_param( # is sent when one of them cannot receive it.
"docuseal.api_url", "https://sign.elabore.coop" # email_normalize refuses empty, malformed and multiple addresses.
).rstrip("/") without_email = partners.filtered(
lambda partner: not email_normalize(partner.email)
)
if without_email:
raise UserError(
_(
"The signature request cannot be emailed to contacts "
"without a valid email address: %(partners)s",
partners=", ".join(without_email.mapped("display_name")),
)
)
results = [] results = []
for partner in partners: for partner in partners:
@@ -160,35 +371,24 @@ 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": [{
"name": partner.name, "name": partner.name,
"role": self.submitter_role or "", "role": self.submitter_role_id.name or "",
"email": partner.email or "", "email": email_normalize(partner.email) or partner.email or "",
"fields": submitter_fields, "fields": submitter_fields,
}], }],
}).encode() }
# Do not log the field values (personal data) nor the response:
# it contains the signing links of the submitters.
_logger.info( _logger.info(
"Docuseal: creating submission for %s with template %s " "Docuseal: creating submission for res.partner %s with "
"(send_email=%s), fields: %s", "template %s (send_email=%s)",
partner.name, partner.id,
self.template_id, self.template_id,
send_email, send_email,
submitter_fields,
) )
req = urllib.request.Request( results.append(self._docuseal_request("/api/submissions", payload))
f"{api_url}/api/submissions",
data=payload,
headers={
"X-Auth-Token": api_token,
"Content-Type": "application/json",
},
)
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))
return results return results

View File

@@ -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",
)

View File

@@ -1,3 +1,4 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink 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_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_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
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
2 access_docuseal_template_system docuseal.template system model_docuseal_template base.group_system 1 1 1 1
3 access_docuseal_template_field_system docuseal.template.field system model_docuseal_template_field base.group_system 1 1 1 1
4 access_docuseal_template_role_system docuseal.template.role system model_docuseal_template_role base.group_system 1 1 1 1

View File

@@ -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 from .common import DocusealApiMockMixin
class TestFetchFields(DocusealApiMockMixin, TransactionCase): class TestFetchFields(DocusealApiMockMixin, TransactionCase):
"""Reconciliation of the field mapping on action_fetch_fields.""" """Roles and field mapping fetched from the Docuseal API."""
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):
@@ -15,7 +23,11 @@ class TestFetchFields(DocusealApiMockMixin, TransactionCase):
cls.template = cls.env["docuseal.template"].create({ cls.template = cls.env["docuseal.template"].create({
"name": "Old name", "name": "Old name",
"template_id": 999, "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({ cls.env["docuseal.template.field"].create({
"template_id": cls.template.id, "template_id": cls.template.id,
@@ -27,78 +39,199 @@ class TestFetchFields(DocusealApiMockMixin, TransactionCase):
"docuseal_field_name": "obsolete", "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): def test_fetch_fields_reconciles_mapping(self):
"""Existing mappings keep their partner field; removed Docuseal """Existing mappings keep their partner field; removed Docuseal
fields are dropped and new ones are added, in the order returned fields are dropped and new ones are added, in the order returned
by the Docuseal API.""" by the Docuseal API."""
payload = { payload = {
"name": "Contract", "name": "Contract",
"submitters": [{"name": "Signer"}], "submitters": [{"name": "Signer", "uuid": "uuid-signer"}],
"fields": [{"name": "phone"}, {"name": "extra"}, {"name": ""}], "fields": [{"name": "phone"}, {"name": "extra"}, {"name": ""}],
} }
with self._mock_api(payload): with self._mock_api(payload):
self.template.action_fetch_fields() 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.assertEqual(
self.template.field_ids.mapped("docuseal_field_name"), self.requests[0]["url"], "https://sign.example.com/api/templates/999"
["phone", "extra"],
) )
self.assertEqual(self._field_names(), ["phone", "extra"])
phone_mapping = self.template.field_ids.filtered( phone_mapping = self.template.field_ids.filtered(
lambda field: field.docuseal_field_name == "phone" lambda field: field.docuseal_field_name == "phone"
) )
self.assertEqual(phone_mapping.partner_field_id, self.phone_field) 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.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): 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.name = False
self.template.submitter_role = False self.template.submitter_role_id = False
payload = { payload = {
"name": "Contract", "name": "Contract",
"submitters": [{"name": "Counterparty"}], "submitters": [{"name": "Counterparty", "uuid": "uuid-cp"}],
"fields": [], "fields": [],
} }
with self._mock_api(payload): with self._mock_api(payload):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.assertEqual(self.template.name, "Contract") self.assertEqual(self.template.name, "Contract")
self.assertEqual(self.template.submitter_role, "Counterparty") self.assertEqual(self.template.submitter_role_id.name, "Counterparty")
self.assertFalse(self.template.field_ids) 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): def test_fetch_fields_restores_order_after_manual_delete(self):
"""Deleting the first mapped field then re-fetching from the """Deleting the first mapped field then re-fetching from the
Docuseal API re-establishes the original field order.""" Docuseal API re-establishes the original field order."""
payload = { payload = {
"submitters": [{"name": "Signer"}], "submitters": [{"name": "Signer", "uuid": "uuid-signer"}],
"fields": [{"name": "a"}, {"name": "b"}, {"name": "c"}], "fields": [{"name": "a"}, {"name": "b"}, {"name": "c"}],
} }
with self._mock_api(payload): with self._mock_api(payload):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.assertEqual( self.assertEqual(self._field_names(), ["a", "b", "c"])
self.template.field_ids.mapped("docuseal_field_name"),
["a", "b", "c"],
)
# The user deletes the first mapping line. # The user deletes the first mapping line.
self.template.field_ids[0].unlink() 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): with self._mock_api(payload):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.template.invalidate_recordset(["field_ids"]) self.assertEqual(self._field_names(), ["a", "b", "c"])
self.assertEqual(
self.template.field_ids.mapped("docuseal_field_name"), def test_fetch_errors_raise_user_error(self):
["a", "b", "c"], """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()
def test_template_id_is_readonly_once_fetched(self):
"""The template ID can be set on a new entry, and becomes read-only
once roles have been fetched from Docuseal."""
form = Form(self.env["docuseal.template"])
form.template_id = 1000
new_template = form.save()
with Form(new_template) as form:
self.assertFalse(form._get_modifier("template_id", "readonly"))
with Form(self.template) as form:
self.assertTrue(form._get_modifier("template_id", "readonly"))

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,84 @@ 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)
def test_copy_does_not_share_action_or_role(self):
"""A duplicated template gets neither the contextual action nor
the role of the original, so it cannot rewrite or delete them."""
template = self.env["docuseal.template"].create({
"name": "Contract",
"template_id": 791,
})
template.submitter_role_id = self.env["docuseal.template.role"].create({
"template_id": template.id,
"name": "Signer",
})
template.action_create_server_action()
action = template.server_action_id
duplicate = template.copy()
self.assertFalse(duplicate.server_action_id)
self.assertFalse(duplicate.submitter_role_id)
duplicate.unlink()
self.assertTrue(action.exists())
self.assertEqual(template.server_action_id, action)

View File

@@ -1,5 +1,16 @@
import http.client
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
@@ -18,7 +29,10 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
cls.template = cls.env["docuseal.template"].create({ cls.template = cls.env["docuseal.template"].create({
"name": "Onboarding", "name": "Onboarding",
"template_id": 777, "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 [ for docuseal_name, fname in [
("full_name", "name"), ("full_name", "name"),
@@ -106,7 +120,10 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
def test_one_submission_per_partner(self): def test_one_submission_per_partner(self):
"""Each partner gets its own submission with a single submitter.""" """Each partner gets its own submission with a single submitter."""
self._set_api_config() self._set_api_config()
partner2 = self.env["res.partner"].create({"name": "Alex Martin"}) partner2 = self.env["res.partner"].create({
"name": "Alex Martin",
"email": "alex@example.com",
})
with self._mock_api({"id": 57}): with self._mock_api({"id": 57}):
self.template._create_submissions(self.partner | partner2) self.template._create_submissions(self.partner | partner2)
@@ -128,3 +145,106 @@ 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)
def test_partner_without_email_is_refused(self):
"""No request is sent when a contact cannot receive the email,
even if the other contacts can."""
self._set_api_config()
no_email = self.env["res.partner"].create({"name": "Sam Leroy"})
with self._mock_api({"id": 62}), self.assertRaisesRegex(
UserError, "Sam Leroy"
):
self.template._create_submissions(self.partner | no_email)
self.assertFalse(self.requests)
# A draft is not emailed: no email address is required.
with self._mock_api({"id": 63}):
self.template._create_draft_submissions(no_email)
self.assertEqual(len(self.requests), 1)
def _assert_user_error(self, regex, **urlopen_patch):
with mock.patch.object(
docuseal_template_module.urllib.request, "urlopen", **urlopen_patch
), self.assertRaisesRegex(UserError, regex):
self.template._create_submissions(self.partner)
def test_invalid_api_url_raises_user_error(self):
"""An API URL without scheme is reported, not a traceback."""
self._set_api_config(api_url="sign.example.com")
with self.assertRaisesRegex(UserError, "is invalid"):
self.template._create_submissions(self.partner)
def test_unexpected_response_raises_user_error(self):
"""A non-JSON response (proxy, login page) is reported."""
self._set_api_config()
resp = mock.MagicMock()
resp.read.return_value = b"<html>Login</html>"
context = mock.MagicMock()
context.__enter__.return_value = resp
self._assert_user_error("unexpected response", return_value=context)
def test_dropped_connection_raises_user_error(self):
"""A connection dropped mid-response is reported."""
self._set_api_config()
self._assert_user_error(
"could not be reached",
side_effect=http.client.RemoteDisconnected("closed"),
)
self._assert_user_error(
"could not be reached",
side_effect=http.client.IncompleteRead(b""),
)
def test_malformed_email_is_refused(self):
"""Malformed and multiple email addresses are refused too."""
self._set_api_config()
for email in (" ", "not-an-email", "a@example.com; b@example.com"):
self.partner.email = email
with self._mock_api({"id": 64}), self.assertRaisesRegex(
UserError, "valid email"
):
self.template._create_submissions(self.partner)
self.assertFalse(self.requests)
def test_invalid_token_raises_user_error(self):
"""A token pasted with a line break is reported as a token problem,
not as an invalid URL."""
self._set_api_config()
self.env["ir.config_parameter"].sudo().set_param(
"docuseal.api_token", "abc\ndef"
)
with self.assertRaisesRegex(UserError, "API token"):
self.template._create_submissions(self.partner)
def test_error_without_message_names_the_exception(self):
"""An exception without message still explains what happened."""
self._set_api_config()
self._assert_user_error("TimeoutError", side_effect=TimeoutError())

View File

@@ -8,7 +8,7 @@
<list string="Docuseal templates"> <list string="Docuseal templates">
<field name="name"/> <field name="name"/>
<field name="template_id"/> <field name="template_id"/>
<field name="submitter_role"/> <field name="submitter_role_id"/>
<field name="server_action_id"/> <field name="server_action_id"/>
</list> </list>
</field> </field>
@@ -39,22 +39,33 @@
<sheet> <sheet>
<group> <group>
<field name="name"/> <field name="name"/>
<field name="template_id"/> <!-- Roles only exist once fetched from Docuseal: from
<field name="submitter_role"/> then on, another template needs a new entry. -->
</group> <field name="role_ids" invisible="1"/>
<div class="o_row mb8"> <field name="template_id" readonly="role_ids"/>
<button <button
colspan="2"
name="action_fetch_fields" name="action_fetch_fields"
string="Fetch template fields" string="Fetch from Docuseal"
type="object" type="object"
class="btn btn-secondary" class="btn btn-secondary mb8"
invisible="not template_id" invisible="not template_id"
/> />
</div> <field
name="submitter_role_id"
options="{'no_create': True, 'no_open': True}"
placeholder="Fetch from Docuseal to list the roles"
/>
</group>
<field name="field_ids" string="Field mapping"> <field name="field_ids" string="Field mapping">
<list editable="bottom"> <!-- Lines come from Docuseal only: no manual creation. -->
<list editable="bottom" create="0">
<field name="sequence" widget="handle"/> <field name="sequence" widget="handle"/>
<field name="docuseal_field_name" readonly="1"/> <field
name="docuseal_field_name"
readonly="1"
force_save="1"
/>
<field <field
name="partner_field_id" name="partner_field_id"
domain="[('model', '=', 'res.partner'), ('ttype', 'not in', ['one2many', 'many2many', 'binary'])]" domain="[('model', '=', 'res.partner'), ('ttype', 'not in', ['one2many', 'many2many', 'binary'])]"