[MERGE] fix a dependence in portal and reorganize xml
[odoo/odoo.git] / addons / email_template / email_template.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2009 Sharoon Thomas
6 #    Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
20 #
21 ##############################################################################
22
23 import base64
24 import logging
25
26 import netsvc
27 from osv import osv
28 from osv import fields
29 import tools
30 from tools.translate import _
31 from urllib import quote as quote
32 _logger = logging.getLogger(__name__)
33
34 try:
35     from mako.template import Template as MakoTemplate
36 except ImportError:
37     _logger.warning("email_template: mako templates not available, templating features will not work!")
38
39 class email_template(osv.osv):
40     "Templates for sending email"
41     _inherit = 'mail.message'
42     _name = "email.template"
43     _description = 'Email Templates'
44     _rec_name = 'name' # override mail.message's behavior
45
46     def render_template(self, cr, uid, template, model, res_id, context=None):
47         """Render the given template text, replace mako expressions ``${expr}``
48            with the result of evaluating these expressions with
49            an evaluation context containing:
50
51                 * ``user``: browse_record of the current user
52                 * ``object``: browse_record of the document record this mail is
53                               related to
54                 * ``context``: the context passed to the mail composition wizard
55
56            :param str template: the template text to render
57            :param str model: model name of the document record this mail is related to.
58            :param int res_id: id of the document record this mail is related to.
59         """
60         if not template: return u""
61         if context is None:
62             context = {}
63         try:
64             template = tools.ustr(template)
65             record = None
66             if res_id:
67                 record = self.pool.get(model).browse(cr, uid, res_id, context=context)
68             user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
69             result = MakoTemplate(template).render_unicode(object=record,
70                                                            user=user,
71                                                            # context kw would clash with mako internals
72                                                            ctx=context,
73                                                            quote=quote,
74                                                            format_exceptions=True)
75             if result == u'False':
76                 result = u''
77             return result
78         except Exception:
79             _logger.exception("failed to render mako template value %r", template)
80             return u""
81
82     def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
83         if context is None:
84             context = {}
85         if not template_id:
86             return False
87         template = self.browse(cr, uid, template_id, context)
88         lang = self.render_template(cr, uid, template.lang, template.model, record_id, context)
89         if lang:
90             # Use translated template if necessary
91             ctx = context.copy()
92             ctx['lang'] = lang
93             template = self.browse(cr, uid, template.id, ctx)
94         else:
95             template = self.browse(cr, uid, int(template_id), context)
96         return template
97
98     def onchange_model_id(self, cr, uid, ids, model_id, context=None):
99         mod_name = False
100         if model_id:
101             mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
102         return {'value':{'model': mod_name}}
103
104     def name_get(self, cr, uid, ids, context=None):
105         """ Override name_get of mail.message: return directly the template
106             name, and not the generated name from mail.message.common."""
107         return [(record.id, record.name) for record in self.browse(cr, uid, ids, context=context)]
108
109     _columns = {
110         'name': fields.char('Name', size=250),
111         'model_id': fields.many2one('ir.model', 'Related document model'),
112         'lang': fields.char('Language Selection', size=250,
113                             help="Optional translation language (ISO code) to select when sending out an email. "
114                                  "If not set, the english version will be used. "
115                                  "This should usually be a placeholder expression "
116                                  "that provides the appropriate language code, e.g. "
117                                  "${object.partner_id.lang.code}."),
118         'user_signature': fields.boolean('Add Signature',
119                                          help="If checked, the user's signature will be appended to the text version "
120                                               "of the message"),
121         'report_name': fields.char('Report Filename', size=200, translate=True,
122                                    help="Name to use for the generated report file (may contain placeholders)\n"
123                                         "The extension can be omitted and will then come from the report type."),
124         'report_template':fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
125         'ref_ir_act_window':fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
126                                             help="Sidebar action to make this template available on records "
127                                                  "of the related document model"),
128         'ref_ir_value':fields.many2one('ir.values', 'Sidebar Button', readonly=True,
129                                        help="Sidebar button to open the sidebar action"),
130         'track_campaign_item': fields.boolean('Resource Tracking',
131                                               help="Enable this is you wish to include a special tracking marker "
132                                                    "in outgoing emails so you can identify replies and link "
133                                                    "them back to the corresponding resource record. "
134                                                    "This is useful for CRM leads for example"),
135
136         # Overridden mail.message.common fields for technical reasons:
137         'model': fields.related('model_id','model', type='char', string='Related Document Model',
138                                 size=128, select=True, store=True, readonly=True),
139         # we need a separate m2m table to avoid ID collisions with the original mail.message entries
140         'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
141                                            'attachment_id', 'Files to attach',
142                                            help="You may attach files to this template, to be added to all "
143                                                 "emails created from this template"),
144
145         # Overridden mail.message.common fields to make tooltips more appropriate:
146         'subject':fields.char('Subject', size=512, translate=True, help="Subject (placeholders may be used here)",),
147         'email_from': fields.char('From', size=128, help="Sender address (placeholders may be used here)"),
148         'email_to': fields.char('To', size=256, help="Comma-separated recipient addresses (placeholders may be used here)"),
149         'email_cc': fields.char('Cc', size=256, help="Carbon copy recipients (placeholders may be used here)"),
150         'email_bcc': fields.char('Bcc', size=256, help="Blind carbon copy recipients (placeholders may be used here)"),
151         'reply_to': fields.char('Reply-To', size=250, help="Preferred response address (placeholders may be used here)"),
152         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
153                                           help="Optional preferred server for outgoing mails. If not set, the highest "
154                                                "priority one will be used."),
155         'body_text': fields.text('Text Contents', translate=True, help="Plaintext version of the message (placeholders may be used here)"),
156         'body_html': fields.text('Rich-text Contents', translate=True, help="Rich-text/HTML version of the message (placeholders may be used here)"),
157         'message_id': fields.char('Message-Id', size=256, help="Message-ID SMTP header to use in outgoing messages based on this template. "
158                                                                "Please note that this overrides the 'Resource Tracking' option, "
159                                                                "so if you simply need to track replies to outgoing emails, enable "
160                                                                "that option instead.\n"
161                                                                "Placeholders must be used here, as this value always needs to be unique!"),
162
163         # Fake fields used to implement the placeholder assistant
164         'model_object_field': fields.many2one('ir.model.fields', string="Field",
165                                               help="Select target field from the related document model.\n"
166                                                    "If it is a relationship field you will be able to select "
167                                                    "a target field at the destination of the relationship."),
168         'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
169                                       help="When a relationship field is selected as first field, "
170                                            "this field shows the document model the relationship goes to."),
171         'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
172                                                   help="When a relationship field is selected as first field, "
173                                                        "this field lets you select the target field within the "
174                                                        "destination document model (sub-model)."),
175         'null_value': fields.char('Null value', help="Optional value to use if the target field is empty", size=128),
176         'copyvalue': fields.char('Expression', size=256, help="Final placeholder expression, to be copy-pasted in the desired template field."),
177     }
178
179     _defaults = {
180         'track_campaign_item': True
181     }
182
183     def create_action(self, cr, uid, ids, context=None):
184         vals = {}
185         action_obj = self.pool.get('ir.actions.act_window')
186         data_obj = self.pool.get('ir.model.data')
187         for template in self.browse(cr, uid, ids, context=context):
188             src_obj = template.model_id.model
189             model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
190             res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
191             button_name = _('Send Mail (%s)') % template.name
192             vals['ref_ir_act_window'] = action_obj.create(cr, uid, {
193                  'name': button_name,
194                  'type': 'ir.actions.act_window',
195                  'res_model': 'mail.compose.message',
196                  'src_model': src_obj,
197                  'view_type': 'form',
198                  'context': "{'mail.compose.message.mode':'mass_mail', 'mail.compose.template_id' : %d}" % (template.id),
199                  'view_mode':'form,tree',
200                  'view_id': res_id,
201                  'target': 'new',
202                  'auto_refresh':1
203             }, context)
204             vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
205                  'name': button_name,
206                  'model': src_obj,
207                  'key2': 'client_action_multi',
208                  'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
209                  'object': True,
210              }, context)
211         self.write(cr, uid, ids, {
212                     'ref_ir_act_window': vals.get('ref_ir_act_window',False),
213                     'ref_ir_value': vals.get('ref_ir_value',False),
214                 }, context)
215         return True
216
217     def unlink_action(self, cr, uid, ids, context=None):
218         for template in self.browse(cr, uid, ids, context=context):
219             try:
220                 if template.ref_ir_act_window:
221                     self.pool.get('ir.actions.act_window').unlink(cr, uid, template.ref_ir_act_window.id, context)
222                 if template.ref_ir_value:
223                     ir_values_obj = self.pool.get('ir.values')
224                     ir_values_obj.unlink(cr, uid, template.ref_ir_value.id, context)
225             except:
226                 raise osv.except_osv(_("Warning"), _("Deletion of the action record failed."))
227         return True
228
229     def unlink(self, cr, uid, ids, context=None):
230         self.unlink_action(cr, uid, ids, context=context)
231         return super(email_template, self).unlink(cr, uid, ids, context=context)
232
233     def copy(self, cr, uid, id, default=None, context=None):
234         template = self.browse(cr, uid, id, context=context)
235         if default is None:
236             default = {}
237         default = default.copy()
238         default['name'] = template.name + _('(copy)')
239         return super(email_template, self).copy(cr, uid, id, default, context)
240
241     def build_expression(self, field_name, sub_field_name, null_value):
242         """Returns a placeholder expression for use in a template field,
243            based on the values provided in the placeholder assistant.
244
245           :param field_name: main field name
246           :param sub_field_name: sub field name (M2O)
247           :param null_value: default value if the target value is empty
248           :return: final placeholder expression
249         """
250         expression = ''
251         if field_name:
252             expression = "${object." + field_name
253             if sub_field_name:
254                 expression += "." + sub_field_name
255             if null_value:
256                 expression += " or '''%s'''" % null_value
257             expression += "}"
258         return expression
259
260     def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
261         result = {
262             'sub_object': False,
263             'copyvalue': False,
264             'sub_model_object_field': False,
265             'null_value': False
266             }
267         if model_object_field:
268             fields_obj = self.pool.get('ir.model.fields')
269             field_value = fields_obj.browse(cr, uid, model_object_field, context)
270             if field_value.ttype in ['many2one', 'one2many', 'many2many']:
271                 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
272                 sub_field_value = False
273                 if sub_model_object_field:
274                     sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
275                 if res_ids:
276                     result.update({
277                         'sub_object': res_ids[0],
278                         'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
279                         'sub_model_object_field': sub_model_object_field or False,
280                         'null_value': null_value or False
281                         })
282             else:
283                 result.update({
284                         'copyvalue': self.build_expression(field_value.name, False, null_value or False),
285                         'null_value': null_value or False
286                         })
287         return {'value':result}
288
289
290     def generate_email(self, cr, uid, template_id, res_id, context=None):
291         """Generates an email from the template for given (model, res_id) pair.
292
293            :param template_id: id of the template to render.
294            :param res_id: id of the record to use for rendering the template (model
295                           is taken from template definition)
296            :returns: a dict containing all relevant fields for creating a new
297                      mail.message entry, with the addition one additional
298                      special key ``attachments`` containing a list of
299         """
300         if context is None:
301             context = {}
302         values = {
303                   'subject': False,
304                   'body_text': False,
305                   'body_html': False,
306                   'email_from': False,
307                   'email_to': False,
308                   'email_cc': False,
309                   'email_bcc': False,
310                   'reply_to': False,
311                   'auto_delete': False,
312                   'model': False,
313                   'res_id': False,
314                   'mail_server_id': False,
315                   'attachments': False,
316                   'attachment_ids': False,
317                   'message_id': False,
318                   'state': 'outgoing',
319                   'content_subtype': 'plain',
320                   'partner_ids': [],
321         }
322         if not template_id:
323             return values
324
325         report_xml_pool = self.pool.get('ir.actions.report.xml')
326         template = self.get_email_template(cr, uid, template_id, res_id, context)
327
328         for field in ['subject', 'body_text', 'body_html', 'email_from',
329                       'email_to', 'email_cc', 'email_bcc', 'reply_to',
330                       'message_id']:
331             values[field] = self.render_template(cr, uid, getattr(template, field),
332                                                  template.model, res_id, context=context) \
333                                                  or False
334
335         # if email_to: find or create a partner
336         if values['email_to']:
337             partner_id = self.pool.get('mail.thread').message_partner_by_email(cr, uid, values['email_to'], context=context)['partner_id']
338             if not partner_id:
339                 partner_id = self.pool.get('res.partner').name_create(cr, uid, values['email_to'], context=context)
340             values['partner_ids'] = [partner_id]
341
342         if values['body_html']:
343             values.update(content_subtype='html')
344
345         if template.user_signature:
346             signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
347             values['body_text'] += '\n\n' + signature
348
349         values.update(mail_server_id = template.mail_server_id.id or False,
350                       auto_delete = template.auto_delete,
351                       model=template.model,
352                       res_id=res_id or False)
353
354         attachments = {}
355         # Add report as a Document
356         if template.report_template:
357             report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
358             report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
359             # Ensure report is rendered using template's language
360             ctx = context.copy()
361             if template.lang:
362                 ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
363             service = netsvc.LocalService(report_service)
364             (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
365             result = base64.b64encode(result)
366             if not report_name:
367                 report_name = report_service
368             ext = "." + format
369             if not report_name.endswith(ext):
370                 report_name += ext
371             attachments[report_name] = result
372
373         # Add document attachments
374         for attach in template.attachment_ids:
375             # keep the bytes as fetched from the db, base64 encoded
376             attachments[attach.datas_fname] = attach.datas
377
378         values['attachments'] = attachments
379         return values
380
381     def send_mail(self, cr, uid, template_id, res_id, force_send=False, context=None):
382         """Generates a new mail message for the given template and record,
383            and schedules it for delivery through the ``mail`` module's scheduler.
384
385            :param int template_id: id of the template to render
386            :param int res_id: id of the record to render the template with
387                               (model is taken from the template)
388            :param bool force_send: if True, the generated mail.message is
389                 immediately sent after being created, as if the scheduler
390                 was executed for this message only.
391            :returns: id of the mail.message that was created 
392         """
393         if context is None: context = {}
394         mail_message = self.pool.get('mail.message')
395         ir_attachment = self.pool.get('ir.attachment')
396         values = self.generate_email(cr, uid, template_id, res_id, context=context)
397         assert 'email_from' in values, 'email_from is missing or empty after template rendering, send_mail() cannot proceed'
398         attachments = values.pop('attachments') or {}
399         msg_id = mail_message.create(cr, uid, values, context=context)
400         # link attachments
401         attachment_ids = []
402         for fname, fcontent in attachments.iteritems():
403             attachment_data = {
404                     'name': fname,
405                     'datas_fname': fname,
406                     'datas': fcontent,
407                     'res_model': mail_message._name,
408                     'res_id': msg_id,
409             }
410             context.pop('default_type', None)
411             attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
412         if attachment_ids:
413             mail_message.write(cr, uid, msg_id, {'attachment_ids': [(6, 0, attachment_ids)]}, context=context)
414         if force_send:
415             mail_message.send(cr, uid, [msg_id], context=context)
416         return msg_id
417
418 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: