1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2009 Sharoon Thomas
6 # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
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.
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.
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/>
21 ##############################################################################
24 from osv import fields
30 from tools.translate import _
34 class email_template(osv.osv):
35 "Templates for sending Email"
36 _inherit = 'email.message.template'
37 _name = "email.template"
38 _description = 'Email Templates for Models'
40 def get_template_value(self, cr, uid, message=None, model=None, record_id=None, context=None):
42 return mako_template.get_value(cr, uid, message=message, model=model, record_id=record_id, context=context)
44 def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
45 "Return Template Object"
49 template_id = context.get('template_id', False)
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)
56 # Use translated template if necessary
59 template = self.browse(cr, uid, template.id, ctx)
62 def onchange_model_id(self, cr, uid, ids, model_id, context=None):
65 mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
66 return {'value':{'model':mod_name}}
69 'name': fields.char('Name', size=250),
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"),
80 help="The default language for the email."
81 " Placeholders can be used here. "
82 "eg. ${object.partner_id.lang}"),
83 'subject':fields.char(
86 help="The subject of email."
87 " Placeholders can be used here.",
89 'description':fields.text(
90 'Standard Body (Text)',
91 help="The text version of the mail",
93 'body_html':fields.text(
94 'Body (Text-Web Client Only)',
95 help="The text version of the mail",
97 'user_signature':fields.boolean(
99 help="the signature from the User details"
100 " will be appended to the mail"),
101 'report_name':fields.char(
104 help="Name of the generated report file. Placeholders can be used in the filename. eg: 2009_SO003.pdf",
106 'report_template':fields.many2one(
107 'ir.actions.report.xml',
109 'attachment_ids': fields.many2many(
111 'email_template_attachment_rel',
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',
120 help="Action that will open this email template on Resource records",
122 'ref_ir_value':fields.many2one(
125 help="Button in the side bar of the form view of this Resource that will invoke the Window Action",
127 'allowed_groups':fields.many2many(
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(
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"
143 'sub_object':fields.many2one(
146 help='When a relation field is used this field'
147 ' will show you the type of field you have selected',
149 'sub_model_object_field':fields.many2one(
152 help="When you choose relationship fields "
153 "this field will specify the sub value you can use.",
155 'null_value':fields.char(
157 help="This Value is used if the field is empty",
158 size=50, store=False),
159 'copyvalue':fields.char(
162 help="Copy and paste the value in the "
163 "location you want to use a system value.",
165 'table_html':fields.text(
167 help="Copy this html code to your HTML message"
168 " body for displaying the info in your mail.",
170 'auto_delete': fields.boolean('Auto Delete', help="Permanently delete emails after sending"),
174 ('name', 'unique (name)','The template name must be unique !')
177 def create_action(self, cr, uid, ids, context=None):
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,
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],
196 vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
197 'name': _('Send Mail (%s)') % template.name,
199 'key2': 'client_action_multi',
200 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
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),
209 def unlink_action(self, cr, uid, ids, context=None):
210 for template in self.browse(cr, uid, ids, context=context):
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)
217 raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
219 def delete_action(self, cr, uid, ids, context=None):
220 self.unlink_action(cr, uid, ids, context=context)
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)
227 def copy(self, cr, uid, id, default=None, context=None):
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)
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)
239 def build_expression(self, field_name, sub_field_name, null_value):
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
249 expression = "${object." + field_name
251 expression += "." + sub_field_name
253 expression += " or '''%s'''" % null_value
257 # def onchange_model_object_field(self, cr, uid, ids, model_object_field, context=None):
258 # if not model_object_field:
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)
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
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}
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:
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)
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
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}
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:
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)
309 # result['sub_object'] = res_ids[0]
310 # result['copyvalue'] = self.build_expression(field_obj.name,
311 # sub_field_obj.name,
315 # result['sub_model_object_field'] = sub_model_object_field
316 # result['null_value'] = null_value
318 # #Its a simple field... just compute placeholder
319 # result['sub_object'] = False
320 # result['copyvalue'] = self.build_expression(field_obj.name,
325 # result['sub_model_object_field'] = False
326 # result['null_value'] = null_value
327 # return {'value':result}
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):
333 'sub_model_object_field': False,
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)
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
353 'copyvalue': self.build_expression(field_value.name, False, null_value or False),
354 'null_value': null_value or False
356 return {'value':result}
359 def _generate_email(self, cr, uid, template_id, record_id, context=None):
361 Generates an email from the template for
362 record record_id of target object
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
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
381 email_from = tools.ustr(smtp_server.name) + "<" + tools.ustr(email_id) + ">"
383 model = template.model_id.model
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),
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)})
399 elif template['track_campaign_item']:
400 # get appropriate message-id
401 values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
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
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
418 data['model'] = template.model
420 # Ensure report is rendered using template's language
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)
428 report_name = reportname
429 report_name = report_name + "." + format
430 attachment.append((report_name, result))
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))
439 context.update({'notemplate':True})
440 email_id = email_message_pool.email_send(cr, uid, values.get('email_from'), values.get('email_to'), values.get('name'), values.get('description'),
441 model=model, email_cc=values.get('email_cc'), email_bcc=values.get('email_bcc'), reply_to=values.get('reply_to'),
442 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)
443 email_message_pool.write(cr, uid, email_id, {'template_id': context.get('template_id',template.id)})
448 def generate_email(self, cr, uid, ids, record_ids, context=None):
451 email_message_pool = self.pool.get('email.message')
453 for template in self.browse(cr, uid, ids, context=context):
454 for record_id in record_ids:
455 email_id = self._generate_email(cr, uid, template.id, record_id, context)
456 email_ids.append(email_id)
460 class email_message(osv.osv):
461 _inherit = 'email.message'
463 'template_id': fields.many2one('email.template', 'Email-Template', readonly=True),
466 def process_email_queue(self, cr, uid, ids=None, context=None):
467 result = super(email_message, self).process_email_queue(cr, uid, ids, context)
468 attachment_obj = self.pool.get('ir.attachment')
469 for message in self.browse(cr, uid, result, context):
470 if message.template_id and message.template_id.auto_delete:
471 self.unlink(cr, uid, [id], context=context)
472 attachment_ids = [x.id for x in message.attachments_ids]
473 attachment_obj.unlink(cr, uid, attachment_ids, context=context)
476 def email_send(self, cr, uid, email_from, email_to, subject, body, model=False, email_cc=None, email_bcc=None, reply_to=False, attach=None,
477 message_id=False, openobject_id=False, debug=False, subtype='plain', x_headers={}, priority='3', smtp_server_id=False, context=None):
480 notemplate = context.get('notemplate', False)
481 if (not notemplate) and model and openobject_id:
482 template_pool = self.pool.get('email.template')
483 template_ids = template_pool.search(cr, uid, [('model','=',model)])
484 if template_ids and len(template_ids):
485 template_id = template_ids[0]
486 return template_pool.generate_email(cr, uid, [template_id], openobject_id, context=context)
487 return super(email_message, self).email_send(cr, uid, email_from, email_to, subject, body, model=model, email_cc=email_cc, email_bcc=email_bcc, reply_to=reply_to, attach=attach,
488 message_id=message_id, openobject_id=openobject_id, debug=debug, subtype=subtype, x_headers=x_headers, priority=priority, smtp_server_id=smtp_server_id, context=context)
491 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: