[IMP] mail, mass_mailing: better recipientsz computation
authorThibault Delavallée <tde@openerp.com>
Tue, 15 Apr 2014 15:47:00 +0000 (17:47 +0200)
committerThibault Delavallée <tde@openerp.com>
Tue, 15 Apr 2014 15:47:00 +0000 (17:47 +0200)
for mass mailing, composer and template. This allows to have one method computing recipints
and avoid repetiting myself.

bzr revid: tde@openerp.com-20140415154700-zu2izvxfjq1k4h4a

addons/email_template/email_template.py
addons/email_template/wizard/mail_compose_message.py
addons/mail/mail_thread.py
addons/mail/wizard/mail_compose_message.py
addons/mass_mailing/models/mail_mail.py
addons/mass_mailing/models/mass_mailing.py
addons/mass_mailing/wizard/mail_compose_message.py

index 4eb01d5..dd9ed49 100644 (file)
@@ -401,13 +401,8 @@ class email_template(osv.osv):
         template = self.browse(cr, uid, template_id, context=context)
 
         if template.use_default_to or context.get('tpl_force_default_to'):
-            if template.model and hasattr(self.pool[template.model], 'message_get_default_recipients'):
-                default_recipients = self.pool[template.model].message_get_default_recipients(cr, uid, res_ids, context=context)
-            elif template.model:
-                ctx = dict(context, thread_model=template.model)
-                default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
-            else:
-                default_recipients = {}
+            ctx = dict(context, thread_model=template.model)
+            default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
             for res_id, recipients in default_recipients.iteritems():
                 results[res_id].pop('partner_to', None)
                 results[res_id].update(recipients)
index 00858e6..8bfc259 100644 (file)
@@ -152,7 +152,7 @@ class mail_compose_message(osv.TransientModel):
         returned_fields = fields + ['partner_ids', 'attachments']
         values = dict.fromkeys(res_ids, False)
 
-        ctx = dict(context, tpl_partners_only=True)
+        ctx = dict(context)
         template_values = self.pool.get('email.template').generate_email_batch(cr, uid, template_id, res_ids, fields=fields, context=ctx)
         for res_id in res_ids:
             res_id_values = dict((field, template_values[res_id][field]) for field in returned_fields if template_values[res_id].get(field))
@@ -172,16 +172,18 @@ class mail_compose_message(osv.TransientModel):
                 fields=['email_to', 'partner_to', 'email_cc', 'attachment_ids', 'mail_server_id'],
                 context=context)
         else:
-            template_values = dict.fromkeys(res_ids, dict())
+            template_values = {}
 
         for res_id in res_ids:
-            if wizard.template_id:
+            if template_values.get(res_id):
                 # recipients are managed by the template
                 composer_values[res_id].pop('partner_ids')
                 composer_values[res_id].pop('email_to')
                 composer_values[res_id].pop('email_cc')
-            # remove attachments from template values as they should not be rendered
-            template_values[res_id].pop('attachment_ids', None)
+                # remove attachments from template values as they should not be rendered
+                template_values[res_id].pop('attachment_ids', None)
+            else:
+                template_values[res_id] = dict()
             # update template values by composer values
             template_values[res_id].update(composer_values[res_id])
         return template_values
index a4bc800..53e4017 100644 (file)
@@ -662,14 +662,15 @@ class mail_thread(osv.AbstractModel):
     #------------------------------------------------------
 
     def message_get_default_recipients(self, cr, uid, ids, context=None):
-        model = self
-        if context and context.get('thread_model'):
-            model = self.pool[context['thread_model']]
+        if context and context.get('thread_model') and context['thread_model'] in self.pool and context['thread_model'] != self._name:
+            sub_ctx = dict(context)
+            sub_ctx.pop('thread_model')
+            return self.pool[context['thread_model']].message_get_default_recipients(cr, uid, ids, context=sub_ctx)
         res = {}
-        for record in model.browse(cr, SUPERUSER_ID, ids, context=context):
+        for record in self.browse(cr, SUPERUSER_ID, ids, context=context):
             recipient_ids, email_to, email_cc = set(), False, False
             if 'partner_id' in self._all_columns and record.partner_id:
-                recipient_ids.add(record.parent_id.id)
+                recipient_ids.add(record.partner_id.id)
             elif 'email_from' in self._all_columns and record.email_from:
                 email_to = record.email_from
             elif 'email' in self._all_columns:
index 842ddcb..e14a8f3 100644 (file)
@@ -324,13 +324,8 @@ class mail_compose_message(osv.TransientModel):
         emails_from = self.render_template_batch(cr, uid, wizard.email_from, wizard.model, res_ids, context=context)
         replies_to = self.render_template_batch(cr, uid, wizard.reply_to, wizard.model, res_ids, context=context)
 
-        if wizard.model and hasattr(self.pool[wizard.model], 'message_get_default_recipients'):
-            default_recipients = self.pool[wizard.model].message_get_default_recipients(cr, uid, res_ids, context=context)
-        elif wizard.model:
-            ctx = dict(context, thread_model=wizard.model)
-            default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
-        else:
-            default_recipients = {}
+        ctx = dict(context, thread_model=wizard.model)
+        default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
 
         results = dict.fromkeys(res_ids, False)
         for res_id in res_ids:
