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