Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions partner_communication/models/communication_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from io import BytesIO
from urllib.parse import urlparse

from lxml import etree, html

from odoo import Command, _, api, fields, models, tools
from odoo.exceptions import UserError
from odoo.tools import html2plaintext
Expand Down Expand Up @@ -254,6 +256,18 @@ class CommunicationJob(models.Model):
)

sms_cost = fields.Float()
signature_user_id = fields.Many2one(
"res.users",
compute="_compute_signature_user_id",
readonly=False,
help="Technical field: user whose signature is in the text being edited, "
"to replace it when the sender changes in the form.",
)

def _compute_signature_user_id(self):
# No dependency on purpose: keeps the previous sender in the form
for job in self:
job.signature_user_id = job.user_id

def _compute_ir_attachments(self):
for job in self:
Expand Down Expand Up @@ -613,8 +627,23 @@ def write(self, vals):
# The attachments depend on the send mode: regenerate them
vals["attachments_object_ids"] = False

# Only used by the form (see _onchange_user_id_signature)
vals.pop("signature_user_id", None)
# The text holds the signature of the sender: follow a sender change
new_bodies = {}
if vals.get("user_id"):
new_user = self.env["res.users"].browse(vals["user_id"])
for job in self.filtered(lambda j: j.user_id != new_user):
body = vals.get("body_html", job.body_html)
new_body = job._replace_sender_signature(body, job.user_id, new_user)
if new_body != body:
new_bodies[job] = new_body

super().write(vals)

for job, body in new_bodies.items():
job.write({"body_html": body})

if vals.get("body_html") or vals.get("send_mode") == "physical":
self.count_pdf_page()

Expand Down Expand Up @@ -779,6 +808,58 @@ def _replace_link(match):
text = re.sub(r" {2,}", " ", sanitize_gsm7(text))
return "\n".join([t.strip() for t in text.split("\n")])

def _replace_sender_signature(self, body, old_user, new_user):
"""Return the text with the signature of old_user replaced by the one
of new_user. The rest of the text, possibly written by hand, is kept.
The text is returned unchanged if the old signature is not in it
(removed or edited by hand, or no signature for this send mode).
"""
self.ensure_one()
lang = self.partner_id.lang
old_sig = str(old_user.with_context(lang=lang).signature or "")
new_sig = str(new_user.with_context(lang=lang).signature or "")
if not body or not old_sig.strip() or old_sig == new_sig:
return body
# Markup.replace() would escape the signatures: work on plain text
body = str(body)
if old_sig in body:
return body.replace(old_sig, new_sig)
# The text editor rewrites the HTML when the text is edited: find the
# signature by its text instead.
try:
root = html.fragment_fromstring(body, create_parent="div")
old_nodes = html.fragments_fromstring(old_sig)
new_nodes = html.fragments_fromstring(new_sig) if new_sig.strip() else []
except (etree.ParserError, ValueError):
return body
if len(old_nodes) != 1 or isinstance(old_nodes[0], str):
return body
old_text = " ".join(old_nodes[0].text_content().split())
if not old_text:
return body
match = next(
(
el
for el in root.iter(old_nodes[0].tag)
if " ".join(el.text_content().split()) == old_text
),
None,
)
if match is None:
return body
if not new_nodes:
# New sender without signature: keep the text that follows it
match.drop_tree()
else:
if len(new_nodes) == 1 and not isinstance(new_nodes[0], str):
new_el = new_nodes[0]
else:
new_el = html.fragment_fromstring(new_sig, create_parent="div")
new_el.tail = match.tail
match.getparent().replace(match, new_el)
# Remove the <div> added around the text by the parser
return html.tostring(root, encoding="unicode")[len("<div>") : -len("</div>")]

