[FIX] mail: model can be None or uninstalled
[odoo/odoo.git] / addons / mail / wizard / mail_compose_message.py
index 43259d3..4fc7de7 100644 (file)
@@ -68,11 +68,14 @@ class mail_compose_message(osv.TransientModel):
         result = super(mail_compose_message, self).default_get(cr, uid, fields, context=context)
 
         # v6.1 compatibility mode
-        result['composition_mode'] = result.get('composition_mode', context.get('mail.compose.message.mode'))
+        result['composition_mode'] = result.get('composition_mode', context.get('mail.compose.message.mode', 'comment'))
         result['model'] = result.get('model', context.get('active_model'))
         result['res_id'] = result.get('res_id', context.get('active_id'))
         result['parent_id'] = result.get('parent_id', context.get('message_id'))
 
+        if not result['model'] or not self.pool.get(result['model']) or not hasattr(self.pool[result['model']], 'message_post'):
+            result['no_auto_thread'] = True
+
         # default values according to composition mode - NOTE: reply is deprecated, fall back on comment
         if result['composition_mode'] == 'reply':
             result['composition_mode'] = 'comment'
@@ -82,7 +85,6 @@ class mail_compose_message(osv.TransientModel):
             vals['active_domain'] = '%s' % context.get('active_domain')
         if result['composition_mode'] == 'comment':
             vals.update(self.get_record_data(cr, uid, result, context=context))
-        result['recipients_data'] = self.get_recipients_data(cr, uid, result, context=context)
 
         for field in vals:
             if field in fields:
@@ -98,6 +100,9 @@ class mail_compose_message(osv.TransientModel):
         if result['model'] == 'res.users' and result['res_id'] == uid:
             result['model'] = 'res.partner'
             result['res_id'] = self.pool.get('res.users').browse(cr, uid, uid).partner_id.id
+
+        if fields is not None:
+            [result.pop(field, None) for field in result.keys() if field not in fields]
         return result
 
     def _get_composition_mode_selection(self, cr, uid, context=None):
@@ -112,8 +117,6 @@ class mail_compose_message(osv.TransientModel):
         'partner_ids': fields.many2many('res.partner',
             'mail_compose_message_res_partner_rel',
             'wizard_id', 'partner_id', 'Additional Contacts'),
-        'recipients_data': fields.text(string='Recipients Data',
-            help='Helper field used in mass mailing to display a sample of recipients'),
         'use_active_domain': fields.boolean('Use active domain'),
         'active_domain': fields.char('Active domain', readonly=True),
         'attachment_ids': fields.many2many('ir.attachment',
@@ -124,16 +127,12 @@ class mail_compose_message(osv.TransientModel):
         # mass mode options
         'notify': fields.boolean('Notify followers',
             help='Notify followers of the document (mass post only)'),
-        'same_thread': fields.boolean('Replies in the document',
-            help='Replies to the messages will go into the selected document (mass mail only)'),
     }
-    #TODO change same_thread to False in trunk (Require view update)
     _defaults = {
         'composition_mode': 'comment',
         'body': lambda self, cr, uid, ctx={}: '',
         'subject': lambda self, cr, uid, ctx={}: False,
         'partner_ids': lambda self, cr, uid, ctx={}: [],
-        'same_thread': True,
     }
 
     def check_access_rule(self, cr, uid, ids, operation, context=None):
@@ -164,23 +163,6 @@ class mail_compose_message(osv.TransientModel):
             not want that feature in the wizard. """
         return
 
-    def get_recipients_data(self, cr, uid, values, context=None):
-        """ Returns a string explaining the targetted recipients, to ease the use
-        of the wizard. """
-        composition_mode, model, res_id = values['composition_mode'], values['model'], values['res_id']
-        if composition_mode == 'comment' and model and res_id:
-            doc_name = self.pool[model].name_get(cr, uid, [res_id], context=context)
-            return doc_name and 'Followers of %s' % doc_name[0][1] or False
-        elif composition_mode == 'mass_post' and model:
-            if 'active_domain' in context:
-                active_ids = self.pool[model].search(cr, uid, eval(context['active_domain']), limit=100, context=context)
-            else:
-                active_ids = context.get('active_ids', list())
-            if active_ids:
-                name_gets = [rec_name[1] for rec_name in self.pool[model].name_get(cr, uid, active_ids[:3], context=context)]
-                return 'Followers of selected documents (' + ', '.join(name_gets) + len(active_ids) > 3 and ', ...' or '' + ')'
-        return False
-
     def get_record_data(self, cr, uid, values, context=None):
         """ Returns a defaults-like dict with initial values for the composition
         wizard when sending an email related a previous email (parent_id) or
@@ -220,10 +202,8 @@ class mail_compose_message(osv.TransientModel):
     def send_mail(self, cr, uid, ids, context=None):
         """ Process the wizard content and proceed with sending the related
             email(s), rendering any template patterns on the fly if needed. """
-        if context is None:
-            context = {}
-        # import datetime
-        # print '--> beginning sending email', datetime.datetime.now()
+        context = dict(context or {})
+
         # clean the context (hint: mass mailing sets some default values that
         # could be wrongly interpreted by mail_mail)
         context.pop('default_email_to', None)
@@ -244,10 +224,9 @@ class mail_compose_message(osv.TransientModel):
             else:
                 res_ids = [wizard.res_id]
 
