[REVIEW+IMP] email_template: set message_id on email.message when generate email...
[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 from osv import osv
24 from osv import fields
25 import base64
26 import random
27 import netsvc
28 import logging
29 import re
30 from tools.translate import _
31 import tools
32 import pooler
33
34 class email_template(osv.osv):
35     "Templates for sending Email"
36     _inherit = 'email.message'
37     _name = "email.template"
38     _description = 'Email Templates for Models'
39
40     def get_template_value(self, cr, uid, message=None, model=None, record_id=None, context=None):
41         import mako_template
42         return mako_template.get_value(cr, uid, message=message, model=model, record_id=record_id, context=context)
43
44     def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
45         "Return Template Object"
46         if context is None:
47             context = {}
48         if not template_id:
49             template_id = context.get('template_id', False)
50         if not template_id:
51             return False
52
53         template = self.browse(cr, uid, int(template_id), context)
54         lang = self.get_template_value(cr, uid, template.lang, template.model, record_id, context)
55         if lang:
56             # Use translated template if necessary
57             ctx = context.copy()
58             ctx['lang'] = lang
59             template = self.browse(cr, uid, template.id, ctx)
60         return template
61
62     def onchange_model_id(self, cr, uid, ids, model_id, context=None):
63         mod_name = False
64         if model_id:
65             mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
66         return {'value':{'model':mod_name}}
67
68     _columns = {
69         'name': fields.char('Name', size=250, required=True),
70         'model_id':fields.many2one('ir.model', 'Resource'),
71         'model': fields.related('model_id', 'model', string='Model', type="char", size=128, store=True, readonly=True),
72         'track_campaign_item':fields.boolean('Resource Tracking',
73                                 help="Enable this is you wish to include a special \
74 tracking marker in outgoing emails so you can identify replies and link \
75 them back to the corresponding resource record. \
76 This is useful for CRM leads for example"),
77         'lang':fields.char(
78                    'Language',
79                    size=250,
80                    help="The default language for the email."
81                    " Placeholders can be used here. "
82                    "eg. ${object.partner_id.lang}"),
83         'subject':fields.char(
84                   'Subject',
85                   size=200,
86                   help="The subject of email."
87                   " Placeholders can be used here.",
88                   translate=True),
89         'description':fields.text(
90                     'Standard Body (Text)',
91                     help="The text version of the mail",
92                     translate=True),
93         'body_html':fields.text(
94                     'Body (Text-Web Client Only)',
95                     help="The text version of the mail",
96                     translate=True),
97         'user_signature':fields.boolean(
98                   'Signature',
99                   help="the signature from the User details"
100                   " will be appended to the mail"),
101         'report_name':fields.char(
102                 'Report Filename',
103                 size=200,
104                 help="Name of the generated report file. Placeholders can be used in the filename. eg: 2009_SO003.pdf",
105                 translate=True),
106         'report_template':fields.many2one(
107                   'ir.actions.report.xml',
108                   'Report to send'),
109         'attachment_ids': fields.many2many(
110                     'ir.attachment',
111                     'email_template_attachment_rel',
112                     'email_template_id',
113                     'attachment_id',
114                     'Attached Files',
115                     help="You may attach existing files to this template, "
116                          "so they will be added in all emails created from this template"),
117         'ref_ir_act_window':fields.many2one(
118                     'ir.actions.act_window',
119                     'Window Action',
120                     help="Action that will open this email template on Resource records",
121                     readonly=True),
122         'ref_ir_value':fields.many2one(
123                    'ir.values',
124                    'Wizard Button',
125                    help="Button in the side bar of the form view of this Resource that will invoke the Window Action",
126                    readonly=True),
127         'allowed_groups':fields.many2many(
128                   'res.groups',
129                   'template_group_rel',
130                   'templ_id', 'group_id',
131                   string="Allowed User Groups",
132                   help="Only users from these groups will be"
133                   " allowed to send mails from this Template"),
134         'model_object_field':fields.many2one(
135                  'ir.model.fields',
136                  string="Field",
137                  help="Select the field from the model you want to use."
138                  "\nIf it is a relationship field you will be able to "
139                  "choose the nested values in the box below\n(Note:If "
140                  "there are no values make sure you have selected the"
141                  " correct model)",
142                  store=False),
143         'sub_object':fields.many2one(
144                  'ir.model',
145                  'Sub-model',
146                  help='When a relation field is used this field'
147                  ' will show you the type of field you have selected',
148                  store=False),
149         'sub_model_object_field':fields.many2one(
150                  'ir.model.fields',
151                  'Sub Field',
152                  help="When you choose relationship fields "
153                  "this field will specify the sub value you can use.",
154                  store=False),
155         'null_value':fields.char(
156                  'Null Value',
157                  help="This Value is used if the field is empty",
158                  size=50, store=False),
159         'copyvalue':fields.char(
160                 'Expression',
161                 size=100,
162                 help="Copy and paste the value in the "
163                 "location you want to use a system value.",
164                 store=False),
165         'table_html':fields.text(
166              'HTML code',
167              help="Copy this html code to your HTML message"
168              " body for displaying the info in your mail.",
169              store=False),
170         'auto_delete': fields.boolean('Auto Delete', help="Permanently delete emails after sending"),
171     }
172
173     _sql_constraints = [
174         ('name', 'unique (name)','The template name must be unique !')
175     ]
176
177     def create_action(self, cr, uid, ids, context=None):
178         vals = {}
179         if context is None:
180             context = {}
181         action_obj = self.pool.get('ir.actions.act_window')
182         for template in self.browse(cr, uid, ids, context=context):
183             src_obj = template.model_id.model
184             vals['ref_ir_act_window'] = action_obj.create(cr, uid, {
185                  'name': template.name,
186                  'type': 'ir.actions.act_window',
187                  'res_model': 'email_template.send.wizard',
188                  'src_model': src_obj,
189                  'view_type': 'form',
190                  'context': "{'src_model':'%s','template_id':'%d','src_rec_id':active_id,'src_rec_ids':active_ids}" % (src_obj, template.id),
191                  'view_mode':'form,tree',
192                  'view_id': self.pool.get('ir.ui.view').search(cr, uid, [('name', '=', 'email_template.send.wizard.form')], context=context)[0],
193                  'target': 'new',
194                  'auto_refresh':1
195             }, context)
196             vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
197                  'name': _('Send Mail (%s)') % template.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                     self.pool.get('ir.values').unlink(cr, uid, template.ref_ir_value.id, context)
216             except:
217                 raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
218
219     def delete_action(self, cr, uid, ids, context=None):
220         self.unlink_action(cr, uid, ids, context=context)
221         return True
222
223     def unlink(self, cr, uid, ids, context=None):
224         self.unlink_action(cr, uid, ids, context=context)
225         return super(email_template, self).unlink(cr, uid, ids, context=context)
226
227     def copy(self, cr, uid, id, default=None, context=None):
228         if default is None:
229             default = {}
230         default = default.copy()
231         old = self.read(cr, uid, id, ['name'], context=context)
232         new_name = _("Copy of template ") + old.get('name', 'No Name')
233         check = self.search(cr, uid, [('name', '=', new_name)], context=context)
234         if check:
235             new_name = new_name + '_' + random.choice('abcdefghij') + random.choice('lmnopqrs') + random.choice('tuvwzyz')
236         default.update({'name':new_name})
237         return super(email_template, self).copy(cr, uid, id, default, context)
238
239     def build_expression(self, field_name, sub_field_name, null_value):
240         """
241         Returns a template expression based on data provided
242         @param field_name: field name
243         @param sub_field_name: sub field name (M2O)
244         @param null_value: default value if the target value is empty
245         @return: computed expression
246         """
247         expression = ''
248         if field_name:
249             expression = "${object." + field_name
250             if sub_field_name:
251                 expression += "." + sub_field_name
252             if null_value:
253                 expression += " or '''%s'''" % null_value
254             expression += "}"
255         return expression
256 #
257 #    def onchange_model_object_field(self, cr, uid, ids, model_object_field, context=None):
258 #        if not model_object_field:
259 #            return {}
260 #        result = {}
261 #        field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
262 #        #Check if field is relational
263 #        if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
264 #            res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
265 #            if res_ids:
266 #                result['sub_object'] = res_ids[0]
267 #                result['copyvalue'] = self.build_expression(False, False, False)
268 #                result['sub_model_object_field'] = False
269 #                result['null_value'] = False
270 #        else:
271 #            #Its a simple field... just compute placeholder
272 #            result['sub_object'] = False
273 #            result['copyvalue'] = self.build_expression(field_obj.name, False, False)
274 #            result['sub_model_object_field'] = False
275 #            result['null_value'] = False
276 #        return {'value':result}
277 #
278 #    def onchange_sub_model_object_field(self, cr, uid, ids, model_object_field, sub_model_object_field, context=None):
279 #        if not model_object_field or not sub_model_object_field:
280 #            return {}
281 #        result = {}
282 #        field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
283 #        if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
284 #            res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
285 #            sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
286 #            if res_ids:
287 #                result['sub_object'] = res_ids[0]
288 #                result['copyvalue'] = self.build_expression(field_obj.name, sub_field_obj.name, False)
289 #                result['sub_model_object_field'] = sub_model_object_field
290 #                result['null_value'] = False
291 #        else:
292 #            #Its a simple field... just compute placeholder
293 #            result['sub_object'] = False
294 #            result['copyvalue'] = self.build_expression(field_obj.name, False, False)
295 #            result['sub_model_object_field'] = False
296 #            result['null_value'] = False
297 #        return {'value':result}
298 #
299 #
300 #    def onchange_null_value(self, cr, uid, ids, model_object_field, sub_model_object_field, null_value, template_language, context=None):
301 #        if not model_object_field and not null_value:
302 #            return {}
303 #        result = {}
304 #        field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
305 #        if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
306 #            res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
307 #            sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
308 #            if res_ids:
309 #                result['sub_object'] = res_ids[0]
310 #                result['copyvalue'] = self.build_expression(field_obj.name,
311 #                                                      sub_field_obj.name,
312 #                                                      null_value,
313 #                                                      template_language
314 #                                                      )
315 #                result['sub_model_object_field'] = sub_model_object_field
316 #                result['null_value'] = null_value
317 #        else:
318 #            #Its a simple field... just compute placeholder
319 #            result['sub_object'] = False
320 #            result['copyvalue'] = self.build_expression(field_obj.name,
321 #                                                  False,
322 #                                                  null_value,
323 #                                                  template_language
324 #                                                  )
325 #            result['sub_model_object_field'] = False
326 #            result['null_value'] = null_value
327 #        return {'value':result}
328
329     def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
330         result = {
331             'sub_object': False,
332             'copyvalue': False,
333             'sub_model_object_field': False,
334             'null_value': False
335             }
336         if model_object_field:
337             fields_obj = self.pool.get('ir.model.fields')
338             field_value = fields_obj.browse(cr, uid, model_object_field, context)
339             if field_value.ttype in ['many2one', 'one2many', 'many2many']:
340                 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
341                 sub_field_value = False
342                 if sub_model_object_field:
343                     sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
344                 if res_ids:
345                     result.update({
346                         'sub_object': res_ids[0],
347                         'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
348                         'sub_model_object_field': sub_model_object_field or False,
349                         'null_value': null_value or False
350                         })
351             else:
352                 result.update({
353                         'copyvalue': self.build_expression(field_value.name, False, null_value or False),
354                         'null_value': null_value or False
355                         })
356         return {'value':result}
357
358     
359     def _generate_email(self, cr, uid, template_id, record_id, context=None):
360         """
361         Generates an email from the template for
362         record record_id of target object
363         """
364         if context is None:
365             context = {}
366         smtp_pool = self.pool.get('email.smtp_server')
367         email_message_pool = self.pool.get('email.message')
368         report_xml_pool = self.pool.get('ir.actions.report.xml')
369         template = self.get_email_template(cr, uid, template_id, record_id, context)
370         smtp_server_id = context.get('smtp_server_id', False)
371         if not smtp_server_id:
372             smtp_server_id = template.smtp_server_id.id
373         smtp_server = smtp_pool.browse(cr, uid, smtp_server_id, context=context)
374         # determine name of sender, either it is specified in email_id
375         
376         email_id = smtp_server.email_id.strip()
377         email_from = re.findall(r'([^ ,<@]+@[^> ,]+)', email_id)[0]
378         if email_from != email_id:
379             email_from = smtp_server.email_id
380         else:
381             email_from = tools.ustr(smtp_server.name) + "<" + tools.ustr(email_id) + ">"
382
383         model = template.model_id.model
384         values = {
385             'email_from': email_from,
386             'email_to': self.get_template_value(cr, uid, template.email_to, model, record_id, context),
387             'email_cc': self.get_template_value(cr, uid, template.email_cc, model, record_id, context),
388             'email_bcc': self.get_template_value(cr, uid, template.email_bcc, model, record_id, context),
389             'reply_to': self.get_template_value(cr, uid, template.reply_to, model, record_id, context),
390             'name': self.get_template_value(cr, uid, template.subject, model, record_id, context),
391             'description': self.get_template_value(cr, uid, template.description, model, record_id, context),
392             #'body_html': self.get_template_value(cr, uid, template.body_html, model, record_id, context),
393         }
394
395         if template.message_id:
396             # use provided message_id with placeholders
397             values.update({'message_id': self.get_template_value(cr, uid, template.message_id, model, record_id, context)})
398
399         elif template['track_campaign_item']:
400             # get appropriate message-id
401             values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
402
403         #Use signatures if allowed
404         if template.user_signature:
405             sign = self.pool.get('res.users').read(cr, uid, uid, ['signature'], context)['signature']
406             if values['description']:
407                 values['description'] += '\n\n' + sign
408             #if values['body_html']:
409             #    values['body_html'] += sign
410         
411         attachment = []
412         
413         # Add report as a Document
414         if template.report_template:
415             report_name = template.report_name
416             reportname = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
417             data = {}
418             data['model'] = template.model
419
420             # Ensure report is rendered using template's language
421             ctx = context.copy()
422             if template.lang:
423                 ctx['lang'] = self.get_template_value(cr, uid, template.lang, template.model, record_id, context)
424             service = netsvc.LocalService(reportname)
425             (result, format) = service.create(cr, uid, [record_id], data, ctx)
426             result = base64.b64encode(result)
427             if not report_name:
428                 report_name = reportname
429             report_name = report_name + "." + format
430             attachment.append((report_name, result))
431             
432
433         # Add document attachments
434         for attach in template.attachment_ids:
435             #attach = attahcment_obj.browse(cr, uid, attachment_id, context)
436             attachment.append((attach.datas_fname, attach.datas))
437        
438         #Send emails
439         email_id = email_message_pool.email_send(cr, uid, values.get('email_from'), values.get('email_to'), values.get('name'), values.get('description'), 
440                     model=model, email_cc=values.get('email_cc'), email_bcc=values.get('email_bcc'), reply_to=values.get('reply_to'), 
441                     attach=attachment, message_id=values.get('message_id'), openobject_id=record_id, debug=True, subtype='plain', x_headers={}, priority='3', smtp_server_id=smtp_server.id, context=context)
442         email_message_pool.write(cr, uid, email_id, {'template_id': template.id})
443         return email_id
444
445
446
447     def generate_email(self, cr, uid, ids, record_ids,  context=None):
448         if context is None:
449             context = {}
450         email_message_pool = self.pool.get('email.message')
451         email_ids = []
452         for template in self.browse(cr, uid, ids, context=context):
453             for record_id in record_ids:
454                 email_id = self._generate_email(cr, uid, template.id, record_id, context)
455                 email_ids.append(email_id)
456         return email_ids
457 email_template()
458
459 class email_message(osv.osv):
460     _inherit = 'email.message'
461     _columns = {
462         'template_id': fields.many2one('email.template', 'Email-Template', readonly=True),
463         }
464
465     def process_email_queue(self, cr, uid, ids=None, context=None):
466         result = super(email_message, self).process_email_queue(cr, uid, ids, context)
467         attachment_obj = self.pool.get('ir.attachment')
468         for message in self.browse(cr, uid, result, context):
469             if message.template_id and message.template_id.auto_delete:
470                 self.unlink(cr, uid, [id], context=context)
471                 attachment_ids = [x.id for x in message.attachments_ids]
472                 attachment_obj.unlink(cr, uid, attachment_ids, context=context)
473         return result
474
475 email_message()
476
477 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: