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