[ADD] docuseal_signing: request Docuseal signatures from Odoo #1

Open
mondot wants to merge 15 commits from docuseal_signing into 18.0
5 changed files with 199 additions and 35 deletions
Showing only changes of commit f9a8358e95 - Show all commits

View File

@@ -1,2 +1,3 @@
from . import test_fetch_fields from . import test_fetch_fields
from . import test_server_action from . import test_server_action
from . import test_submissions

View File

@@ -0,0 +1,42 @@
import json
from unittest import mock
from odoo.addons.docuseal_signing.models import (
docuseal_template as docuseal_template_module,
)
class DocusealApiMockMixin:
"""Mock the Docuseal HTTP API, capturing every request made.
``_mock_api(response)`` returns a patcher for ``urlopen``; each
request lands in ``self.requests`` as a dict with ``url``,
``payload`` (decoded JSON body) and ``headers``.
"""
def _set_api_config(self, api_url="https://sign.example.com"):
params = self.env["ir.config_parameter"].sudo()
params.set_param("docuseal.api_token", "test-token")
params.set_param("docuseal.api_url", api_url)
def _mock_api(self, response):
self.requests = []
def fake_urlopen(req, timeout=None):
self.requests.append({
"url": req.full_url,
"payload": json.loads(req.data.decode()) if req.data else None,
"headers": dict(req.header_items()),
})
resp = mock.MagicMock()
resp.read.return_value = json.dumps(response).encode()
context = mock.MagicMock()
context.__enter__.return_value = resp
context.__exit__.return_value = False
return context
return mock.patch.object(
docuseal_template_module.urllib.request,
"urlopen",
side_effect=fake_urlopen,
)

View File

