You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
6.5 KiB

  1. # Copyright 2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
  2. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  3. import logging
  4. from odoo import _, api, fields, models, tools
  5. from odoo.exceptions import UserError
  6. from odoo.tools import pycompat
  7. from odoo.addons.mail.models.mail_template import format_amount, format_date, format_tz
  8. _logger = logging.getLogger(__name__)
  9. FIELDS = ["body_html", "mail_server_id", "report_template"]
  10. try:
  11. from odoo.addons.mail.models.mail_template import (
  12. mako_safe_template_env,
  13. mako_template_env,
  14. )
  15. except ImportError:
  16. _logger.warning("jinja2 not available, templating features will not work!")
  17. class MailTemplate(models.Model):
  18. _inherit = ["mail.template", "website_dependent.mixin"]
  19. _name = "mail.template"
  20. body_html = fields.Html(company_dependent=True, website_dependent=True)
  21. mail_server_id = fields.Many2one(
  22. string="Outgoing Mail Server (Multi-Website)",
  23. company_dependent=True,
  24. website_dependent=True,
  25. )
  26. report_template = fields.Many2one(
  27. string="Optional report to print and attach (Multi-Website)",
  28. company_dependent=True,
  29. website_dependent=True,
  30. )
  31. @api.multi
  32. def generate_email(self, res_ids, fields=None):
  33. """Remove mail_server_id when not set to recompute in _default_mail_server_id in mail.message"""
  34. multi_mode = True
  35. if isinstance(res_ids, pycompat.integer_types):
  36. multi_mode = False
  37. res = super(MailTemplate, self).generate_email(res_ids, fields=fields)
  38. if not multi_mode:
  39. list_of_dict = {0: res}
  40. else:
  41. list_of_dict = res
  42. for _unused, data in list_of_dict.items():
  43. if "mail_server_id" in data and not data.get("mail_server_id"):
  44. del data["mail_server_id"]
  45. return res
  46. @api.model
  47. def render_template(self, template_txt, model, res_ids, post_process=False):
  48. """Override to add website to context"""
  49. multi_mode = True
  50. if isinstance(res_ids, pycompat.integer_types):
  51. multi_mode = False
  52. res_ids = [res_ids]
  53. results = dict.fromkeys(res_ids, u"")
  54. # try to load the template
  55. try:
  56. mako_env = (
  57. mako_safe_template_env
  58. if self.env.context.get("safe")
  59. else mako_template_env
  60. )
  61. template = mako_env.from_string(tools.ustr(template_txt))
  62. except Exception:
  63. _logger.info("Failed to load template %r", template_txt, exc_info=True)
  64. return multi_mode and results or results[res_ids[0]]
  65. # prepare template variables
  66. records = self.env[model].browse(
  67. it for it in res_ids if it
  68. ) # filter to avoid browsing [None]
  69. res_to_rec = dict.fromkeys(res_ids, None)
  70. for record in records:
  71. res_to_rec[record.id] = record
  72. variables = {
  73. "format_date": lambda date, format=False, context=self._context: format_date(
  74. self.env, date, format
  75. ),
  76. "format_tz": lambda dt, tz=False, format=False, context=self._context: format_tz(
  77. self.env, dt, tz, format
  78. ),
  79. "format_amount": lambda amount, currency, context=self._context: format_amount(
  80. self.env, amount, currency
  81. ),
  82. "user": self.env.user,
  83. "ctx": self._context, # context kw would clash with mako internals
  84. }
  85. # [NEW] Check website and company context
  86. company = self.env["res.company"] # empty value
  87. company_id = self.env.context.get("force_company")
  88. if company_id:
  89. company = self.env["res.company"].sudo().browse(company_id)
  90. if self.env.context.get("website_id"):
  91. website = self.env["website"].browse(self.env.context.get("website_id"))
  92. else:
  93. website = self.env.user.backend_website_id
  94. for res_id, record in res_to_rec.items():
  95. record_company = company
  96. if not record_company:
  97. if hasattr(record, "company_id") and record.company_id:
  98. record_company = record.company_id
  99. record_website = website
  100. if hasattr(record, "website_id") and record.website_id:
  101. record_website = record.website_id
  102. if (
  103. record_company
  104. and record_website
  105. and record_website.company_id != company
  106. ):
  107. # company and website are incompatible, so keep only company
  108. record_website = self.env["website"] # empty value
  109. record_context = dict(
  110. force_company=record_company.id, website_id=record_website.id
  111. )
  112. variables["object"] = record.with_context(**record_context)
  113. variables["website"] = record_website
  114. try:
  115. render_result = template.render(variables)
  116. except Exception:
  117. _logger.info(
  118. "Failed to render template %r using values %r"
  119. % (template, variables),
  120. exc_info=True,
  121. )
  122. raise UserError(
  123. _("Failed to render template %r using values %r")
  124. % (template, variables)
  125. )
  126. if render_result == u"False":
  127. render_result = u""
  128. if post_process:
  129. render_result = self.with_context(**record_context).render_post_process(
  130. render_result
  131. )
  132. results[res_id] = render_result
  133. return multi_mode and results or results[res_ids[0]]
  134. @api.model
  135. def create(self, vals):
  136. res = super(MailTemplate, self).create(vals)
  137. # make value company independent
  138. for f in FIELDS:
  139. res._force_default(f, vals.get(f))
  140. return res
  141. @api.multi
  142. def write(self, vals):
  143. res = super(MailTemplate, self).write(vals)
  144. # TODO: will it work with OCA's partner_firstname module?
  145. if "name" in vals:
  146. fields_to_update = FIELDS
  147. else:
  148. fields_to_update = [f for f in FIELDS if f in vals]
  149. for f in fields_to_update:
  150. self._update_properties_label(f)
  151. return res
  152. def _auto_init(self):
  153. for f in FIELDS:
  154. self._auto_init_website_dependent(f)
  155. return super(MailTemplate, self)._auto_init()