import ast import base64 from odoo import _, fields, models from odoo.exceptions import ValidationError from odoo.tools import pycompat class MailTemplate(models.Model): """Extended to add features of redner api""" _inherit = "mail.template" is_redner_template = fields.Boolean( string="Is redner template?", default=False, help="Check this box if this template is a redner. " "If it's not checked , it assumes that the default " "email template odoo to be used.", ) redner_tmpl_id = fields.Many2one( comodel_name="redner.template", string="Redner template", domain=[("active", "=", True)], ) redner_substitution_ids = fields.One2many( comodel_name="redner.substitution", inverse_name="template_id", string="Substitutions", ) def action_get_substitutions(self): """Call by: action button `Get Substitutions from Redner Template`""" self.ensure_one() if self.redner_tmpl_id: keywords = self.redner_tmpl_id.get_keywords() # Get current substitutions subs = self.redner_substitution_ids.mapped("keyword") or [] values = [] for key in keywords: # check to avoid duplicate keys if key not in subs: values.append((0, 0, {"keyword": key})) self.write({"redner_substitution_ids": values}) # remove obsolete keywords in substitutions model if len(self.redner_substitution_ids) > len(keywords): deprecated_keys = self.redner_substitution_ids.filtered( lambda s: s.keyword not in keywords ) if len(deprecated_keys) > 0: deprecated_keys.unlink() def _patch_email_values(self, values, res_id): # get redner template values values_sent_to_redner = {} for sub in self.redner_substitution_ids: value = self.render_template(sub.value, self.model, res_id) if sub.deserialize: value = ast.literal_eval(value) values_sent_to_redner[sub.keyword] = value try: res = self.redner_tmpl_id.redner.templates.render( self.redner_tmpl_id.redner_id, values_sent_to_redner ) except Exception as e: if isinstance(e, ValidationError): raise raise ValidationError( _( "We received an unexpected error from redner server. " "Please contact your administrator" ) ) values["body_html"] = ( base64.b64decode(res[0]["body"]).decode("utf-8") if res else "" ) values["body"] = values["body_html"] return values def generate_email(self, res_ids, fields=None): self.ensure_one() results = super(MailTemplate, self).generate_email( res_ids, fields=fields ) if not self.is_redner_template: return results multi_mode = True if isinstance(res_ids, pycompat.integer_types): res_ids = [res_ids] multi_mode = False if multi_mode: return { res_id: self._patch_email_values(values, res_id) for res_id, values in results.items() } return self._patch_email_values(results, res_ids[0])