From 879db1975c737567c08ca444eedb128931a50fdd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fernanda=20Hern=C3=A1ndez?= <fernanda@vauxoo.com>
Date: Fri, 16 Feb 2024 20:16:47 +0000
Subject: [PATCH] [FIX] mail: lock mail.mail record before sending email

In this line:

https://github.com/odoo/odoo/blob/c58a34294112b9d156fd563c207aaaacb1a90eb5/addons/mail/models/mail_mail.py#L730

The changes applied in mail.mail sending the email
are applied, if there is another process at the same
time updating the same record, that is going
to raise a concurrence error. The problem with this
is the email went out already, but in Odoo, it keeps
as `outgoing`, causing multiple emails went out
for same record in Odoo.

This commit adds a `flush_recordset` before to
send the email, if there is another process trying
to update the same record, it will be blocked and
it must wait to sending email process finishes.
The mail record will be updated as `sent`.
---
 addons/mail/models/mail_mail.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/addons/mail/models/mail_mail.py b/addons/mail/models/mail_mail.py
index b03ca0a37b1d7..f3bbc49411f28 100644
--- a/addons/mail/models/mail_mail.py
+++ b/addons/mail/models/mail_mail.py
@@ -333,6 +333,7 @@ def _send(self, auto_commit=False, raise_exception=False, smtp_session=None):
                     'state': 'exception',
                     'failure_reason': _('Error without exception. Probably due do sending an email without computed recipients.'),
                 })
+                mail.flush()
                 # Update notification in a transient exception state to avoid concurrent
                 # update in case an email bounces while sending all emails related to current
                 # mail record.