From 189c1c2b99b4dd53cf7239017d1f1646e6fddee4 Mon Sep 17 00:00:00 2001
From: Benjamin Dauvergne <bdauvergne@entrouvert.com>
Date: Tue, 11 Feb 2014 17:51:49 +0100
Subject: [PATCH 1/4] workflows: refactoring in ExportToModel

 - factorize building of the variable dictionnary for templates into the
	 context_from_formdata() method
 - factorize extraction of the model file content type
 - factorize templating on RTF files in a specific method
---
 wcs/workflows.py | 80 +++++++++++++++++++++++++++++++++++---------------------
 1 file changed, 50 insertions(+), 30 deletions(-)

diff --git a/wcs/workflows.py b/wcs/workflows.py
index 975bc9f..b5045b7 100644
--- a/wcs/workflows.py
+++ b/wcs/workflows.py
@@ -1141,40 +1141,44 @@ class SendmailWorkflowStatusItem(WorkflowStatusItem):
                     fire_and_forget=True)
 register_item_class(SendmailWorkflowStatusItem)
 
-
-def template_on_formdata(formdata, template, process=None):
-    dict = {}
-    dict.update(get_publisher().substitutions.get_context_variables())
-    dict['url'] = formdata.get_url()
-    dict['url_status'] = '%sstatus' % formdata.get_url()
-    dict['details'] = formdata.formdef.get_detailed_email_form(formdata, dict['url'])
-    dict['name'] = formdata.formdef.name
-    dict['number'] = formdata.id
+def context_from_formdata(formdata, process=None):
+    context = {}
+    context.update(get_publisher().substitutions.get_context_variables())
+    context['url'] = formdata.get_url()
+    context['url_status'] = '%sstatus' % formdata.get_url()
+    context['details'] = formdata.formdef.get_detailed_email_form(formdata, context['url'])
+    context['name'] = formdata.formdef.name
+    context['number'] = formdata.id
     if formdata.evolution and formdata.evolution[-1].comment:
-        dict['comment'] = formdata.evolution[-1].comment
+        context['comment'] = formdata.evolution[-1].comment
     else:
-        dict['comment'] = ''
-    dict.update(formdata.get_as_dict())
+        context['comment'] = ''
+    context.update(formdata.get_as_dict())
 
     # compatibility vars
-    dict['before'] = dict.get('form_previous_status')
-    dict['after'] = dict.get('form_status')
-    dict['evolution'] = dict.get('form_evolution')
+    context['before'] = context.get('form_previous_status')
+    context['after'] = context.get('form_status')
+    context['evolution'] = context.get('form_evolution')
 
     if process:
-        for key in dict:
-            dict[key] = process(dict[key])
+        for key in context:
+            context[key] = process(context[key])
 
     charset = get_publisher().site_charset
-    for k, v in dict.items():
+    for k, v in context.items():
         if isinstance(v, unicode):
-            dict[k] = v.encode(charset, 'ignore')
+            context[k] = v.encode(charset, 'ignore')
+
+    return context
+
+def template_on_formdata(formdata, template, process=None):
+    context = context_from_formdata(formdata, process=process)
 
     processor = ezt.Template(compress_whitespace=False)
     processor.parse(template or '')
 
     fd = StringIO()
-    processor.generate(fd, dict)
+    processor.generate(fd, context)
 
     return fd.getvalue()
 
@@ -1410,16 +1414,27 @@ class ExportToModel(WorkflowStatusItem):
                 evo.comment = _('Form exported in a model')
             return formdata.get_url() + self.get_directory_name()
 
-    def model_file_validation(self, upload):
+    def model_file_kind(self, upload):
+        if hasattr(upload, 'fp'):
+            fp = upload.fp
+        elif hasattr(upload, 'get_file'):
+            fp = upload.get_file()
+        else:
+            raise NotImplementedError
+        # RTF
         if upload.content_type and upload.content_type == 'application/rtf':
-            return True, ''
+            return 'rtf'
         if (upload.content_type and upload.content_type == 'application/octet-stream') or \
                 upload.content_type is None:
             if upload.base_filename and upload.base_filename.endswith('.rtf'):
-                return True, ''
-        upload.fp.seek(0)
-        if upload.read(10).startswith('{\\rtf'):
-            upload.fp.seek(0)
+                return 'rtf'
+        fp.seek(0)
+        if fp.read(10).startswith('{\\rtf'):
+            fp.seek(0)
+            return 'rtf'
+
+    def model_file_validation(self, upload):
+        if self.model_file_kind(upload) in ('rtf',):
             return True, ''
         return False, _('Only RTF files can be used')
 
@@ -1457,10 +1472,8 @@ class ExportToModel(WorkflowStatusItem):
         return qommon.misc.simplify(self.label or 'export_to_model', space='_')
     directory_name = property(get_directory_name)
 
-    def apply_template_to_formdata(self, formdata):
-        process = None
-        if self.model_file.base_filename.endswith('.rtf'):
-            process = rtf_process
+    def apply_template_to_formdata_rtf(self, formdata):
+        process = rtf_process
         try:
             return template_on_formdata(formdata, self.model_file.get_file().read(),
                     process=process)
@@ -1473,6 +1486,13 @@ class ExportToModel(WorkflowStatusItem):
             get_logger().error('error in template for export to model [%s], model could not be generated' % url)
             raise TemplatingError(_('Unknown error in the template: %s') % str(e))
 
+    def apply_template_to_formdata(self, formdata):
+        kind = self.model_file_kind(self.model_file)
+        if kind == 'rtf':
+            return self.apply_template_to_formdata_rtf(formdata)
+        else:
+            raise NotImplementedError
+
     def get_parameters(self):
         return ('label', 'model_file')
 
-- 
1.8.5.3

