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__) 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 _fetch_docuseal_template(self): """Return the template definition from the Docuseal API.""" 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("/") if not api_token: raise UserError( _("Set the Docuseal API token in the General Settings first.") ) url = f"{api_url}/api/templates/{self.template_id}" req = urllib.request.Request(url, headers={"X-Auth-Token": api_token}) try: with urllib.request.urlopen(req, timeout=10) as resp: return json.loads(resp.read().decode()) except urllib.error.HTTPError as err: raise UserError( _( "Docuseal returned an error for template %(template)s: " "%(code)s %(reason)s", template=self.template_id, code=err.code, reason=err.reason, ) ) 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 _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"env['docuseal.template'].browse({self.id})" f"._create_submissions(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", } 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 _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() IrParam = self.env["ir.config_parameter"].sudo() api_token = IrParam.get_param("docuseal.api_token") api_url = IrParam.get_param( "docuseal.api_url", "https://sign.elabore.coop" ).rstrip("/") results = [] for partner in partners: 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 = json.dumps({ "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, }], }).encode() _logger.info( "Docuseal: creating submission for %s with template %s " "(send_email=%s), fields: %s", partner.name, self.template_id, send_email, submitter_fields, ) req = urllib.request.Request( f"{api_url}/api/submissions", data=payload, headers={ "X-Auth-Token": api_token, "Content-Type": "application/json", }, ) 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