[FIX] mail: compose wizard: fixed subtype.
[odoo/odoo.git] / addons / mail / wizard / mail_compose_message.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU General Public License as published by
9 #    the Free Software Foundation, either version 3 of the License, or
10 #    (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 import base64
23 import re
24 from openerp import tools
25
26 from openerp.osv import osv
27 from openerp.osv import fields
28 from openerp.tools.safe_eval import safe_eval as eval
29 from openerp.tools.translate import _
30
31 # main mako-like expression pattern
32 EXPRESSION_PATTERN = re.compile('(\$\{.+?\})')
33
34
35 class mail_compose_message(osv.TransientModel):
36     """ Generic message composition wizard. You may inherit from this wizard
37         at model and view levels to provide specific features.
38
39         The behavior of the wizard depends on the composition_mode field:
40         - 'reply': reply to a previous message. The wizard is pre-populated
41             via ``get_message_data``.
42         - 'comment': new post on a record. The wizard is pre-populated via
43             ``get_record_data``
44         - 'mass_mail': wizard in mass mailing mode where the mail details can
45             contain template placeholders that will be merged with actual data
46             before being sent to each recipient.
47     """
48     _name = 'mail.compose.message'
49     _inherit = 'mail.message'
50     _description = 'Email composition wizard'
51     _log_access = True
52
53     def default_get(self, cr, uid, fields, context=None):
54         """ Handle composition mode. Some details about context keys:
55             - comment: default mode, model and ID of a record the user comments
56                 - default_model or active_model
57                 - default_res_id or active_id
58             - reply: active_id of a message the user replies to
59                 - default_parent_id or message_id or active_id: ID of the
60                     mail.message we reply to
61                 - message.res_model or default_model
62                 - message.res_id or default_res_id
63             - mass_mail: model and IDs of records the user mass-mails
64                 - active_ids: record IDs
65                 - default_model or active_model
66         """
67         if context is None:
68             context = {}
69         result = super(mail_compose_message, self).default_get(cr, uid, fields, context=context)
70
71         # get some important values from context
72         composition_mode = context.get('default_composition_mode', context.get('mail.compose.message.mode'))
73         model = context.get('default_model', context.get('active_model'))
74         res_id = context.get('default_res_id', context.get('active_id'))
75         message_id = context.get('default_parent_id', context.get('message_id', context.get('active_id')))
76         active_ids = context.get('active_ids')
77
78         # get default values according to the composition mode
79         if composition_mode == 'reply':
80             vals = self.get_message_data(cr, uid, message_id, context=context)
81         elif composition_mode == 'comment' and model and res_id:
82             vals = self.get_record_data(cr, uid, model, res_id, context=context)
83         elif composition_mode == 'mass_mail' and model and active_ids:
84             vals = {'model': model, 'res_id': res_id}
85         else:
86             vals = {'model': model, 'res_id': res_id}
87         if composition_mode:
88             vals['composition_mode'] = composition_mode
89
90         for field in vals:
91             if field in fields:
92                 result[field] = vals[field]
93
94         # TDE HACK: as mailboxes used default_model='res.users' and default_res_id=uid
95         # (because of lack of an accessible pid), creating a message on its own
96         # profile may crash (res_users does not allow writing on it)
97         # Posting on its own profile works (res_users redirect to res_partner)
98         # but when creating the mail.message to create the mail.compose.message
99         # access rights issues may rise
100         # We therefore directly change the model and res_id
101         if result.get('model') == 'res.users' and result.get('res_id') == uid:
102             result['model'] = 'res.partner'
103             result['res_id'] = self.pool.get('res.users').browse(cr, uid, uid).partner_id.id
104         return result
105
106     def _get_composition_mode_selection(self, cr, uid, context=None):
107         return [('comment', 'Comment a document'), ('reply', 'Reply to a message'), ('mass_mail', 'Mass mailing')]
108
109     _columns = {
110         'composition_mode': fields.selection(
111             lambda s, *a, **k: s._get_composition_mode_selection(*a, **k),
112             string='Composition mode'),
113         'partner_ids': fields.many2many('res.partner',
114             'mail_compose_message_res_partner_rel',
115             'wizard_id', 'partner_id', 'Additional contacts'),
116         'notify': fields.boolean('Notify followers',
117             help='Notify followers of the documents.'),
118         'post': fields.boolean('Post',
119             help='Post a copy of the message on the document communication history.'),
120         'same_thread': fields.boolean('Reply in the document',
121             help='Replies to the messages will go into the selected document.'),
122         'attachment_ids': fields.many2many('ir.attachment',
123             'mail_compose_message_ir_attachments_rel',
124             'wizard_id', 'attachment_id', 'Attachments'),
125         'filter_id': fields.many2one('ir.filters', 'Filters'),
126     }
127
128     _defaults = {
129         'composition_mode': 'comment',
130         'body': lambda self, cr, uid, ctx={}: '',
131         'subject': lambda self, cr, uid, ctx={}: False,
132         'partner_ids': lambda self, cr, uid, ctx={}: [],
133         'notify': lambda self, cr, uid, ctx={}: False,
134         'post': lambda self, cr, uid, ctx={}: True,
135         'same_thread': lambda self, cr, uid, ctx={}: True,
136     }
137
138     def _notify(self, cr, uid, newid, context=None):
139         """ Override specific notify method of mail.message, because we do
140             not want that feature in the wizard. """
141         return
142
143     def get_record_data(self, cr, uid, model, res_id, context=None):
144         """ Returns a defaults-like dict with initial values for the composition
145             wizard when sending an email related to the document record
146             identified by ``model`` and ``res_id``.
147
148             :param str model: model name of the document record this mail is
149                 related to.
150             :param int res_id: id of the document record this mail is related to
151         """
152         doc_name_get = self.pool.get(model).name_get(cr, uid, [res_id], context=context)
153         if doc_name_get:
154             record_name = doc_name_get[0][1]
155         else:
156             record_name = False
157         return {'model': model, 'res_id': res_id, 'record_name': record_name}
158
159     def get_message_data(self, cr, uid, message_id, context=None):
160         """ Returns a defaults-like dict with initial values for the composition
161             wizard when replying to the given message (e.g. including the quote
162             of the initial message, and the correct recipients).
163
164             :param int message_id: id of the mail.message to which the user
165                 is replying.
166         """
167         if not message_id:
168             return {}
169         if context is None:
170             context = {}
171         message_data = self.pool.get('mail.message').browse(cr, uid, message_id, context=context)
172
173         # create subject
174         re_prefix = _('Re:')
175         reply_subject = tools.ustr(message_data.subject or '')
176         if not (reply_subject.startswith('Re:') or reply_subject.startswith(re_prefix)) and message_data.subject:
177             reply_subject = "%s %s" % (re_prefix, reply_subject)
178         # get partner_ids from original message
179         partner_ids = [partner.id for partner in message_data.partner_ids] if message_data.partner_ids else []
180         partner_ids += context.get('default_partner_ids', [])
181
182         # update the result
183         result = {
184             'record_name': message_data.record_name,
185             'model': message_data.model,
186             'res_id': message_data.res_id,
187             'parent_id': message_data.id,
188             'subject': reply_subject,
189             'partner_ids': partner_ids,
190         }
191         return result
192
193     #------------------------------------------------------
194     # Wizard validation and send
195     #------------------------------------------------------
196
197     def send_mail(self, cr, uid, ids, context=None):
198         """ Process the wizard content and proceed with sending the related
199             email(s), rendering any template patterns on the fly if needed. """
200         if context is None:
201             context = {}
202         active_ids = context.get('active_ids')
203
204         for wizard in self.browse(cr, uid, ids, context=context):
205             mass_mail_mode = wizard.composition_mode == 'mass_mail'
206             active_model_pool = self.pool.get(wizard.model if wizard.model else 'mail.thread')
207
208             # wizard works in batch mode: [res_id] or active_ids
209             res_ids = active_ids if mass_mail_mode and wizard.model and active_ids else [wizard.res_id]
210             for res_id in res_ids:
211                 # default values, according to the wizard options
212                 post_values = {
213                     'subject': wizard.subject,
214                     'body': wizard.body,
215                     'parent_id': wizard.parent_id and wizard.parent_id.id,
216                     'partner_ids': [(4, partner.id) for partner in wizard.partner_ids],
217                     'attachments': [(attach.datas_fname or attach.name, base64.b64decode(attach.datas)) for attach in wizard.attachment_ids],
218                 }
219                 # mass mailing: render and override default values
220                 if mass_mail_mode and wizard.model:
221                     email_dict = self.render_message(cr, uid, wizard, res_id, context=context)
222                     new_partner_ids = email_dict.pop('partner_ids', [])
223                     post_values['partner_ids'] += [(4, partner_id) for partner_id in new_partner_ids]
224                     new_attachments = email_dict.pop('attachments', [])
225                     post_values['attachments'] += new_attachments
226                     post_values.update(email_dict)
227                     # email_from: mass mailing only can specify another email_from
228                     if email_dict.get('email_from'):
229                         post_values['email_from'] = email_dict.pop('email_from')
230                     # replies redirection: mass mailing only
231                     if not wizard.same_thread:
232                         post_values['reply_to'] = email_dict.pop('reply_to')
233                 # automatically subscribe recipients if asked to
234                 if context.get('mail_post_autofollow') and wizard.model and post_values.get('partner_ids'):
235                     active_model_pool.message_subscribe(cr, uid, [res_id], [item[1] for item in post_values.get('partner_ids')], context=context)
236                 # post the message
237                 if mass_mail_mode and not wizard.post:
238                     post_values['recipient_ids'] = post_values.pop('partner_ids')
239                     self.pool.get('mail.mail').create(cr, uid, post_values, context=context)
240                 else:
241                     subtype = 'mail.mt_comment'
242                     if mass_mail_mode and not wizard.notify:
243                         subtype = False
244                     msg_id = active_model_pool.message_post(cr, uid, [res_id], type='comment', subtype=subtype, context=context, **post_values)
245                     # mass_mailing, post without notify: notify specific partners
246                     if mass_mail_mode and not wizard.notify and post_values['partner_ids']:
247                         self.pool.get('mail.notification')._notify(cr, uid, msg_id, [item[1] for item in post_values['partner_ids']], context=context)
248
249         return {'type': 'ir.actions.act_window_close'}
250
251     def render_message(self, cr, uid, wizard, res_id, context=None):
252         """ Generate an email from the template for given (wizard.model, res_id)
253             pair. This method is meant to be inherited by email_template that
254             will produce a more complete dictionary. """
255         return {
256             'subject': self.render_template(cr, uid, wizard.subject, wizard.model, res_id, context),
257             'body': self.render_template(cr, uid, wizard.body, wizard.model, res_id, context),
258             'email_from': self.render_template(cr, uid, wizard.email_from, wizard.model, res_id, context),
259             'reply_to': self.render_template(cr, uid, wizard.reply_to, wizard.model, res_id, context),
260         }
261
262     def render_template(self, cr, uid, template, model, res_id, context=None):
263         """ Render the given template text, replace mako-like expressions ``${expr}``
264             with the result of evaluating these expressions with an evaluation context
265             containing:
266
267                 * ``user``: browse_record of the current user
268                 * ``object``: browse_record of the document record this mail is
269                               related to
270                 * ``context``: the context passed to the mail composition wizard
271
272             :param str template: the template text to render
273             :param str model: model name of the document record this mail is related to.
274             :param int res_id: id of the document record this mail is related to.
275         """
276         if context is None:
277             context = {}
278
279         def merge(match):
280             exp = str(match.group()[2:-1]).strip()
281             result = eval(exp, {
282                 'user': self.pool.get('res.users').browse(cr, uid, uid, context=context),
283                 'object': self.pool.get(model).browse(cr, uid, res_id, context=context),
284                 'context': dict(context),  # copy context to prevent side-effects of eval
285                 })
286             return result and tools.ustr(result) or ''
287         return template and EXPRESSION_PATTERN.sub(merge, template)