index d4aa1f3..e27156e 100644 (file)
@@ -33,6 +33,7 @@ class MailMail(osv.Model):
     _inherit = ['mail.mail']
 
     _columns = {
+        'mailing_id': fields.many2one('mail.mass_mailing', 'Mass Mailing'),
         'statistics_ids': fields.one2many(
             'mail.mail.statistics', 'mail_mail_id',
             string='Statistics',
@@ -59,6 +60,16 @@ class MailMail(osv.Model):
         )
         return '<img src="%s" alt=""/>' % track_url
 
+    def _get_unsubscribe_url(self, cr, uid, mail, email_to, msg=None, context=None):
+        base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
+        url = urlparse.urljoin(
+            base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
+                'mailing_id': mail.mailing_id.id,
+                'params': urllib.urlencode({'db': cr.dbname, 'res_id': mail.res_id, 'email': email_to})
+            }
+        )
+        return '<small><a href="%s">%s</a></small>' % (url, msg or 'Click to unsubscribe')
+
     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
         """ Override to add the tracking URL to the body. """
         body = super(MailMail, self).send_get_mail_body(cr, uid, mail, partner=partner, context=context)
@@ -70,6 +81,15 @@ class MailMail(osv.Model):
                 body = tools.append_content_to_html(body, tracking_url, plaintext=False, container_tag='div')
         return body
 
+    def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
+        res = super(MailMail, self).send_get_email_dict(cr, uid, mail, partner, context=context)
+        if mail.mailing_id and res.get('body'):
+            email_to = tools.email_split(res.get('email_to'))
+            unsubscribe_url = self._get_unsubscribe_url(cr, uid, mail, email_to, context=context)
+            if unsubscribe_url:
+                res['body'] = tools.append_content_to_html(res['body'], unsubscribe_url, plaintext=False, container_tag='p')
+        return res
+
     def _postprocess_sent_message(self, cr, uid, mail, context=None, mail_sent=True):
         if mail_sent is True and mail.statistics_ids:
             self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'sent': fields.datetime.now()}, context=context)
index cdbfab4..a8ae154 100644 (file)
@@ -552,16 +552,6 @@ class MassMailing(osv.Model):
             res_ids = random.sample(remaining, topick)
         return res_ids
 
-    def get_unsubscribe_url(self, cr, uid, mailing_id, res_id, email, msg=None, context=None):
-        base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
-        url = urlparse.urljoin(
-            base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
-                'mailing_id': mailing_id,
-                'params': urllib.urlencode({'db': cr.dbname, 'res_id': res_id, 'email': email})
-            }
-        )
-        return '<small><a href="%s">%s</a></small>' % (url, msg or 'Click to unsubscribe')
-
     def send_mail(self, cr, uid, ids, context=None):
         author_id = self.pool['res.users'].browse(cr, uid, uid, context=context).partner_id.id
         for mailing in self.browse(cr, uid, ids, context=context):
index 20a2c21..4aebff2 100644 (file)
@@ -1,25 +1,5 @@
 # -*- coding: utf-8 -*-
-##############################################################################
-#
-#    OpenERP, Open Source Management Solution
-#    Copyright (C) 2013-today OpenERP SA (<http://www.openerp.com>)
-#
-#    This program is free software: you can redistribute it and/or modify
-#    it under the terms of the GNU Affero General Public License as
-#    published by the Free Software Foundation, either version 3 of the
-#    License, or (at your option) any later version
-#
-#    This program is distributed in the hope that it will be useful,
-#    but WITHOUT ANY WARRANTY; without even the implied warranty of
-#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#    GNU Affero General Public License for more details
-#
-#    You should have received a copy of the GNU Affero General Public License
-#    along with this program.  If not, see <http://www.gnu.org/licenses/>
-#
-##############################################################################
 
-from openerp import tools
 from openerp.osv import osv, fields
 
 
@@ -62,17 +42,8 @@ class MailComposeMessage(osv.TransientModel):
                         'mailing_domain': wizard.active_domain,
                     }, context=context)
                 mass_mailing = self.pool['mail.mass_mailing'].browse(cr, uid, mass_mailing_id, context=context)
-            recipient_values = self.pool['mail.mass_mailing'].get_recipients_data(cr, uid, mass_mailing, res_ids, context=context)
             for res_id in res_ids:
-                mail_values = res[res_id]
-                recipient = recipient_values[res_id]
-                unsubscribe_url = self.pool['mail.mass_mailing'].get_unsubscribe_url(cr, uid, mass_mailing.id, res_id, recipient['email'], context=context)
-                if unsubscribe_url:
-                    mail_values['body_html'] = tools.append_content_to_html(mail_values['body_html'], unsubscribe_url, plaintext=False, container_tag='p')
-                mail_values.update({
-                    'email_to': '"%s" <%s>' % (recipient['name'], recipient['email'])
-                })
-                recipient = recipient_values[res_id]
+                res[res_id]['mailing_id'] = mass_mailing.id
                 res[res_id]['statistics_ids'] = [(0, 0, {
                     'model': wizard.model,
                     'res_id': res_id,