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.

76 lines
3.0 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016-2017 Compassion CH (http://www.compassion.ch)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from odoo import models, fields, api
  5. from collections import defaultdict
  6. class EmailTemplate(models.Model):
  7. _inherit = 'mail.template'
  8. substitution_ids = fields.One2many(
  9. 'sendgrid.substitution', 'email_template_id', 'Substitutions')
  10. sendgrid_template_ids = fields.One2many(
  11. 'sendgrid.email.lang.template', 'email_template_id',
  12. 'Sendgrid Templates')
  13. sendgrid_localized_template = fields.Many2one(
  14. 'sendgrid.template', compute='_compute_localized_template')
  15. def _compute_localized_template(self):
  16. lang = self.env.context.get('lang', 'en_US')
  17. for template in self:
  18. lang_template = template.sendgrid_template_ids.filtered(
  19. lambda t: t.lang == lang)
  20. if lang_template and len(lang_template) == 1:
  21. template.sendgrid_localized_template = \
  22. lang_template.sendgrid_template_id
  23. @api.multi
  24. def update_substitutions(self):
  25. for template in self:
  26. new_substitutions = []
  27. for language_template in template.sendgrid_template_ids:
  28. sendgrid_template = language_template.sendgrid_template_id
  29. lang = language_template.lang
  30. substitutions = template.substitution_ids.filtered(
  31. lambda s: s.lang == lang)
  32. keywords = sendgrid_template.get_keywords()
  33. # Add new keywords from the sendgrid template
  34. for key in keywords:
  35. if key not in substitutions.mapped('key'):
  36. substitution_vals = {
  37. 'key': key,
  38. 'lang': lang,
  39. 'email_template_id': template.id
  40. }
  41. new_substitutions.append((0, 0, substitution_vals))
  42. template.write({'substitution_ids': new_substitutions})
  43. return True
  44. @api.multi
  45. def render_substitutions(self, res_ids):
  46. """
  47. :param res_ids: resource ids for rendering the template
  48. Returns values for substitutions in a mail.message creation
  49. :return:
  50. Values for mail creation (for each resource id given)
  51. {res_id: list of substitutions values [0, 0 {substitution_vals}]}
  52. """
  53. self.ensure_one()
  54. if isinstance(res_ids, (int, long)):
  55. res_ids = [res_ids]
  56. substitutions = self.substitution_ids.filtered(
  57. lambda s: s.lang == self.env.context.get('lang', 'en_US'))
  58. substitution_vals = defaultdict(list)
  59. for substitution in substitutions:
  60. values = self.render_template(
  61. substitution.value, self.model, res_ids)
  62. for res_id in res_ids:
  63. substitution_vals[res_id].append((0, 0, {
  64. 'key': substitution.key,
  65. 'value': values[res_id]
  66. }))
  67. return substitution_vals