[FIX] mail: model can be None or uninstalled
[odoo/odoo.git] / addons / mail / wizard / mail_compose_message.py
index 367597d..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,62 +163,37 @@ 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 to the document record
-            identified by ``model`` and ``res_id``.
-
-            :param values: dictionary of default and already computed values for the mail_compose_message_res_partner_re
-            :type values: dict"""
+        wizard when sending an email related a previous email (parent_id) or
+        a document (model, res_id). This is based on previously computed default
+        values. """
         if context is None:
             context = {}
-        model, res_id, parent_id = values.get('model'), values.get('res_id'), values.get('parent_id')
-        record_name, subject, partner_ids = values.get('record_name'), values.get('subject'), values.get('partner_ids', list())
-        if parent_id:
-            message_data = self.pool.get('mail.message').browse(cr, uid, parent_id, context=context)
-            record_name = message_data.record_name,
-            subject = tools.ustr(message_data.subject or message_data.record_name or '')
-            if not model:
-                model = message_data.model
-            if not res_id:
-                res_id = message_data.res_id
-            # get partner_ids from original message
-            partner_ids += [partner.id for partner in message_data.partner_ids]
-            if context.get('is_private') and message_data.author_id:  # check message is private then add author also in partner list.
-                partner_ids += [message_data.author_id.id]
-            # create subject
-            re_prefix = _('Re:')
-            if not (subject.startswith('Re:') or subject.startswith(re_prefix)):
-                subject = "%s %s" % (re_prefix, subject)
-        elif model and res_id:
-            doc_name_get = self.pool[model].name_get(cr, uid, [res_id], context=context)
-            record_name = doc_name_get and doc_name_get[0][1] or ''
-            subject = tools.ustr(record_name)
-
-        return {
-            'record_name': record_name,
-            'subject': subject,
-            'partner_ids': list(set(partner_ids)),
-            'model': model,
-            'res_id': res_id,
-        }
+        result, subject = {}, False
+        if values.get('parent_id'):
+            parent = self.pool.get('mail.message').browse(cr, uid, values.get('parent_id'), context=context)
+            result['record_name'] = parent.record_name,
+            subject = tools.ustr(parent.subject or parent.record_name or '')
+            if not values.get('model'):
+                result['model'] = parent.model
+            if not values.get('res_id'):
+                result['res_id'] = parent.res_id
+            partner_ids = values.get('partner_ids', list()) + [partner.id for partner in parent.partner_ids]
+            if context.get('is_private') and parent.author_id:  # check message is private then add author also in partner list.
+                partner_ids += [parent.author_id.id]
+            result['partner_ids'] = partner_ids
+        elif values.get('model') and values.get('res_id'):
+            doc_name_get = self.pool[values.get('model')].name_get(cr, uid, [values.get('res_id')], context=context)
+            result['record_name'] = doc_name_get and doc_name_get[0][1] or ''
+            subject = tools.ustr(result['record_name'])
+
+        re_prefix = _('Re:')
+        if subject and not (subject.startswith('Re:') or subject.startswith(re_prefix)):
+            subject = "%s %s" % (re_prefix, subject)
+        result['subject'] = subject
+
+        return result
 
     #------------------------------------------------------
     # Wizard validation and send
@@ -228,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)
@@ -252,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():
@@ -271,18 +242,22 @@ 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):
         """Generate the values that will be used by send_mail to create mail_messages
         or mail_mails. """
         results = dict.fromkeys(res_ids, False)
+        rendered_values, default_recipients = {}, {}
         mass_mail_mode = wizard.composition_mode == 'mass_mail'
 
         # 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)
+        # 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
@@ -295,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:
@@ -306,13 +282,16 @@ class mail_compose_message(osv.TransientModel):
                 # rendered values using template
                 email_dict = rendered_values[res_id]
                 mail_values['partner_ids'] += email_dict.pop('partner_ids', [])
-                if wizard.same_thread:
-                    email_dict.pop('reply_to', None)
-                else:
-                    mail_values['reply_to'] = email_dict.pop('reply_to', None)
-                # if not mail_values.get('reply_to'):
-                #     mail_values['reply_to'] = mail_values['email_from']
                 mail_values.update(email_dict)
+                if not wizard.no_auto_thread:
+                    mail_values.pop('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', [])]
 
                 # 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())]
@@ -323,9 +302,6 @@ 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)
-                # 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', [])]
 
             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):