From a094095ef3c0be08adfaee69f9865465e3813d46 Mon Sep 17 00:00:00 2001 From: Adrian Torres Date: Fri, 26 Jan 2018 16:02:24 +0100 Subject: [PATCH] [IMP] mail: check if template can be rendered on write (#20834) * [IMP] mail: check if template can be rendered on write Before this commit, whenever a user would send an email from a template containing mako python expressions and those expressions contained syntax errors, the mail would still be sent but the body would be empty, this was intended behavior but due to an increase in complaints of empty mails being sent, the behavior was reviewed. This commit improves on this behavior by: 1. Rendering the template on write (save) 2. Checking if the template rendered successfully 3. Raising a UserError if the rendering failed The end result is a modal box showing an error to the user whenever he either saves an mail.template with python syntax error in mako snippers or when a mail with mako snippets is rendered on-the-fly (wizard). --- addons/mail/models/mail_template.py | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/addons/mail/models/mail_template.py b/addons/mail/models/mail_template.py index e0e16eeef7c..5dfaf162573 100644 --- a/addons/mail/models/mail_template.py +++ b/addons/mail/models/mail_template.py @@ -237,6 +237,37 @@ class MailTemplate(models.Model): self.sub_model_object_field = False self.null_value = False + @api.multi + def write(self, vals): + # This override is for checking that the template is correct when + # saving it + if vals.get('body_html'): + # render_template can return empty results if the mako rendering + # crashes or if the body_html is empty, therefore we will only + # perform this check if the new body_html is non-empty + if vals.get('model_id'): + _model = self.env['ir.model'].sudo().browse( + vals['model_id']).model + else: + _model = self.model + + Model = self.env[_model] + if not Model._abstract: + # Get the latest record so as to not use older, potentially + # deprecated/obsolete records + res_ids = Model.search([], limit=1, order='id DESC').ids[:1] + if res_ids: + render = self.render_template( + vals['body_html'], _model, res_ids) + + if not any(render.values()): + raise UserError(_( + "Template rendering failed, this could mean that " + "your template contains python syntax errors" + )) + + return super(MailTemplate, self).write(vals) + @api.multi def unlink(self): self.unlink_action()