[FIX] base(res_partner),point_of_sale,product,sale_stock,stock: uniformization of...
[odoo/odoo.git] / addons / email_template / email_template.py
index 8a16c01..ba9bd26 100644 (file)
@@ -24,17 +24,44 @@ import base64
 import datetime
 import dateutil.relativedelta as relativedelta
 import logging
+import lxml
+import urlparse
 
 import openerp
 from openerp import SUPERUSER_ID
 from openerp.osv import osv, fields
-from openerp import tools
+from openerp import tools, api
 from openerp.tools.translate import _
 from urllib import urlencode, quote as quote
 
-
 _logger = logging.getLogger(__name__)
 
+
+def format_tz(pool, cr, uid, dt, tz=False, format=False, context=None):
+    context = dict(context or {})
+    if tz:
+        context['tz'] = tz or pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] or "UTC"
+    timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)
+
+    ts = fields.datetime.context_timestamp(cr, uid, timestamp, context)
+
+    if format:
+        return ts.strftime(format)
+    else:
+        lang = context.get("lang")
+        lang_params = {}
+        if lang:
+            res_lang = pool.get('res.lang')
+            ids = res_lang.search(cr, uid, [("code", "=", lang)])
+            if ids:
+                lang_params = res_lang.read(cr, uid, ids[0], ["date_format", "time_format"])
+        format_date = lang_params.get("date_format", '%B-%d-%Y')
+        format_time = lang_params.get("time_format", '%I-%M %p')
+
+        fdate = ts.strftime(format_date)
+        ftime = ts.strftime(format_time)
+        return "%s %s (%s)" % (fdate, ftime, tz)
+
 try:
     # We use a jinja2 sandboxed environment to render mako templates.
     # Note that the rendering does not cover all the mako syntax, in particular
@@ -61,6 +88,15 @@ try:
         'quote': quote,
         'urlencode': urlencode,
         'datetime': datetime,
+        'len': len,
+        'abs': abs,
+        'min': min,
+        'max': max,
+        'sum': sum,
+        'filter': filter,
+        'reduce': reduce,
+        'map': map,
+        'round': round,
 
         # dateutil.relativedelta is an old-style class and cannot be directly
         # instanciated wihtin a jinja2 expression, so a lambda "proxy" is
@@ -70,13 +106,61 @@ try:
 except ImportError:
     _logger.warning("jinja2 not available, templating features will not work!")
 
+
 class email_template(osv.osv):
     "Templates for sending email"
     _name = "email.template"
     _description = 'Email Templates'
     _order = 'name'
 