def refresh_text(self):
"""Regenerate the text. The attachments are only regenerated if the
resources of the communication changed since they were generated.
Expand Down Expand Up @@ -823,6 +904,15 @@ def quick_refresh(self):
)
return True

@api.onchange("user_id")
def _onchange_user_id_signature(self):
old_user = self.signature_user_id or self._origin.user_id
if old_user and self.user_id and old_user != self.user_id:
self.body_html = self._replace_sender_signature(
self.body_html, old_user, self.user_id
)
self.signature_user_id = self.user_id

@api.onchange("config_id", "partner_id")
def onchange_config_id(self):
self.user_id = self.config_id.user_id or self.env.user
Expand Down
1 change: 1 addition & 0 deletions partner_communication/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
#
##############################################################################
from . import test_ir_actions_report
from . import test_sender_signature
106 changes: 106 additions & 0 deletions partner_communication/tests/test_sender_signature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import re

from odoo.tests import Form
from odoo.tests.common import TransactionCase, tagged


@tagged("post_install", "-at_install")
class TestSenderSignature(TransactionCase):
"""The signature at the end of a communication follows its sender."""

@classmethod
def setUpClass(cls):
super().setUpClass()
users = cls.env["res.users"].with_context(no_reset_password=True)
signature_is_stored = not users._fields["signature"].compute
cls.users = []
for name in ("Alice Sender", "Bruno Sender", "Carla Sender"):
vals = {"name": name, "login": name.lower().replace(" ", ".")}
if signature_is_stored:
vals["signature"] = (
f"<table><tr><td><b>{name}</b></td></tr>"
"<tr><td>Compassion</td></tr></table>"
)
user = users.create(vals)
if "hr.employee" in cls.env:
# Signatures built from the employee data (name, job, photo)
cls.env["hr.employee"].create(
{"name": name, "user_id": user.id, "job_title": "Tester"}
)
cls.users.append(user)
cls.user_a, cls.user_b, cls.user_c = cls.users
cls.partner = cls.env["res.partner"].create(
{"name": "Signature Test Partner", "email": "sig@example.com"}
)
cls.config = cls.env.ref("partner_communication.default_communication")

def _signature(self, user):
return str(user.with_context(lang=self.partner.lang).signature)

def _new_job(self):
job = self.env["partner.communication.job"].create(
{
"config_id": self.config.id,
"partner_id": self.partner.id,
"object_ids": self.partner.id,
"user_id": self.user_a.id,
"send_mode": "digital",
}
)
# Text generated from the template first, as for a real communication
self.assertTrue(job.body_html)
job.body_html = (
"<p>Hello</p><p>Text written for the sponsor.</p>"
f"<p>{self._signature(self.user_a)}</p>"
)
return job

def test_signatures_differ(self):
self.assertNotEqual(self._signature(self.user_a), self._signature(self.user_b))

def test_sender_change_replaces_signature(self):
job = self._new_job()
job.user_id = self.user_b
self.assertIn(self._signature(self.user_b), job.body_html)
self.assertNotIn(self._signature(self.user_a), job.body_html)
self.assertIn("Text written for the sponsor.", job.body_html)

def test_sender_change_with_text_edited_in_editor(self):
"""The editor rewrites the HTML: the signature is found by its text."""
job = self._new_job()
edited = re.sub(
r">\s*<",
">\n <",
str(job.body_html).replace(
"<p>Hello</p>", '<p data-oe-version="1.2">Hi</p>'
),
)
self.assertNotIn(self._signature(self.user_a), edited)
job.write({"user_id": self.user_b.id, "body_html": edited})
self.assertIn("Hi", job.body_html)
self.assertIn("Text written for the sponsor.", job.body_html)
self.assertIn(self.user_b.name, job.body_html)
self.assertNotIn(self.user_a.name, job.body_html)

def test_signature_removed_by_hand_is_kept_removed(self):
job = self._new_job()
body = "<p>Hello</p><p>No signature here.</p>"
job.body_html = body
job.user_id = self.user_b
self.assertEqual(job.body_html, body)

def test_sender_change_in_form_updates_text_before_saving(self):
job = self._new_job()
with Form(job) as form:
form.user_id = self.user_b
self.assertIn(self.user_b.name, form.body_html)
self.assertNotIn(self.user_a.name, form.body_html)
# Several changes before saving: each one replaces the previous
form.user_id = self.user_c
self.assertIn(self.user_c.name, form.body_html)
self.assertNotIn(self.user_b.name, form.body_html)
self.assertEqual(job.user_id, self.user_c)
self.assertIn(self.user_c.name, job.body_html)
self.assertNotIn(self.user_a.name, job.body_html)
self.assertNotIn(self.user_b.name, job.body_html)
self.assertIn("Text written for the sponsor.", job.body_html)
1 change: 1 addition & 0 deletions partner_communication/views/communication_job_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
readonly="state in ('processing', 'done')"
/>
<field name="user_id" readonly="state == 'done'" />
<field name="signature_user_id" invisible="1" />
<field
name="partner_id"
readonly="state in ('processing', 'done')"
Expand Down
Loading