@@ -1,13 +1,9 @@
import json
from unittest import mock
from odoo.addons.docuseal_signing.models import (
docuseal_template as docuseal_template_module,
)
from odoo.tests import TransactionCase from odoo.tests import TransactionCase
from .common import DocusealApiMockMixin
class TestFetchFields(TransactionCase):
class TestFetchFields(DocusealApiMockMixin, TransactionCase):
"""Reconciliation of the field mapping on action_fetch_fields.""" """Reconciliation of the field mapping on action_fetch_fields."""
@classmethod @classmethod
@@ -31,14 +27,6 @@ class TestFetchFields(TransactionCase):
"docuseal_field_name": "obsolete", "docuseal_field_name": "obsolete",
}) })
def _mock_urlopen(self, payload):
resp = mock.MagicMock()
resp.read.return_value = json.dumps(payload).encode()
context_manager = mock.MagicMock()
context_manager.__enter__.return_value = resp
context_manager.__exit__.return_value = False
return context_manager
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
@@ -48,11 +36,7 @@ class TestFetchFields(TransactionCase):
"submitters": [{"name": "Signer"}], "submitters": [{"name": "Signer"}],
"fields": [{"name": "phone"}, {"name": "extra"}, {"name": ""}], "fields": [{"name": "phone"}, {"name": "extra"}, {"name": ""}],
} }
with mock.patch.object( with self._mock_api(payload):
docuseal_template_module.urllib.request,
"urlopen",
return_value=self._mock_urlopen(payload),
):
self.template.action_fetch_fields() self.template.action_fetch_fields()
names = { names = {
@@ -84,11 +68,7 @@ class TestFetchFields(TransactionCase):
"submitters": [{"name": "Counterparty"}], "submitters": [{"name": "Counterparty"}],
"fields": [], "fields": [],
} }
with mock.patch.object( with self._mock_api(payload):
docuseal_template_module.urllib.request,
"urlopen",
return_value=self._mock_urlopen(payload),
):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.assertEqual(self.template.name, "Contract") self.assertEqual(self.template.name, "Contract")
@@ -102,11 +82,7 @@ class TestFetchFields(TransactionCase):
"submitters": [{"name": "Signer"}], "submitters": [{"name": "Signer"}],
"fields": [{"name": "a"}, {"name": "b"}, {"name": "c"}], "fields": [{"name": "a"}, {"name": "b"}, {"name": "c"}],
} }
with mock.patch.object( with self._mock_api(payload):
docuseal_template_module.urllib.request,
"urlopen",
return_value=self._mock_urlopen(payload),
):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.assertEqual( self.assertEqual(
self.template.field_ids.mapped("docuseal_field_name"), self.template.field_ids.mapped("docuseal_field_name"),
@@ -119,11 +95,7 @@ class TestFetchFields(TransactionCase):
# Re-fetching must restore the Docuseal order. Invalidate the # Re-fetching must restore the Docuseal order. Invalidate the
# one2many cache to read like a fresh request would (the web # one2many cache to read like a fresh request would (the web
# client always re-reads after the action). # client always re-reads after the action).
with mock.patch.object( with self._mock_api(payload):
docuseal_template_module.urllib.request,
"urlopen",
return_value=self._mock_urlopen(payload),
):
self.template.action_fetch_fields() self.template.action_fetch_fields()
self.template.invalidate_recordset(["field_ids"]) self.template.invalidate_recordset(["field_ids"])
self.assertEqual( self.assertEqual(

View File

@@ -17,3 +17,22 @@ class TestServerAction(TransactionCase):
template.unlink() template.unlink()
self.assertFalse(action.exists()) self.assertFalse(action.exists())
def test_create_server_action_is_idempotent(self):
"""Creating the contextual action twice updates the existing
action instead of generating a duplicate."""
template = self.env["docuseal.template"].create({
"name": "Contract",
"template_id": 456,
})
template.action_create_server_action()
first_action = template.server_action_id
template.action_create_server_action()
self.assertEqual(template.server_action_id, first_action)
self.assertEqual(
self.env["ir.actions.server"].search_count([
("name", "=", "Request signature (Contract)"),
]),
1,
)

View File

@@ -0,0 +1,130 @@
from odoo.tests import TransactionCase
from .common import DocusealApiMockMixin
class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
"""Payload sent to the Docuseal API by _create_submissions."""
@classmethod
def setUpClass(cls):
super().setUpClass()
def partner_field(fname):
return cls.env["ir.model.fields"].search([
("model", "=", "res.partner"), ("name", "=", fname),
], limit=1)
cls.template = cls.env["docuseal.template"].create({
"name": "Onboarding",
"template_id": 777,
"submitter_role": "Signer",
})
for docuseal_name, fname in [
("full_name", "name"),
("email", "email"),
("company_type", "company_type"),
("birth_date", "create_date"),
("country", "country_id"),
("categories", "category_id"),
("phone", "phone"),
]:
cls.env["docuseal.template.field"].create({
"template_id": cls.template.id,
"docuseal_field_name": docuseal_name,
"partner_field_id": partner_field(fname).id,
})
cls.country = cls.env["res.country"].search([], limit=1)
cls.categories = cls.env["res.partner.category"].create([
{"name": "Gold"}, {"name": "Silver"},
])
cls.partner = cls.env["res.partner"].create({
"name": "Camille Dupont",
"email": "camille@example.com",
"phone": False,
"country_id": cls.country.id,
"category_id": cls.categories.ids,
})
def test_submission_payload_conversion(self):
"""Field values are converted per type and locked when set."""
self._set_api_config()
with self._mock_api({"id": 55}):
results = self.template._create_submissions(self.partner)
self.assertEqual(results, [{"id": 55}])
request = self.requests[0]
self.assertEqual(
request["url"], "https://sign.example.com/api/submissions"
)
self.assertIn("test-token", request["headers"].values())
payload = request["payload"]
self.assertEqual(payload["template_id"], 777)
self.assertTrue(payload["send_email"])
self.assertEqual(len(payload["submitters"]), 1)
submitter = payload["submitters"][0]
self.assertEqual(submitter["name"], "Camille Dupont")
self.assertEqual(submitter["email"], "camille@example.com")
self.assertEqual(submitter["role"], "Signer")
fields = {field["name"]: field for field in submitter["fields"]}
self.assertEqual(
fields["full_name"]["default_value"], "Camille Dupont"
)
self.assertTrue(fields["full_name"]["readonly"])
# selection: human-readable label, not the raw key
self.assertEqual(fields["company_type"]["default_value"], "Individual")
self.assertTrue(fields["company_type"]["readonly"])
# many2one / many2many: display names joined with ", "
self.assertEqual(
fields["country"]["default_value"], self.country.display_name
)
self.assertEqual(
fields["categories"]["default_value"],
", ".join(self.categories.mapped("display_name")),
)
# datetime: dd/mm/yyyy
self.assertEqual(
fields["birth_date"]["default_value"],
self.partner.create_date.strftime("%d/%m/%Y"),
)
# empty value: sent as "" and left editable for the signer
self.assertEqual(fields["phone"]["default_value"], "")
self.assertFalse(fields["phone"]["readonly"])
def test_draft_submissions_do_not_send_email(self):
"""_create_draft_submissions creates pre-filled submissions
without asking Docuseal to email the signers."""
self._set_api_config()
with self._mock_api({"id": 56}):
self.template._create_draft_submissions(self.partner)
self.assertFalse(self.requests[0]["payload"]["send_email"])
def test_one_submission_per_partner(self):
"""Each partner gets its own submission with a single submitter."""
self._set_api_config()
partner2 = self.env["res.partner"].create({"name": "Alex Martin"})
with self._mock_api({"id": 57}):
self.template._create_submissions(self.partner | partner2)
self.assertEqual(len(self.requests), 2)
for request in self.requests:
self.assertEqual(len(request["payload"]["submitters"]), 1)
self.assertEqual(
self.requests[1]["payload"]["submitters"][0]["name"],
"Alex Martin",
)
def test_api_url_trailing_slash(self):
"""A configured API URL with a trailing slash does not produce
a double slash in the request URL."""
self._set_api_config(api_url="https://sign.example.com/")
with self._mock_api({"id": 58}):
self.template._create_submissions(self.partner)
self.assertEqual(
self.requests[0]["url"],
"https://sign.example.com/api/submissions",
)