-    def render_template_batch(self, cr, uid, template, model, res_ids, context=None):
+    def default_get(self, cr, uid, fields, context=None):
+        res = super(email_template, self).default_get(cr, uid, fields, context)
+        if res.get('model'):
+            res['model_id'] = self.pool['ir.model'].search(cr, uid, [('model', '=', res.pop('model'))], context=context)[0]
+        return res
+
+    def _replace_local_links(self, cr, uid, html, context=None):
+        """ Post-processing of html content to replace local links to absolute
+        links, using web.base.url as base url. """
+        if not html:
+            return html
+
+        # form a tree
+        root = lxml.html.fromstring(html)
+        if not len(root) and root.text is None and root.tail is None:
+            html = '<div>%s</div>' % html
+            root = lxml.html.fromstring(html)
+
+        base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
+        (base_scheme, base_netloc, bpath, bparams, bquery, bfragment) = urlparse.urlparse(base_url)
+
+        def _process_link(url):
+            new_url = url
+            (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
+            if not scheme and not netloc:
+                new_url = urlparse.urlunparse((base_scheme, base_netloc, path, params, query, fragment))
+            return new_url
+
+        # check all nodes, replace :
+        # - img src -> check URL
+        # - a href -> check URL
+        for node in root.iter():
+            if node.tag == 'a' and node.get('href'):
+                node.set('href', _process_link(node.get('href')))
+            elif node.tag == 'img' and not node.get('src', 'data').startswith('data'):
+                node.set('src', _process_link(node.get('src')))
+
+        html = lxml.html.tostring(root, pretty_print=False, method='html')
+        # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
+        if html.startswith('<div>') and html.endswith('</div>'):
+            html = html[5:-6]
+        return html
+
+    def render_post_process(self, cr, uid, html, context=None):
+        html = self._replace_local_links(cr, uid, html, context=context)
+        return html
+
+    def render_template_batch(self, cr, uid, template, model, res_ids, context=None, post_process=False):
         """Render the given template text, replace mako expressions ``${expr}``
            with the result of evaluating these expressions with
            an evaluation context containing:
@@ -92,6 +176,7 @@ class email_template(osv.osv):
         """
         if context is None:
             context = {}
+        res_ids = filter(None, res_ids)         # to avoid browsing [None] below
         results = dict.fromkeys(res_ids, u"")
 
         # try to load the template
@@ -105,6 +190,7 @@ class email_template(osv.osv):
         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
         records = self.pool[model].browse(cr, uid, res_ids, context=context) or [None]
         variables = {
+            'format_tz': lambda dt, tz=False, format=False: format_tz(self.pool, cr, uid, dt, tz, format, context),
             'user': user,
             'ctx': context,  # context kw would clash with mako internals
         }
@@ -119,6 +205,10 @@ class email_template(osv.osv):
             if render_result == u"False":
                 render_result = u""
             results[res_id] = render_result
+
+        if post_process:
+            for res_id, result in results.iteritems():
+                results[res_id] = self.render_post_process(cr, uid, result, context=context)
         return results
 
     def get_email_template_batch(self, cr, uid, template_id=False, res_ids=None, context=None):
@@ -153,14 +243,14 @@ class email_template(osv.osv):
         'name': fields.char('Name'),
         'model_id': fields.many2one('ir.model', 'Applies to', help="The kind of document with with this template can be used"),
         'model': fields.related('model_id', 'model', type='char', string='Related Document Model',
-                                size=128, select=True, store=True, readonly=True),
+                                 select=True, store=True, readonly=True),
         'lang': fields.char('Language',
                             help="Optional translation language (ISO code) to select when sending out an email. "
                                  "If not set, the english version will be used. "
                                  "This should usually be a placeholder expression "
-                                 "that provides the appropriate language code, e.g. "
-                                 "${object.partner_id.lang.code}.",
-                            placeholder="${object.partner_id.lang.code}"),
+                                 "that provides the appropriate language, e.g. "
+                                 "${object.partner_id.lang}.",
+                            placeholder="${object.partner_id.lang}"),
         'user_signature': fields.boolean('Add Signature',
                                          help="If checked, the user's signature will be appended to the text version "
                                               "of the message"),
@@ -168,6 +258,11 @@ class email_template(osv.osv):
         'email_from': fields.char('From',
             help="Sender address (placeholders may be used here). If not set, the default "
                     "value will be the author's email alias if configured, or email address."),
+        'use_default_to': fields.boolean(
+            'Default recipients',
+            help="Default recipients of the record:\n"
+                 "- partner (using id on a partner or the partner_id field) OR\n"
+                 "- email (using email_from or email field)"),
         'email_to': fields.char('To (Emails)', help="Comma-separated recipient addresses (placeholders may be used here)"),
         'partner_to': fields.char('To (Partners)',
             help="Comma-separated ids of recipient partners (placeholders may be used here)",
@@ -177,15 +272,15 @@ class email_template(osv.osv):
         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
                                           help="Optional preferred server for outgoing mails. If not set, the highest "
                                                "priority one will be used."),
-        'body_html': fields.text('Body', translate=True, help="Rich-text/HTML version of the message (placeholders may be used here)"),
+        'body_html': fields.html('Body', translate=True, sanitize=False, help="Rich-text/HTML version of the message (placeholders may be used here)"),
         'report_name': fields.char('Report Filename', translate=True,
                                    help="Name to use for the generated report file (may contain placeholders)\n"
                                         "The extension can be omitted and will then come from the report type."),
         'report_template': fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
