From fb71686abf58243118653c5dee87a5b42a6dde0d Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Fri, 4 Dec 2020 12:46:26 +0100
Subject: [PATCH] admin: add export/import on single mail template (#46094)

---
 tests/test_mail_templates.py                  | 62 +++++++++++++++
 wcs/admin/mail_templates.py                   | 78 ++++++++++++++++++-
 .../wcs/backoffice/mail-template.html         |  1 -
 .../wcs/backoffice/mail-templates.html        |  1 +
 4 files changed, 137 insertions(+), 5 deletions(-)

diff --git a/tests/test_mail_templates.py b/tests/test_mail_templates.py
index a49be0dd..a2260a5e 100644
--- a/tests/test_mail_templates.py
+++ b/tests/test_mail_templates.py
@@ -1,15 +1,18 @@
 # -*- coding: utf-8 -*-
 
 import base64
 import os
 import pytest
+from webtest import Upload
+import xml.etree.ElementTree as ET
 
 from django.utils.encoding import force_bytes
+from django.utils.six import StringIO
 from quixote import cleanup
 from wcs.formdef import FormDef
 from wcs.fields import FileField
 from wcs.logged_errors import LoggedError
 from wcs.mail_templates import MailTemplate
 from wcs.workflows import Workflow, SendmailWorkflowStatusItem
 from wcs.qommon.http_request import HTTPRequest
 from wcs.qommon.form import PicklableUpload
@@ -62,16 +65,26 @@ def mail_templates_option(pub):
     if not pub.site_options.has_section('options'):
         pub.site_options.add_section('options')
     pub.site_options.set('options', 'mail-templates', 'true')
     with open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w') as fd:
         pub.site_options.write(fd)
     return pub
 
 
+@pytest.fixture
+def mail_template():
+    MailTemplate.wipe()
+    mail_template = MailTemplate(name='test MT')
+    mail_template.subject = 'test subject'
+    mail_template.body = 'test body'
+    mail_template.store()
+    return mail_template
+
+
 def test_mail_templates_disabled(pub, superuser):
     if not pub.site_options.has_section('options'):
         pub.site_options.add_section('options')
     pub.site_options.set('options', 'mail-templates', 'false')
     with open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w') as fd:
         pub.site_options.write(fd)
     app = login(get_app(pub))
     resp = app.get('/backoffice/workflows/')
@@ -290,8 +303,57 @@ def test_workflow_send_mail_template_attachments(pub, superuser, mail_templates_
     emails.empty()
     item.attachments = ['form_var_file1_raw']
     item.perform(formdata)
     pub.get_request().response.process_after_jobs()
     payloads = emails.get('test subject')['msg'].get_payload()
     assert len(payloads) == 3
     assert payloads[1].get_content_type() == 'image/jpeg'
     assert payloads[2].get_content_type() == 'image/jpeg'
+
+
+def test_mail_templates_export(pub, superuser, mail_template):
+    app = login(get_app(pub))
+    resp = app.get('/backoffice/workflows/mail-templates/1/')
+
+    resp = resp.click(href='export')
+    xml_export = resp.text
+
+    ds = StringIO(xml_export)
+    mail_template2 = MailTemplate.import_from_xml(ds)
+    assert mail_template2.name == 'test MT'
+
+
+def test_mail_templates_import(pub, superuser, mail_template):
+    mail_template.slug = 'foobar'
+    mail_template.store()
+    mail_template_xml = ET.tostring(mail_template.export_to_xml(include_id=True))
+    MailTemplate.wipe()
+    assert MailTemplate.count() == 0
+
+    app = login(get_app(pub))
+    resp = app.get('/backoffice/workflows/mail-templates/')
+    resp = resp.click(href='import')
+    resp.forms[0]['file'] = Upload('mail_template.wcs', mail_template_xml)
+    resp = resp.forms[0].submit()
+    assert MailTemplate.count() == 1
+    assert set([wc.slug for wc in MailTemplate.select()]) == set(['foobar'])
+
+    # check slug
+    resp = app.get('/backoffice/workflows/mail-templates/')
+    resp = resp.click(href='import')
+    resp.forms[0]['file'] = Upload('mail_template.wcs', mail_template_xml)
+    resp = resp.forms[0].submit()
+    assert MailTemplate.count() == 2
+    assert set([wc.slug for wc in MailTemplate.select()]) == set(['foobar', 'test-mt'])
+    resp = app.get('/backoffice/workflows/mail-templates/')
+    resp = resp.click(href='import')
+    resp.forms[0]['file'] = Upload('mail_template.wcs', mail_template_xml)
+    resp = resp.forms[0].submit()
+    assert MailTemplate.count() == 3
+    assert set([wc.slug for wc in MailTemplate.select()]) == set(['foobar', 'test-mt', 'test-mt-1'])
+
+    # import an invalid file
+    resp = app.get('/backoffice/workflows/mail-templates/')
+    resp = resp.click(href='import')
+    resp.form['file'] = Upload('mail_template.wcs', b'garbage')
+    resp = resp.form.submit()
+    assert 'Invalid File' in resp.text
diff --git a/wcs/admin/mail_templates.py b/wcs/admin/mail_templates.py
index 3fb6b01b..18daee1d 100644
--- a/wcs/admin/mail_templates.py
+++ b/wcs/admin/mail_templates.py
@@ -9,29 +9,31 @@
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, see <http://www.gnu.org/licenses/>.
 
+import xml.etree.ElementTree as ET
+
 from quixote import get_publisher, get_response, redirect
 from quixote.directory import Directory
 from quixote.html import TemplateIO, htmltext
 
-from wcs.qommon import _, errors, template
+from wcs.qommon import _, errors, force_str, misc, template
 from wcs.qommon.backoffice.menu import html_top
 from wcs.qommon.form import (Form, HtmlWidget, StringWidget, TextWidget,
-        ComputedExpressionWidget, WidgetList)
+        ComputedExpressionWidget, WidgetList, FileWidget, get_session)
 from wcs.mail_templates import MailTemplate
 
 
 class MailTemplatesDirectory(Directory):
-    _q_exports = ['', 'new']
+    _q_exports = ['', 'new', ('import', 'p_import')]
     do_not_call_in_templates = True
 
     def _q_traverse(self, path):
         get_response().breadcrumb.append(('mail-templates/', _('Mail Templates')))
         return super(MailTemplatesDirectory, self)._q_traverse(path)
 
     def _q_lookup(self, component):
         return MailTemplatePage(component)
@@ -57,30 +59,88 @@ class MailTemplatesDirectory(Directory):
 
         get_response().breadcrumb.append(('new', _('New Mail Template')))
         html_top('mail_templates', title=_('New Mail Template'))
         r = TemplateIO(html=True)
         r += htmltext('<h2>%s</h2>') % _('New Mail Template')
         r += form.render()
         return r.getvalue()
 
+    def p_import(self):
+        form = Form(enctype='multipart/form-data')
+        import_title = _('Import Mail Template call')
+
+        form.add(FileWidget, 'file', title=_('File'), required=True)
+        form.add_submit('submit', import_title)
+        form.add_submit('cancel', _('Cancel'))
+
+        if form.get_submit() == 'cancel':
+            return redirect('.')
+
+        if form.is_submitted() and not form.has_errors():
+            try:
+                return self.import_submit(form)
+            except ValueError:
+                pass
+
+        get_response().breadcrumb.append(('import', _('Import')))
+        html_top('mail_templates', title=import_title)
+        r = TemplateIO(html=True)
+        r += htmltext('<h2>%s</h2>') % import_title
+        r += htmltext('<p>%s</p>') % _(
+            'You can install a new mail template by uploading a file.')
+        r += form.render()
+        return r.getvalue()
+
+    def import_submit(self, form):
+        fp = form.get_widget('file').parse().fp
+
+        error = False
+        try:
+            mail_template = MailTemplate.import_from_xml(fp)
+            get_session().message = (
+                'info', _('This mail template has been successfully imported.'))
+        except ValueError:
+            error = True
+
+        if error:
+            form.set_error('file', _('Invalid File'))
+            raise ValueError()
+
+        # check slug unicity
+        known_slugs = {
+            x.slug: x.id for x in MailTemplate.select(ignore_migration=True, ignore_errors=True)}
+        if mail_template.slug in known_slugs:
+            mail_template.slug = None  # a new one will be set in .store()
+        mail_template.store()
+        return redirect('%s/' % mail_template.id)
+
 
 class MailTemplatePage(Directory):
-    _q_exports = ['', 'edit', 'delete']
+    _q_exports = ['', 'edit', 'delete', 'export', ]
     do_not_call_in_templates = True
 
     def __init__(self, mail_template_id):
         try:
             self.mail_template = MailTemplate.get(mail_template_id)
         except KeyError:
             raise errors.TraversalError()
         get_response().breadcrumb.append((mail_template_id + '/', self.mail_template.name))
 
+    def get_sidebar(self):
+        r = TemplateIO(html=True)
+        r += htmltext('<ul id="sidebar-actions">')
+        r += htmltext('<li><a href="export">%s</a></li>') % _('Export')
+        r += htmltext('<li><a href="delete" rel="popup">%s</a></li>') % _('Delete')
+        r += htmltext('</ul>')
+        return r.getvalue()
+
     def _q_index(self):
         html_top('mail_templates', title=self.mail_template.name)
+        get_response().filter['sidebar'] = self.get_sidebar()
         return template.QommonTemplateResponse(
                 templates=['wcs/backoffice/mail-template.html'],
                 context={'view': self, 'mail_template': self.mail_template})
 
     def get_form(self):
         form = Form(enctype='multipart/form-data', advanced_label=_('Additional options'))
         form.add(StringWidget, 'name', title=_('Name'), required=True, size=30,
                 value=self.mail_template.name)
@@ -175,8 +235,18 @@ class MailTemplatePage(Directory):
             html_top('mail_templates', title=_('Delete Mail Template'))
             r = TemplateIO(html=True)
             r += htmltext('<h2>%s %s</h2>') % (_('Deleting Mail Template:'), self.mail_template.name)
             r += form.render()
             return r.getvalue()
         else:
             self.mail_template.remove_self()
             return redirect('..')
+
+    def export(self):
+        x = self.mail_template.export_to_xml(include_id=True)
+        misc.indent_xml(x)
+        response = get_response()
+        response.set_content_type('application/x-wcs-mail-template')
+        response.set_header(
+            'content-disposition',
+            'attachment; filename=mail-template-%s.wcs' % self.mail_template.slug)
+        return '<?xml version="1.0"?>\n' + force_str(ET.tostring(x))
diff --git a/wcs/templates/wcs/backoffice/mail-template.html b/wcs/templates/wcs/backoffice/mail-template.html
index eeb59108..f6797534 100644
--- a/wcs/templates/wcs/backoffice/mail-template.html
+++ b/wcs/templates/wcs/backoffice/mail-template.html
@@ -1,15 +1,14 @@
 {% extends "wcs/backoffice/base.html" %}
 {% load i18n %}
 
 {% block appbar-title %}{% trans "Mail Template" %} - {{ mail_template.name }}{% endblock %}
 
 {% block appbar-actions %}
-<a href="delete">{% trans "Delete" %}</a>
 <a href="edit">{% trans "Edit" %}</a>
 {% endblock %}
 
 {% block content %}
 {% if mail_template.description %}
 <div class="bo-block">{{ mail_template.description }}</div>
 {% endif %}
 
diff --git a/wcs/templates/wcs/backoffice/mail-templates.html b/wcs/templates/wcs/backoffice/mail-templates.html
index cbbbed2f..2b9e74d1 100644
--- a/wcs/templates/wcs/backoffice/mail-templates.html
+++ b/wcs/templates/wcs/backoffice/mail-templates.html
@@ -1,14 +1,15 @@
 {% extends "wcs/backoffice/base.html" %}
 {% load i18n %}
 
 {% block appbar-title %}{% trans "Mail Templates" %}{% endblock %}
 
 {% block appbar-actions %}
+<a rel="popup" href="import">{% trans "Import" %}</a>
 <a rel="popup" href="new">{% trans "New mail template" %}</a>
 {% endblock %}
 
 {% block content %}
 {% if mail_templates %}
 <ul class="objects-list single-links">
   {% for mail_template in mail_templates %}
   <li><a href="{{ mail_template.id }}/">{{ mail_template.name }}</a></li>
-- 
2.29.2

