[I18N] all: updated translation templates after latest changes (again)
[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-2010 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 random
25 import netsvc
26 import logging
27 import re
28
29 TEMPLATE_ENGINES = []
30
31 from osv import osv, fields
32 from tools.translate import _
33
34 try:
35     from mako.template import Template as MakoTemplate
36     TEMPLATE_ENGINES.append(('mako', 'Mako Templates'))
37 except ImportError:
38     logging.getLogger('init').warning("module email_template: Mako templates not installed")
39     
40 try:
41     from django.template import Context, Template as DjangoTemplate
42     #Workaround for bug:
43     #http://code.google.com/p/django-tagging/issues/detail?id=110
44     from django.conf import settings
45     settings.configure()
46     #Workaround ends
47     TEMPLATE_ENGINES.append(('django', 'Django Template'))
48 except ImportError:
49     logging.getLogger('init').warning("module email_template: Django templates not installed")
50
51 import tools
52 import pooler
53 import logging
54
55 def get_value(cursor, user, recid, message=None, template=None, context=None):
56     """
57     Evaluates an expression and returns its value
58     @param cursor: Database Cursor
59     @param user: ID of current user
60     @param recid: ID of the target record under evaluation
61     @param message: The expression to be evaluated
62     @param template: BrowseRecord object of the current template
63     @param context: OpenERP Context
64     @return: Computed message (unicode) or u""
65     """
66     pool = pooler.get_pool(cursor.dbname)
67     if message is None:
68         message = {}
69     #Returns the computed expression
70     if message:
71         try:
72             message = tools.ustr(message)
73             object = pool.get(template.model_int_name).browse(cursor, user, recid, context=context)
74             env = {
75                 'user':pool.get('res.users').browse(cursor, user, user, context=context),
76                 'db':cursor.dbname
77                    }
78             if template.template_language == 'mako':
79                 templ = MakoTemplate(message, input_encoding='utf-8')
80                 reply = MakoTemplate(message).render_unicode(object=object,
81                                                              peobject=object,
82                                                              env=env,
83                                                              format_exceptions=True)
84             elif template.template_language == 'django':
85                 templ = DjangoTemplate(message)
86                 env['object'] = object
87                 env['peobject'] = object
88                 reply = templ.render(Context(env))
89             return reply or False
90         except Exception:
91             logging.exception("can't render %r", message)
92             return u""
93     else:
94         return message
95
96 class email_template(osv.osv):
97     "Templates for sending Email"
98
99     _name = "email.template"
100     _description = 'Email Templates for Models'
101
102     def change_model(self, cursor, user, ids, object_name, context=None):
103         if object_name:
104             mod_name = self.pool.get('ir.model').read(
105                                               cursor,
106                                               user,
107                                               object_name,
108                                               ['model'], context)['model']
109         else:
110             mod_name = False
111         return {
112                 'value':{'model_int_name':mod_name}
113                 }
114
115     _columns = {
116         'name' : fields.char('Name', size=100, required=True),
117         'object_name':fields.many2one('ir.model', 'Resource'),
118         'model_int_name':fields.char('Model Internal Name', size=200,),
119         'from_account':fields.many2one(
120                    'email_template.account',
121                    string="Email Account",
122                    help="Emails will be sent from this approved account."),
123         'def_to':fields.char(
124                  'Recipient (To)',
125                  size=250,
126                  help="The Recipient of email. "
127                  "Placeholders can be used here. "
128                  "e.g. ${object.email_to}"),
129         'def_cc':fields.char(
130                  'CC',
131                  size=250,
132                  help="Carbon Copy address(es), comma-separated."
133                     " Placeholders can be used here. "
134                     "e.g. ${object.email_cc}"),
135         'def_bcc':fields.char(
136                   'BCC',
137                   size=250,
138                   help="Blind Carbon Copy address(es), comma-separated."
139                     " Placeholders can be used here. "
140                     "e.g. ${object.email_bcc}"),
141         'reply_to':fields.char('Reply-To',
142                     size=250,
143                     help="The address recipients should reply to,"
144                     " if different from the From address."
145                     " Placeholders can be used here. "
146                     "e.g. ${object.email_reply_to}"),
147         'message_id':fields.char('Message-ID',
148                     size=250,
149                     help="Specify the Message-ID SMTP header to use in outgoing emails. Please note that this overrides the Resource tracking option! Placeholders can be used here."),
150         'track_campaign_item':fields.boolean('Resource Tracking',
151                                 help="Enable this is you wish to include a special \
152 tracking marker in outgoing emails so you can identify replies and link \
153 them back to the corresponding resource record. \
154 This is useful for CRM leads for example"),
155         'lang':fields.char(
156                    'Language',
157                    size=250,
158                    help="The default language for the email."
159                    " Placeholders can be used here. "
160                    "eg. ${object.partner_id.lang}"),
161         'def_subject':fields.char(
162                   'Subject',
163                   size=200,
164                   help="The subject of email."
165                   " Placeholders can be used here.",
166                   translate=True),
167         'def_body_text':fields.text(
168                     'Standard Body (Text)',
169                     help="The text version of the mail",
170                     translate=True),
171         'def_body_html':fields.text(
172                     'Body (Text-Web Client Only)',
173                     help="The text version of the mail",
174                     translate=True),
175         'use_sign':fields.boolean(
176                   'Signature',
177                   help="the signature from the User details"
178                   " will be appended to the mail"),
179         'file_name':fields.char(
180                 'Report Filename',
181                 size=200,
182                 help="Name of the generated report file. Placeholders can be used in the filename. eg: 2009_SO003.pdf",
183                 translate=True),
184         'report_template':fields.many2one(
185                   'ir.actions.report.xml',
186                   'Report to send'),
187         'attachment_ids': fields.many2many(
188                     'ir.attachment',
189                     'email_template_attachment_rel',
190                     'email_template_id',
191                     'attachment_id',
192                     'Attached Files',
193                     help="You may attach existing files to this template, "
194                          "so they will be added in all emails created from this template"),
195         'ref_ir_act_window':fields.many2one(
196                     'ir.actions.act_window',
197                     'Window Action',
198                     help="Action that will open this email template on Resource records",
199                     readonly=True),
200         'ref_ir_value':fields.many2one(
201                    'ir.values',
202                    'Wizard Button',
203                    help="Button in the side bar of the form view of this Resource that will invoke the Window Action",
204                    readonly=True),
205         'allowed_groups':fields.many2many(
206                   'res.groups',
207                   'template_group_rel',
208                   'templ_id', 'group_id',
209                   string="Allowed User Groups",
210                   help="Only users from these groups will be"
211                   " allowed to send mails from this Template"),
212         'model_object_field':fields.many2one(
213                  'ir.model.fields',
214                  string="Field",
215                  help="Select the field from the model you want to use."
216                  "\nIf it is a relationship field you will be able to "
217                  "choose the nested values in the box below\n(Note:If "
218                  "there are no values make sure you have selected the"
219                  " correct model)",
220                  store=False),
221         'sub_object':fields.many2one(
222                  'ir.model',
223                  'Sub-model',
224                  help='When a relation field is used this field'
225                  ' will show you the type of field you have selected',
226                  store=False),
227         'sub_model_object_field':fields.many2one(
228                  'ir.model.fields',
229                  'Sub Field',
230                  help="When you choose relationship fields "
231                  "this field will specify the sub value you can use.",
232                  store=False),
233         'null_value':fields.char(
234                  'Null Value',
235                  help="This Value is used if the field is empty",
236                  size=50, store=False),
237         'copyvalue':fields.char(
238                 'Expression',
239                 size=100,
240                 help="Copy and paste the value in the "
241                 "location you want to use a system value.",
242                 store=False),
243         'table_html':fields.text(
244              'HTML code',
245              help="Copy this html code to your HTML message"
246              " body for displaying the info in your mail.",
247              store=False),
248         #Template language(engine eg.Mako) specifics
249         'template_language':fields.selection(
250                 TEMPLATE_ENGINES,
251                 'Templating Language',
252                 required=True
253                 )
254     }
255
256     _defaults = {
257         'template_language' : lambda *a:'mako',
258
259     }
260
261     _sql_constraints = [
262         ('name', 'unique (name)','The template name must be unique !')
263     ]
264
265     def create_action(self, cr, uid, ids, context=None):
266         vals = {}
267         if context is None:
268             context = {}
269         template_obj = self.browse(cr, uid, ids, context=context)[0]
270         src_obj = template_obj.object_name.model
271         vals['ref_ir_act_window'] = self.pool.get('ir.actions.act_window').create(cr, uid, {
272              'name': template_obj.name,
273              'type': 'ir.actions.act_window',
274              'res_model': 'email_template.send.wizard',
275              'src_model': src_obj,
276              'view_type': 'form',
277              'context': "{'src_model':'%s','template_id':'%d','src_rec_id':active_id,'src_rec_ids':active_ids}" % (src_obj, template_obj.id),
278              'view_mode':'form,tree',
279              'view_id': self.pool.get('ir.ui.view').search(cr, uid, [('name', '=', 'email_template.send.wizard.form')], context=context)[0],
280              'target': 'new',
281              'auto_refresh':1
282         }, context)
283         vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
284              'name': _('Send Mail (%s)') % template_obj.name,
285              'model': src_obj,
286              'key2': 'client_action_multi',
287              'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
288              'object': True,
289          }, context)
290         self.write(cr, uid, ids, {
291             'ref_ir_act_window': vals['ref_ir_act_window'],
292             'ref_ir_value': vals['ref_ir_value'],
293         }, context)
294         return True
295
296     def unlink_action(self, cr, uid, ids, context=None):
297         for template in self.browse(cr, uid, ids, context=context):
298             try:
299                 if template.ref_ir_act_window:
300                     self.pool.get('ir.actions.act_window').unlink(cr, uid, template.ref_ir_act_window.id, context)
301                 if template.ref_ir_value:
302                     self.pool.get('ir.values').unlink(cr, uid, template.ref_ir_value.id, context)
303             except:
304                 raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
305
306     def delete_action(self, cr, uid, ids, context=None):
307         self.unlink_action(cr, uid, ids, context=context)
308         return True
309
310     def unlink(self, cr, uid, ids, context=None):
311         self.unlink_action(cr, uid, ids, context=context)
312         return super(email_template, self).unlink(cr, uid, ids, context=context)
313
314     def copy(self, cr, uid, id, default=None, context=None):
315         if default is None:
316             default = {}
317         default = default.copy()
318         old = self.read(cr, uid, id, ['name'], context=context)
319         new_name = _("Copy of template ") + old.get('name', 'No Name')
320         check = self.search(cr, uid, [('name', '=', new_name)], context=context)
321         if check:
322             new_name = new_name + '_' + random.choice('abcdefghij') + random.choice('lmnopqrs') + random.choice('tuvwzyz')
323         default.update({'name':new_name})
324         return super(email_template, self).copy(cr, uid, id, default, context)
325
326     def build_expression(self, field_name, sub_field_name, null_value, template_language='mako'):
327         """
328         Returns a template expression based on data provided
329         @param field_name: field name
330         @param sub_field_name: sub field name (M2O)
331         @param null_value: default value if the target value is empty
332         @param template_language: name of template engine
333         @return: computed expression
334         """
335
336         expression = ''
337         if template_language == 'mako':
338             if field_name:
339                 expression = "${object." + field_name
340                 if sub_field_name:
341                     expression += "." + sub_field_name
342                 if null_value:
343                     expression += " or '''%s'''" % null_value
344                 expression += "}"
345         elif template_language == 'django':
346             if field_name:
347                 expression = "{{object." + field_name
348                 if sub_field_name:
349                     expression += "." + sub_field_name
350                 if null_value:
351                     expression += "|default: '''%s'''" % null_value
352                 expression += "}}"
353         return expression
354
355     def onchange_model_object_field(self, cr, uid, ids, model_object_field, template_language, context=None):
356         if not model_object_field:
357             return {}
358         result = {}
359         field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
360         #Check if field is relational
361         if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
362             res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
363             if res_ids:
364                 result['sub_object'] = res_ids[0]
365                 result['copyvalue'] = self.build_expression(False,
366                                                       False,
367                                                       False,
368                                                       template_language)
369                 result['sub_model_object_field'] = False
370                 result['null_value'] = False
371         else:
372             #Its a simple field... just compute placeholder
373             result['sub_object'] = False
374             result['copyvalue'] = self.build_expression(field_obj.name,
375                                                   False,
376                                                   False,
377                                                   template_language
378                                                   )
379             result['sub_model_object_field'] = False
380             result['null_value'] = False
381         return {'value':result}
382
383     def onchange_sub_model_object_field(self, cr, uid, ids, model_object_field, sub_model_object_field, template_language, context=None):
384         if not model_object_field or not sub_model_object_field:
385             return {}
386         result = {}
387         field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
388         if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
389             res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
390             sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
391             if res_ids:
392                 result['sub_object'] = res_ids[0]
393                 result['copyvalue'] = self.build_expression(field_obj.name,
394                                                       sub_field_obj.name,
395                                                       False,
396                                                       template_language
397                                                       )
398                 result['sub_model_object_field'] = sub_model_object_field
399                 result['null_value'] = False
400         else:
401             #Its a simple field... just compute placeholder
402             result['sub_object'] = False
403             result['copyvalue'] = self.build_expression(field_obj.name,
404                                                   False,
405                                                   False,
406                                                   template_language
407                                                   )
408             result['sub_model_object_field'] = False
409             result['null_value'] = False
410         return {'value':result}
411
412     def onchange_null_value(self, cr, uid, ids, model_object_field, sub_model_object_field, null_value, template_language, context=None):
413         if not model_object_field and not null_value:
414             return {}
415         result = {}
416         field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
417         if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
418             res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
419             sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
420             if res_ids:
421                 result['sub_object'] = res_ids[0]
422                 result['copyvalue'] = self.build_expression(field_obj.name,
423                                                       sub_field_obj.name,
424                                                       null_value,
425                                                       template_language
426                                                       )
427                 result['sub_model_object_field'] = sub_model_object_field
428                 result['null_value'] = null_value
429         else:
430             #Its a simple field... just compute placeholder
431             result['sub_object'] = False
432             result['copyvalue'] = self.build_expression(field_obj.name,
433                                                   False,
434                                                   null_value,
435                                                   template_language
436                                                   )
437             result['sub_model_object_field'] = False
438             result['null_value'] = null_value
439         return {'value':result}
440
441     def _add_attachment(self, cursor, user, mailbox_id, name, data, filename, context=None):
442         """
443         Add an attachment to a given mailbox entry.
444
445         :param data: base64 encoded attachment data to store
446         """
447         attachment_obj = self.pool.get('ir.attachment')
448         attachment_data = {
449             'name':  (name or '') + _(' (Email Attachment)'),
450             'datas': data,
451             'datas_fname': filename,
452             'description': name or _('No Description'),
453             'res_model':'email_template.mailbox',
454             'res_id': mailbox_id,
455         }
456         attachment_id = attachment_obj.create(cursor,
457                                               user,
458                                               attachment_data,
459                                               context)
460         if attachment_id:
461             self.pool.get('email_template.mailbox').write(
462                               cursor,
463                               user,
464                               mailbox_id,
465                               {
466                                'attachments_ids':[(4, attachment_id)],
467                                'mail_type':'multipart/mixed'
468                               },
469                               context)
470
471     def generate_attach_reports(self,
472                                  cursor,
473                                  user,
474                                  template,
475                                  record_id,
476                                  mail,
477                                  context=None):
478         """
479         Generate report to be attached and attach it
480         to the email, and add any directly attached files as well.
481
482         @param cursor: Database Cursor
483         @param user: ID of User
484         @param template: Browse record of
485                          template
486         @param record_id: ID of the target model
487                           for which this mail has
488                           to be generated
489         @param mail: Browse record of email object
490         @return: True
491         """
492         if template.report_template:
493             reportname = 'report.' + \
494                 self.pool.get('ir.actions.report.xml').read(
495                                              cursor,
496                                              user,
497                                              template.report_template.id,
498                                              ['report_name'],
499                                              context)['report_name']
500             service = netsvc.LocalService(reportname)
501             data = {}
502             data['model'] = template.model_int_name
503             (result, format) = service.create(cursor,
504                                               user,
505                                               [record_id],
506                                               data,
507                                               context)
508             fname = tools.ustr(get_value(cursor, user, record_id,
509                                          template.file_name, template, context)
510                                or 'Report')
511             ext = '.' + format
512             if not fname.endswith(ext):
513                 fname += ext
514             self._add_attachment(cursor, user, mail.id, mail.subject, base64.b64encode(result), fname, context)
515
516         if template.attachment_ids:
517             for attachment in template.attachment_ids:
518                 self._add_attachment(cursor, user, mail.id, attachment.name, attachment.datas, attachment.datas_fname, context)
519
520         return True
521
522     def _generate_mailbox_item_from_template(self,
523                                       cursor,
524                                       user,
525                                       template,
526                                       record_id,
527                                       context=None):
528         """
529         Generates an email from the template for
530         record record_id of target object
531
532         @param cursor: Database Cursor
533         @param user: ID of User
534         @param template: Browse record of
535                          template
536         @param record_id: ID of the target model
537                           for which this mail has
538                           to be generated
539         @return: ID of created object
540         """
541         if context is None:
542             context = {}
543         #If account to send from is in context select it, else use enforced account
544         if 'account_id' in context.keys():
545             from_account = self.pool.get('email_template.account').read(
546                                                     cursor,
547                                                     user,
548                                                     context.get('account_id'),
549                                                     ['name', 'email_id'],
550                                                     context
551                                                     )
552         else:
553             from_account = {
554                             'id':template.from_account.id,
555                             'name':template.from_account.name,
556                             'email_id':template.from_account.email_id
557                             }
558         lang = get_value(cursor,
559                          user,
560                          record_id,
561                          template.lang,
562                          template,
563                          context)
564         if lang:
565             ctx = context.copy()
566             ctx.update({'lang':lang})
567             template = self.browse(cursor, user, template.id, context=ctx)
568
569         # determine name of sender, either it is specified in email_id or we
570         # use the account name
571         email_id = from_account['email_id'].strip()
572         email_from = re.findall(r'([^ ,<@]+@[^> ,]+)', email_id)[0]
573         if email_from != email_id:
574             # we should keep it all, name is probably specified in the address
575             email_from = from_account['email_id']
576         else:
577             email_from = tools.ustr(from_account['name']) + "<" + tools.ustr('email_id') + ">",
578
579         # FIXME: should do this in a loop and rename template fields to the corresponding
580         # mailbox fields. (makes no sense to have different names I think.
581         mailbox_values = {
582             'email_from': email_from,
583             'email_to':get_value(cursor,
584                                user,
585                                record_id,
586                                template.def_to,
587                                template,
588                                context),
589             'email_cc':get_value(cursor,
590                                user,
591                                record_id,
592                                template.def_cc,
593                                template,
594                                context),
595             'email_bcc':get_value(cursor,
596                                 user,
597                                 record_id,
598                                 template.def_bcc,
599                                 template,
600                                 context),
601             'reply_to':get_value(cursor,
602                                 user,
603                                 record_id,
604                                 template.reply_to,
605                                 template,
606                                 context),
607             'subject':get_value(cursor,
608                                     user,
609                                     record_id,
610                                     template.def_subject,
611                                     template,
612                                     context),
613             'body_text':get_value(cursor,
614                                       user,
615                                       record_id,
616                                       template.def_body_text,
617                                       template,
618                                       context),
619             'body_html':get_value(cursor,
620                                       user,
621                                       record_id,
622                                       template.def_body_html,
623                                       template,
624                                       context),
625             'account_id' :from_account['id'],
626             #This is a mandatory field when automatic emails are sent
627             'state':'na',
628             'folder':'drafts',
629             'mail_type':'multipart/alternative',
630         }
631
632         if template['message_id']:
633             # use provided message_id with placeholders
634             mailbox_values.update({'message_id': get_value(cursor, user, record_id, template['message_id'], template, context)})
635
636         elif template['track_campaign_item']:
637             # get appropriate message-id
638             mailbox_values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
639
640         if not mailbox_values['account_id']:
641             raise Exception("Unable to send the mail. No account linked to the template.")
642         #Use signatures if allowed
643         if template.use_sign:
644             sign = self.pool.get('res.users').read(cursor,
645                                                    user,
646                                                    user,
647                                                    ['signature'],
648                                                    context)['signature']
649             if mailbox_values['body_text']:
650                 mailbox_values['body_text'] += sign
651             if mailbox_values['body_html']:
652                 mailbox_values['body_html'] += sign
653         mailbox_id = self.pool.get('email_template.mailbox').create(
654                                                              cursor,
655                                                              user,
656                                                              mailbox_values,
657                                                              context)
658
659         return mailbox_id
660
661
662     def generate_mail(self,
663                       cursor,
664                       user,
665                       template_id,
666                       record_ids,
667                       context=None):
668         if context is None:
669             context = {}
670         template = self.browse(cursor, user, template_id, context=context)
671         if not template:
672             raise Exception("The requested template could not be loaded")
673         result = True
674         mailbox_obj = self.pool.get('email_template.mailbox')
675         for record_id in record_ids:
676             mailbox_id = self._generate_mailbox_item_from_template(
677                                                                 cursor,
678                                                                 user,
679                                                                 template,
680                                                                 record_id,
681                                                                 context)
682             mail = mailbox_obj.browse(
683                                         cursor,
684                                         user,
685                                         mailbox_id,
686                                         context=context
687                                               )
688             if template.report_template or template.attachment_ids:
689                 self.generate_attach_reports(
690                                               cursor,
691                                               user,
692                                               template,
693                                               record_id,
694                                               mail,
695                                               context
696                                               )
697
698             self.pool.get('email_template.mailbox').write(
699                                                 cursor,
700                                                 user,
701                                                 mailbox_id,
702                                                 {'folder':'outbox'},
703                                                 context=context
704             )
705             # TODO : manage return value of all the records
706             result = self.pool.get('email_template.mailbox').send_this_mail(cursor, user, [mailbox_id], context)
707         return result
708
709 email_template()
710
711
712 ## FIXME: this class duplicates a lot of features of the email template send wizard,
713 ##        one of the 2 should inherit from the other!
714
715 class email_template_preview(osv.osv_memory):
716     _name = "email_template.preview"
717     _description = "Email Template Preview"
718
719     def _get_model_recs(self, cr, uid, context=None):
720         if context is None:
721             context = {}
722             #Fills up the selection box which allows records from the selected object to be displayed
723         self.context = context
724         if 'template_id' in context:
725             ref_obj_id = self.pool.get('email.template').read(cr, uid, context['template_id'], ['object_name'], context)
726             ref_obj_name = self.pool.get('ir.model').read(cr, uid, ref_obj_id['object_name'][0], ['model'], context)['model']
727             model_obj = self.pool.get(ref_obj_name)
728             ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id', context=context)
729             if not ref_obj_ids:
730                 ref_obj_ids = []
731
732             # also add the default one if requested, otherwise it won't be available for selection:
733             default_id = context.get('default_rel_model_ref')
734             if default_id and default_id not in ref_obj_ids:
735                 ref_obj_ids.insert(0, default_id)
736             return model_obj.name_get(cr, uid, ref_obj_ids, context)
737         return []
738
739     def default_get(self, cr, uid, fields, context=None):
740         if context is None:
741             context = {}
742         result = super(email_template_preview, self).default_get(cr, uid, fields, context=context)
743         if (not fields or 'rel_model_ref' in fields) and 'template_id' in context \
744            and not result.get('rel_model_ref'):
745             selectables = self._get_model_recs(cr, uid, context=context)
746             result['rel_model_ref'] = selectables and selectables[0][0] or False
747         return result
748
749     def _default_model(self, cursor, user, context=None):
750         """
751         Returns the default value for model field
752         @param cursor: Database Cursor
753         @param user: ID of current user
754         @param context: OpenERP Context
755         """
756         return self.pool.get('email.template').read(
757                                                    cursor,
758                                                    user,
759                                                    context['template_id'],
760                                                    ['object_name'],
761                                                    context).get('object_name', False)
762
763     _columns = {
764         'ref_template':fields.many2one(
765                                        'email.template',
766                                        'Template', readonly=True),
767         'rel_model':fields.many2one('ir.model', 'Model', readonly=True),
768         'rel_model_ref':fields.selection(_get_model_recs, 'Referred Document'),
769         'to':fields.char('To', size=250, readonly=True),
770         'cc':fields.char('CC', size=250, readonly=True),
771         'bcc':fields.char('BCC', size=250, readonly=True),
772         'reply_to':fields.char('Reply-To',
773                     size=250,
774                     help="The address recipients should reply to,"
775                          " if different from the From address."
776                          " Placeholders can be used here."),
777         'message_id':fields.char('Message-ID',
778                     size=250,
779                     help="The Message-ID header value, if you need to"
780                          "specify it, for example to automatically recognize the replies later."
781                         " Placeholders can be used here."),
782         'subject':fields.char('Subject', size=200, readonly=True),
783         'body_text':fields.text('Body', readonly=True),
784         'body_html':fields.text('Body', readonly=True),
785         'report':fields.char('Report Name', size=100, readonly=True),
786     }
787     _defaults = {
788         'ref_template': lambda self, cr, uid, ctx:ctx['template_id'] or False,
789         'rel_model': _default_model,
790     }
791     def on_change_ref(self, cr, uid, ids, rel_model_ref, context=None):
792         if context is None:
793             context = {}
794         if not rel_model_ref:
795             return {}
796         vals = {}
797         if context == {}:
798             context = self.context
799         template = self.pool.get('email.template').browse(cr, uid, context['template_id'], context)
800         #Search translated template
801         lang = get_value(cr, uid, rel_model_ref, template.lang, template, context)
802         if lang:
803             ctx = context.copy()
804             ctx.update({'lang':lang})
805             template = self.pool.get('email.template').browse(cr, uid, context['template_id'], ctx)
806         vals['to'] = get_value(cr, uid, rel_model_ref, template.def_to, template, context)
807         vals['cc'] = get_value(cr, uid, rel_model_ref, template.def_cc, template, context)
808         vals['bcc'] = get_value(cr, uid, rel_model_ref, template.def_bcc, template, context)
809         vals['reply_to'] = get_value(cr, uid, rel_model_ref, template.reply_to, template, context)
810         if template.message_id:
811             vals['message_id'] = get_value(cr, uid, rel_model_ref, template.message_id, template, context)
812         elif template.track_campaign_item:
813             vals['message_id'] = tools.misc.generate_tracking_message_id(rel_model_ref)
814         vals['subject'] = get_value(cr, uid, rel_model_ref, template.def_subject, template, context)
815         vals['body_text'] = get_value(cr, uid, rel_model_ref, template.def_body_text, template, context)
816         vals['body_html'] = get_value(cr, uid, rel_model_ref, template.def_body_html, template, context)
817         vals['report'] = get_value(cr, uid, rel_model_ref, template.file_name, template, context)
818         return {'value':vals}
819
820 email_template_preview()
821
822 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: