Files
docuseal-tools/docuseal_signing/models/docuseal_template.py
Quentin Mondot 87653552b1
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 50s
[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>
2026-11-09 17:04:23 +01:00

344 lines
13 KiB
Python

import json
import logging
import urllib.error
import urllib.request
from odoo import Command, _, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
DEFAULT_API_URL = "https://sign.elabore.coop"
class DocusealTemplate(models.Model):
_name = "docuseal.template"
_description = "Docuseal Template"
name = fields.Char(string="Name")
template_id = fields.Integer(
string="Template ID",
help="You can find the template id in the URL when you have selected the template in Docuseal.",
required=True
)
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",
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",
inverse_name="template_id",
string="Fields",
)
server_action_id = fields.Many2one(
comodel_name="ir.actions.server",
string="Server action",
readonly=True,
ondelete="set null",
)
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"
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 %(code)s: %(detail)s",
code=err.code,
detail=self._docuseal_error_detail(err),
)
) 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 _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):
self.ensure_one()
data = self._fetch_docuseal_template()
if data.get("name") and not self.name:
self.name = data["name"]
self._sync_roles(data.get("submitters", []))
# 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
}
for index, name in enumerate(docuseal_names):
field = existing.get(name)
if field:
field.sequence = index
else:
self.env["docuseal.template.field"].create({
"template_id": self.id,
"docuseal_field_name": name,
"sequence": index,
})
self.field_ids.filtered(
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(
[("model", "=", "res.partner")], limit=1
)
code = (
f"action = env['docuseal.template'].browse({self.id})"
f"._action_request_signature(records)"
)
vals = {
"name": f"Request signature ({self.name or self.template_id})",
"model_id": partner_model.id,
"state": "code",
"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)
else:
self.server_action_id = self.env["ir.actions.server"].create(vals)
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"title": _("Action created"),
"message": _("Contextual action created on res.partner."),
"type": "success",
},
}
def action_delete_server_action(self):
self.ensure_one()
if self.server_action_id:
self.server_action_id.unlink()
self.server_action_id = False
def unlink(self):
# Remove the generated contextual action: an action left behind
# would browse a deleted template at runtime.
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."""
return self._create_submissions(partners, send_email=False)
def _create_submissions(self, partners, send_email=True):
self.ensure_one()
results = []
for partner in partners:
submitter_fields = []
for field_map in self.field_ids:
if not field_map.partner_field_id:
continue
field_name = field_map.partner_field_id.name
value = partner[field_name]
if hasattr(value, "strftime"):
value = value.strftime("%d/%m/%Y")
elif isinstance(value, models.BaseModel):
value = ", ".join(value.mapped("display_name"))
elif value is False or value is None:
value = ""
elif partner._fields[field_name].type == "selection":
selection = partner._fields[field_name]._description_selection(
partner.env
)
value = str(dict(selection).get(value, value))
else:
value = str(value)
# Lock pre-filled values so the signer cannot change them;
# empty values stay editable for the signer to fill in.
submitter_fields.append({
"name": field_map.docuseal_field_name,
"default_value": value,
"readonly": bool(value),
})
payload = {
"template_id": self.template_id,
"send_email": send_email,
"submitters": [{
"name": partner.name,
"role": self.submitter_role_id.name or "",
"email": partner.email or "",
"fields": submitter_fields,
}],
}
_logger.info(
"Docuseal: creating submission for %s with template %s "
"(send_email=%s), fields: %s",
partner.name,
self.template_id,
send_email,
submitter_fields,
)
result = self._docuseal_request("/api/submissions", payload)
_logger.info(
"Docuseal submission created for %s: %s", partner.name, result
)
results.append(result)
return results