import json import logging import urllib.request from odoo import fields, models _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 ) submitter_role = fields.Char( string="Submitter role", help="Name of the submitter role you have set up in 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 action_fetch_fields(self): 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") 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: self.name = data["name"] if data.get("submitters") and not self.submitter_role: self.submitter_role = data["submitters"][0].get("name", "") self.field_ids.unlink() fields_data = [ {"template_id": self.id, "docuseal_field_name": f["name"]} for f in data.get("fields", []) if f.get("name") ] if fields_data: self.env["docuseal.template.field"].create(fields_data) 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 _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") 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 value is False or value is None: 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 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