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.

138 lines
6.9 KiB

  1. # -*- coding: utf-8 -*-
  2. ################################################################
  3. # License, author and contributors information in: #
  4. # __openerp__.py file at the root folder of this module. #
  5. ################################################################
  6. import base64
  7. import logging
  8. from openerp import api, fields, models
  9. from openerp import tools
  10. from openerp import report as odoo_report
  11. _logger = logging.getLogger(__name__)
  12. class MailTemplate(models.Model):
  13. _inherit = 'mail.template'
  14. email_bcc = fields.Char(string='Bcc',
  15. help='Blind carbon copy message recipients')
  16. @api.multi
  17. def generate_email(self, res_ids, fields=None):
  18. """Generates an email from the template for given the given model based on
  19. records given by res_ids.
  20. :param template_id: id of the template to render.
  21. :param res_id: id of the record to use for rendering the template (model
  22. is taken from template definition)
  23. :returns: a dict containing all relevant fields for creating a new
  24. mail.mail entry, with one extra key ``attachments``, in the
  25. format [(report_name, data)] where data is base64 encoded.
  26. """
  27. self.ensure_one()
  28. multi_mode = True
  29. if isinstance(res_ids, (int, long)):
  30. res_ids = [res_ids]
  31. multi_mode = False
  32. if fields is None:
  33. fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']
  34. fields = fields + ['email_bcc']
  35. res_ids_to_templates = self.get_email_template_batch(res_ids)
  36. # templates: res_id -> template; template -> res_ids
  37. templates_to_res_ids = {}
  38. for res_id, template in res_ids_to_templates.iteritems():
  39. templates_to_res_ids.setdefault(template, []).append(res_id)
  40. results = dict()
  41. for template, template_res_ids in templates_to_res_ids.iteritems():
  42. Template = self.env['mail.template']
  43. # generate fields value for all res_ids linked to the current template
  44. if template.lang:
  45. Template = Template.with_context(lang=template._context.get('lang'))
  46. for field in fields:
  47. Template = Template.with_context(safe=field in {'subject'})
  48. generated_field_values = Template.render_template(
  49. getattr(template, field), template.model, template_res_ids,
  50. post_process=(field == 'body_html'))
  51. for res_id, field_value in generated_field_values.iteritems():
  52. results.setdefault(res_id, dict())[field] = field_value
  53. # compute recipients
  54. if any(field in fields for field in ['email_to', 'partner_to', 'email_cc']):
  55. results = template.generate_recipients(results, template_res_ids)
  56. # update values for all res_ids
  57. for res_id in template_res_ids:
  58. values = results[res_id]
  59. # body: add user signature, sanitize
  60. if 'body_html' in fields and template.user_signature:
  61. signature = self.env.user.signature
  62. if signature:
  63. values['body_html'] = tools.append_content_to_html(values['body_html'], signature, plaintext=False)
  64. if values.get('body_html'):
  65. values['body'] = tools.html_sanitize(values['body_html'])
  66. # technical settings
  67. values.update(
  68. mail_server_id=template.mail_server_id.id or False,
  69. auto_delete=template.auto_delete,
  70. model=template.model,
  71. res_id=res_id or False,
  72. attachment_ids=[attach.id for attach in template.attachment_ids],
  73. )
  74. # Add report in attachments: generate once for all template_res_ids
  75. if template.report_template and not 'report_template_in_attachment' in self.env.context:
  76. for res_id in template_res_ids:
  77. attachments = []
  78. report_name = self.render_template(template.report_name, template.model, res_id)
  79. report = template.report_template
  80. report_service = report.report_name
  81. if report.report_type in ['qweb-html', 'qweb-pdf']:
  82. result, format = self.pool['report'].get_pdf(self._cr, self._uid, [res_id], report_service, context=Template._context), 'pdf'
  83. else:
  84. result, format = odoo_report.render_report(self._cr, self._uid, [res_id], report_service, {'model': template.model}, Template._context)
  85. # TODO in trunk, change return format to binary to match message_post expected format
  86. result = base64.b64encode(result)
  87. if not report_name:
  88. report_name = 'report.' + report_service
  89. ext = "." + format
  90. if not report_name.endswith(ext):
  91. report_name += ext
  92. attachments.append((report_name, result))
  93. results[res_id]['attachments'] = attachments
  94. return multi_mode and results or results[res_ids[0]]
  95. @api.multi
  96. def generate_recipients(self, results, res_ids):
  97. """Generates the recipients of the template. Default values can ben generated
  98. instead of the template values if requested by template or context.
  99. Emails (email_to, email_cc) can be transformed into partners if requested
  100. in the context. """
  101. self.ensure_one()
  102. if self.use_default_to or self._context.get('tpl_force_default_to'):
  103. default_recipients = self.env['mail.thread'].message_get_default_recipients(res_model=self.model, res_ids=res_ids)
  104. for res_id, recipients in default_recipients.iteritems():
  105. results[res_id].pop('partner_to', None)
  106. results[res_id].update(recipients)
  107. for res_id, values in results.iteritems():
  108. partner_ids = values.get('partner_ids', list())
  109. if self._context.get('tpl_partners_only'):
  110. mails = tools.email_split(values.pop('email_to', '')) + tools.email_split(values.pop('email_cc', '')) + tools.email_split(values.pop('email_bcc', ''))
  111. for mail in mails:
  112. partner_id = self.env['res.partner'].find_or_create(mail)
  113. partner_ids.append(partner_id)
  114. partner_to = values.pop('partner_to', '')
  115. if partner_to:
  116. # placeholders could generate '', 3, 2 due to some empty field values
  117. tpl_partner_ids = [int(pid) for pid in partner_to.split(',') if pid]
  118. partner_ids += self.env['res.partner'].sudo().browse(tpl_partner_ids).exists().ids
  119. results[res_id]['partner_ids'] = partner_ids
  120. return results