-        'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
+        'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True, copy=False,
                                             help="Sidebar action to make this template available on records "
                                                  "of the related document model"),
-        'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True,
+        'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True, copy=False,
                                        help="Sidebar button to open the sidebar action"),
         'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
                                            'attachment_id', 'Attachments',
@@ -266,13 +361,8 @@ class email_template(osv.osv):
 
     def copy(self, cr, uid, id, default=None, context=None):
         template = self.browse(cr, uid, id, context=context)
-        if default is None:
-            default = {}
-        default = default.copy()
-        default.update(
-            name=_("%s (copy)") % (template.name),
-            ref_ir_act_window=False,
-            ref_ir_value=False)
+        default = dict(default or {},
+                       name=_("%s (copy)") % template.name)
         return super(email_template, self).copy(cr, uid, id, default, context)
 
     def build_expression(self, field_name, sub_field_name, null_value):
@@ -323,6 +413,37 @@ class email_template(osv.osv):
                         })
         return {'value': result}
 
+    def generate_recipients_batch(self, cr, uid, results, template_id, res_ids, context=None):
+        """Generates the recipients of the template. Default values can ben generated
+        instead of the template values if requested by template or context.
+        Emails (email_to, email_cc) can be transformed into partners if requested
+        in the context. """
+        if context is None:
+            context = {}
+        template = self.browse(cr, uid, template_id, context=context)
+
+        if template.use_default_to or context.get('tpl_force_default_to'):
+            ctx = dict(context, thread_model=template.model)
+            default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
+            for res_id, recipients in default_recipients.iteritems():
+                results[res_id].pop('partner_to', None)
+                results[res_id].update(recipients)
+
+        for res_id, values in results.iteritems():
+            partner_ids = values.get('partner_ids', list())
+            if context and context.get('tpl_partners_only'):
+                mails = tools.email_split(values.pop('email_to', '')) + tools.email_split(values.pop('email_cc', ''))
+                for mail in mails:
+                    partner_id = self.pool.get('res.partner').find_or_create(cr, uid, mail, context=context)
+                    partner_ids.append(partner_id)
+            partner_to = values.pop('partner_to', '')
+            if partner_to:
+                # placeholders could generate '', 3, 2 due to some empty field values
+                tpl_partner_ids = [int(pid) for pid in partner_to.split(',') if pid]
+                partner_ids += self.pool['res.partner'].exists(cr, SUPERUSER_ID, tpl_partner_ids, context=context)
+            results[res_id]['partner_ids'] = partner_ids
+        return results
+
     def generate_email_batch(self, cr, uid, template_id, res_ids, context=None, fields=None):
         """Generates an email from the template for given the given model based on
         records given by res_ids.
@@ -332,7 +453,7 @@ class email_template(osv.osv):
                        is taken from template definition)
         :returns: a dict containing all relevant fields for creating a new
                   mail.mail entry, with one extra key ``attachments``, in the
-                  format expected by :py:meth:`mail_thread.message_post`.
+                  format [(report_name, data)] where data is base64 encoded.
         """
         if context is None:
             context = {}
@@ -350,18 +471,26 @@ class email_template(osv.osv):
         results = dict()
         for template, template_res_ids in templates_to_res_ids.iteritems():
             # generate fields value for all res_ids linked to the current template
-            for field in ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']:
-                generated_field_values = self.render_template_batch(cr, uid, getattr(template, field), template.model, template_res_ids, context=context)
+            for field in fields:
+                generated_field_values = self.render_template_batch(
+                    cr, uid, getattr(template, field), template.model, template_res_ids,
+                    post_process=(field == 'body_html'),
+                    context=context)
                 for res_id, field_value in generated_field_values.iteritems():
                     results.setdefault(res_id, dict())[field] = field_value
