import http.client import json import logging import urllib.error import urllib.request from odoo import Command, _, api, fields, models from odoo.exceptions import UserError from odoo.tools.mail import email_normalize _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. It cannot be changed once fetched from " "Docuseal: to use another template, create a new entry.", 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)]", # 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( 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", # 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): 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() if send_email: # Check every partner before the first call, so that no request # is sent when one of them cannot receive it. # email_normalize refuses empty, malformed and multiple addresses. 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 = [] 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": email_normalize(partner.email) or partner.email or "", "fields": submitter_fields, }], } # Do not log the field values (personal data) nor the response: # it contains the signing links of the submitters. _logger.info( "Docuseal: creating submission for res.partner %s with " "template %s (send_email=%s)", partner.id, self.template_id, send_email, ) results.append(self._docuseal_request("/api/submissions", payload)) return results