-            # print '----> before computing values', datetime.datetime.now()
-            # print '----> after computing values', datetime.datetime.now()
+            batch_size = int(self.pool['ir.config_parameter'].get_param(cr, SUPERUSER_ID, 'mail.batch_size')) or self._batch_size
 
-            sliced_res_ids = [res_ids[i:i + self._batch_size] for i in range(0, len(res_ids), self._batch_size)]
+            sliced_res_ids = [res_ids[i:i + batch_size] for i in range(0, len(res_ids), batch_size)]
             for res_ids in sliced_res_ids:
                 all_mail_values = self.get_mail_values(cr, uid, wizard, res_ids, context=context)
                 for res_id, mail_values in all_mail_values.iteritems():
@@ -263,7 +242,6 @@ class mail_compose_message(osv.TransientModel):
                                            mail_create_nosubscribe=True)  # add context key to avoid subscribing the author
                         active_model_pool.message_post(cr, uid, [res_id], type='comment', subtype=subtype, context=context, **mail_values)
 
-        # print '--> finished sending email', datetime.datetime.now()
         return {'type': 'ir.actions.act_window_close'}
 
     def get_mail_values(self, cr, uid, wizard, res_ids, context=None):
@@ -276,10 +254,10 @@ class mail_compose_message(osv.TransientModel):
         # render all template-based value at once
         if mass_mail_mode and wizard.model:
             rendered_values = self.render_message_batch(cr, uid, wizard, res_ids, context=context)
-
-        # # get default recipients for mass mailing
-        # if mass_mail_mode 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)
+        # compute alias-based reply-to in batch
+        reply_to_value = dict.fromkeys(res_ids, None)
+        if mass_mail_mode and not wizard.no_auto_thread:
+            reply_to_value = self.pool['mail.thread'].message_get_reply_to(cr, uid, res_ids, default=wizard.email_from, context=dict(context, thread_model=wizard.model))
 
         for res_id in res_ids:
             # static wizard (mail.message) values
@@ -292,6 +270,7 @@ class mail_compose_message(osv.TransientModel):
                 'author_id': wizard.author_id.id,
                 'email_from': wizard.email_from,
                 'record_name': wizard.record_name,
+                'no_auto_thread': wizard.no_auto_thread,
             }
             # mass mailing: rendering override wizard static values
             if mass_mail_mode and wizard.model:
@@ -302,20 +281,17 @@ class mail_compose_message(osv.TransientModel):
                     mail_values['auto_delete'] = context.get('mail_auto_delete')
                 # rendered values using template
                 email_dict = rendered_values[res_id]
-                print email_dict
                 mail_values['partner_ids'] += email_dict.pop('partner_ids', [])
                 mail_values.update(email_dict)
-                if wizard.same_thread:
+                if not wizard.no_auto_thread:
                     mail_values.pop('reply_to')
-                elif not mail_values.get('reply_to'):
+                    if reply_to_value.get(res_id):
+                        mail_values['reply_to'] = reply_to_value[res_id]
+                if wizard.no_auto_thread and not mail_values.get('reply_to'):
                     mail_values['reply_to'] = mail_values['email_from']
                 # mail_mail values: body -> body_html, partner_ids -> recipient_ids
                 mail_values['body_html'] = mail_values.get('body', '')
                 mail_values['recipient_ids'] = [(4, id) for id in mail_values.pop('partner_ids', [])]
-                # add some specific recipients depending on the model, to be sure some are mailed
-                if default_recipients.get(res_id):
-                    mail_values['recipient_ids'] += [(4, id) for id in default_recipients[res_id]['recipient_ids']]
-                    mail_values['email_to'] = ','.join(filter(None, [mail_values.get('email_to', ''), default_recipients[res_id]['email_to']]))
 
                 # process attachments: should not be encoded before being processed by message_post / mail_mail create
                 mail_values['attachments'] = [(name, base64.b64decode(enc_cont)) for name, enc_cont in email_dict.pop('attachments', list())]
@@ -326,7 +302,7 @@ class mail_compose_message(osv.TransientModel):
                 mail_values['attachment_ids'] = self.pool['mail.thread']._message_preprocess_attachments(
                     cr, uid, mail_values.pop('attachments', []),
                     attachment_ids, 'mail.message', 0, context=context)
-                print mail_values
+
             results[res_id] = mail_values
         return results
 
@@ -343,6 +319,10 @@ class mail_compose_message(osv.TransientModel):
         once, and render it multiple times. This is useful for mass mailing where
         template rendering represent a significant part of the process.
 
+        Default recipients are also computed, based on mail_thread method
+        message_get_default_recipients. This allows to ensure a mass mailing has
+        always some recipients specified.
+
         :param browse wizard: current mail.compose.message browse record
         :param list res_ids: list of record ids
 
@@ -354,6 +334,9 @@ 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)
 
+        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:
             results[res_id] = {
@@ -362,6 +345,7 @@ class mail_compose_message(osv.TransientModel):
                 'email_from': emails_from[res_id],
                 'reply_to': replies_to[res_id],
             }
+            results[res_id].update(default_recipients.get(res_id, dict()))
         return results
 
     def render_template_batch(self, cr, uid, template, model, res_ids, context=None, post_process=False):