[ADD] sale_async_emails: allow sending order status emails asynchronously

This commit adds a new module to allow delaying the sending of sales
order confirmation emails, thus removing a performance bottleneck in the
order confirmation flow.

This is particularly useful for "flash" sales in which a large number of
event tickets are sold in a very short time span. When the emails are
scheduled to be sent right away, the email rendering that is part of the
payment post-processing keeps the worker busy. When the system parameter
`sale.async_emails` is set to `True`, the email rendering is delegated
to a cron, allowing the payment post-processing to execute much faster.

task-3782827

closes odoo/odoo#157612

Signed-off-by: Antoine Vandevenne (anv) <anv@odoo.com>
This commit is contained in:
Antoine Vandevenne (anv)
2024-04-15 16:21:47 +00:00
parent 9f319cbc95
commit f0016849c1
8 changed files with 167 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import models
+14
View File
@@ -0,0 +1,14 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Sales - Async Emails",
'category': 'Sales/Sales',
'summary': "Send order status emails asynchronously",
'depends': ['sale'],
'data': [
'data/ir_config_parameter.xml',
'data/ir_cron.xml',
],
'auto_install': True,
'license': 'LGPL-3',
}
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<odoo noupdate="1">
<record id="async_emails" model="ir.config_parameter">
<field name="key">sale.async_emails</field>
<field name="value">False</field>
</record>
</odoo>
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo noupdate="1">
<record id="sale_async_emails.cron" model="ir.cron">
<field name="name">Sales: Send pending emails</field>
<field name="model_id" ref="model_sale_order"/>
<field name="state">code</field>
<field name="code">model._cron_send_pending_emails()</field>
<field name="user_id" ref="base.user_root"/>
<field name="interval_number">1</field>
<field name="interval_type">days</field>
<field name="numbercall">-1</field>
<field name="active">True</field>
</record>
</odoo>
@@ -0,0 +1,3 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import sale_order
@@ -0,0 +1,45 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.misc import str2bool
class SaleOrder(models.Model):
_inherit = 'sale.order'
pending_email_template_id = fields.Many2one(
string="Pending Email Template",
help="The template of the pending email that must be sent asynchronously.",
comodel_name='mail.template',
ondelete='set null',
readonly=True,
)
def _send_order_notification_mail(self, mail_template):
""" Override of `sale` to reschedule order status emails to be sent asynchronously. """
async_send = str2bool(self.env['ir.config_parameter'].sudo().get_param('sale.async_emails'))
cron = async_send and self.env.ref('sale_async_emails.cron', raise_if_not_found=False)
if async_send and cron and not self.env.context.get('is_async_email', False):
# Schedule the email to be sent asynchronously.
self.pending_email_template_id = mail_template
cron._trigger()
else: # We are in the cron job, or the user has disabled async emails.
super()._send_order_notification_mail(mail_template) # Send the email synchronously.
@api.model
def _cron_send_pending_emails(self, auto_commit=True):
""" Find and send pending order status emails asynchronously.
:param bool auto_commit: Whether the database cursor should be committed as soon as an email
is sent. Set to False in unit tests.
:return: None
"""
pending_email_orders = self.search([('pending_email_template_id', '!=', False)])
for order in pending_email_orders:
order = order[0] # Avoid pre-fetching after each cache invalidation due to committing.
order.with_context(is_async_email=True)._send_order_notification_mail(
order.pending_email_template_id
) # Asynchronously resume the email sending.
order.pending_email_template_id = None
if auto_commit:
self.env.cr.commit() # Save progress in case the cron is killed.
@@ -0,0 +1,3 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import test_sale_order
@@ -0,0 +1,74 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.tests import tagged
from odoo.addons.sale.tests.common import SaleCommon
@tagged('post_install', '-at_install')
class TestSaleOrder(SaleCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.async_emails_cron = cls.env.ref('sale_async_emails.cron')
cls.confirmation_email_template = cls.sale_order._get_confirmation_template()
def test_order_status_email_is_sent_asynchronously(self):
""" Test that the order status email is sent asynchronously when configured. """
self.env['ir.config_parameter'].set_param('sale.async_emails', 'True')
with patch(
'odoo.addons.sale.models.sale_order.SaleOrder._send_order_notification_mail'
) as sync_email_send_mock:
self.sale_order._send_order_notification_mail(self.confirmation_email_template)
self.assertTrue(
self.sale_order.pending_email_template_id,
msg="The email template should be saved on the sales order.",
)
self.assertTrue(
self.env['ir.cron.trigger'].search_count(
[('cron_id', '=', self.async_emails_cron.id)]
),
msg="The asynchronous email sending cron should be triggered.",
)
self.assertEqual(
sync_email_send_mock.call_count,
0,
msg="The email should not also be sent synchronously.",
)
def test_order_status_email_is_sent_synchronously_if_not_configured(self):
""" Test that the order status email is sent synchronously when nothing is configured. """
self.env['ir.config_parameter'].set_param('sale.async_emails', 'False')
with patch(
'odoo.addons.sale.models.sale_order.SaleOrder._send_order_notification_mail'
) as sync_email_send_mock:
self.sale_order._send_order_notification_mail(self.confirmation_email_template)
self.assertEqual(
sync_email_send_mock.call_count,
1,
msg="The email should be sent synchronously when the system parameter is not set.",
)
def test_async_emails_cron_does_not_trigger_itself(self):
""" Test that the asynchronous email sending cron does not enter an infinite loop. """
self.env['ir.config_parameter'].set_param('sale.async_emails', 'True')
self.sale_order.pending_email_template_id = self.confirmation_email_template
with patch(
'odoo.addons.sale.models.sale_order.SaleOrder._send_order_notification_mail'
) as sync_email_send_mock:
self.env['sale.order']._cron_send_pending_emails(auto_commit=False)
self.assertFalse(
self.sale_order.pending_email_template_id,
msg="The email template should be removed from the sales order.",
)
self.assertEqual(
sync_email_send_mock.call_count,
1,
msg="The email should be sent synchronously when requested by the cron.",
)