+            # compute recipients
+            results = self.generate_recipients_batch(cr, uid, results, template.id, template_res_ids, context=context)
             # update values for all res_ids
             for res_id in template_res_ids:
                 values = results[res_id]
-                if template.user_signature:
+                # body: add user signature, sanitize
+                if 'body_html' in fields and template.user_signature:
                     signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
-                    values['body_html'] = tools.append_content_to_html(values['body_html'], signature)
-                if values['body_html']:
+                    if signature:
+                        values['body_html'] = tools.append_content_to_html(values['body_html'], signature, plaintext=False)
+                if values.get('body_html'):
                     values['body'] = tools.html_sanitize(values['body_html'])
+                # technical settings
                 values.update(
                     mail_server_id=template.mail_server_id.id or False,
                     auto_delete=template.auto_delete,
@@ -375,12 +504,19 @@ class email_template(osv.osv):
                 for res_id in template_res_ids:
                     attachments = []
                     report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
-                    report_service = report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
+                    report = report_xml_pool.browse(cr, uid, template.report_template.id, context)
+                    report_service = report.report_name
                     # Ensure report is rendered using template's language
                     ctx = context.copy()
                     if template.lang:
                         ctx['lang'] = self.render_template_batch(cr, uid, template.lang, template.model, [res_id], context)[res_id]  # take 0 ?
-                    result, format = openerp.report.render_report(cr, uid, [res_id], report_service, {'model': template.model}, ctx)
+
+                    if report.report_type in ['qweb-html', 'qweb-pdf']:
+                        result, format = self.pool['report'].get_pdf(cr, uid, [res_id], report_service, context=ctx), 'pdf'
+                    else:
+                        result, format = openerp.report.render_report(cr, uid, [res_id], report_service, {'model': template.model}, ctx)
+            
+                   # TODO in trunk, change return format to binary to match message_post expected format
                     result = base64.b64encode(result)
                     if not report_name:
                         report_name = 'report.' + report_service
@@ -392,6 +528,7 @@ class email_template(osv.osv):
 
         return results
 
+    @api.cr_uid_id_context
     def send_mail(self, cr, uid, template_id, res_id, force_send=False, raise_exception=False, context=None):
         """Generates a new mail message for the given template and record,
            and schedules it for delivery through the ``mail`` module's scheduler.
@@ -411,18 +548,9 @@ class email_template(osv.osv):
 
         # create a mail_mail based on values, without attachments
         values = self.generate_email(cr, uid, template_id, res_id, context=context)
-        assert values.get('email_from'), 'email_from is missing or empty after template rendering, send_mail() cannot proceed'
-
-        # process partner_to field that is a comma separated list of partner_ids -> recipient_ids
-        # NOTE: only usable if force_send is True, because otherwise the value is
-        # not stored on the mail_mail, and therefore lost -> fixed in v8
-        values['recipient_ids'] = []
-        partner_to = values.pop('partner_to', '')
-        if partner_to:
-            # placeholders could generate '', 3, 2 due to some empty field values
-            tpl_partner_ids = [pid for pid in partner_to.split(',') if pid]
-            values['recipient_ids'] += [(4, pid) for pid in self.pool['res.partner'].exists(cr, SUPERUSER_ID, tpl_partner_ids, context=context)]
-
+        if not values.get('email_from'):
+            raise osv.except_osv(_('Warning!'), _("Sender email is missing or empty after template rendering. Specify one to deliver your message"))
+        values['recipient_ids'] = [(4, pid) for pid in values.get('partner_ids', list())]
         attachment_ids = values.pop('attachment_ids', [])
         attachments = values.pop('attachments', [])
         msg_id = mail_mail.create(cr, uid, values, context=context)
@@ -437,6 +565,7 @@ class email_template(osv.osv):
                 'res_model': 'mail.message',
                 'res_id': mail.mail_message_id.id,
             }
+            context = dict(context)
             context.pop('default_type', None)
             attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
         if attachment_ids: