collective.documentgenerator 4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. collective/documentgenerator/DX_renderer.py +51 -0
  2. collective/documentgenerator/__init__.py +11 -0
  3. collective/documentgenerator/adapters.py +30 -0
  4. collective/documentgenerator/browser/__init__.py +0 -0
  5. collective/documentgenerator/browser/actionspanel.py +19 -0
  6. collective/documentgenerator/browser/check_pod_templates.pt +86 -0
  7. collective/documentgenerator/browser/children_pod_template.pt +27 -0
  8. collective/documentgenerator/browser/configure.zcml +217 -0
  9. collective/documentgenerator/browser/controlpanel.py +165 -0
  10. collective/documentgenerator/browser/generation_view.py +613 -0
  11. collective/documentgenerator/browser/overrides.py +9 -0
  12. collective/documentgenerator/browser/resources/css/documentgenerator.css +133 -0
  13. collective/documentgenerator/browser/static/.gitkeep +0 -0
  14. collective/documentgenerator/browser/static/configurable.svg +1232 -0
  15. collective/documentgenerator/browser/static/csv.svg +521 -0
  16. collective/documentgenerator/browser/static/doc.svg +23 -0
  17. collective/documentgenerator/browser/static/docx.svg +20 -0
  18. collective/documentgenerator/browser/static/download_icon.svg +54 -0
  19. collective/documentgenerator/browser/static/libreoffice-blanck.svg +481 -0
  20. collective/documentgenerator/browser/static/mailinglooptemplate.svg +1207 -0
  21. collective/documentgenerator/browser/static/missing_use.svg +42 -0
  22. collective/documentgenerator/browser/static/nok.svg +38 -0
  23. collective/documentgenerator/browser/static/nok_use.svg +38 -0
  24. collective/documentgenerator/browser/static/nok_used.svg +38 -0
  25. collective/documentgenerator/browser/static/odp.svg +1264 -0
  26. collective/documentgenerator/browser/static/ods.svg +1354 -0
  27. collective/documentgenerator/browser/static/odt.svg +1347 -0
  28. collective/documentgenerator/browser/static/ok.svg +38 -0
  29. collective/documentgenerator/browser/static/ok_use.svg +38 -0
  30. collective/documentgenerator/browser/static/ok_used.svg +38 -0
  31. collective/documentgenerator/browser/static/pdf.svg +557 -0
  32. collective/documentgenerator/browser/static/podtemplate.svg +1197 -0
  33. collective/documentgenerator/browser/static/rtf.svg +521 -0
  34. collective/documentgenerator/browser/static/style.svg +1207 -0
  35. collective/documentgenerator/browser/static/subtemplate.svg +1232 -0
  36. collective/documentgenerator/browser/static/xls.svg +159 -0
  37. collective/documentgenerator/browser/static/xlsx.svg +48 -0
  38. collective/documentgenerator/browser/table.py +326 -0
  39. collective/documentgenerator/browser/templates_listing.pt +29 -0
  40. collective/documentgenerator/browser/views.py +366 -0
  41. collective/documentgenerator/config.py +174 -0
  42. collective/documentgenerator/configure.zcml +51 -0
  43. collective/documentgenerator/content/__init__.py +0 -0
  44. collective/documentgenerator/content/condition.py +66 -0
  45. collective/documentgenerator/content/conditions.zcml +30 -0
  46. collective/documentgenerator/content/configure.zcml +18 -0
  47. collective/documentgenerator/content/document_factory.py +73 -0
  48. collective/documentgenerator/content/file_representation.py +70 -0
  49. collective/documentgenerator/content/file_representation.zcml +29 -0
  50. collective/documentgenerator/content/merge_templates.py +15 -0
  51. collective/documentgenerator/content/merge_templates.zcml +11 -0
  52. collective/documentgenerator/content/pod_template.py +601 -0
  53. collective/documentgenerator/content/style_template.py +54 -0
  54. collective/documentgenerator/content/vocabulary.py +344 -0
  55. collective/documentgenerator/content/vocabulary.zcml +105 -0
  56. collective/documentgenerator/demo/__init__.py +0 -0
  57. collective/documentgenerator/demo/configure.zcml +18 -0
  58. collective/documentgenerator/demo/helper.py +170 -0
  59. collective/documentgenerator/events/__init__.py +0 -0
  60. collective/documentgenerator/events/configure.zcml +44 -0
  61. collective/documentgenerator/events/pod_templates_events.py +66 -0
  62. collective/documentgenerator/events/styles_events.py +151 -0
  63. collective/documentgenerator/helper/__init__.py +7 -0
  64. collective/documentgenerator/helper/base.py +334 -0
  65. collective/documentgenerator/helper/configure.zcml +34 -0
  66. collective/documentgenerator/helper/dexterity.py +178 -0
  67. collective/documentgenerator/interfaces.py +166 -0
  68. collective/documentgenerator/locales/collective.documentgenerator.pot +564 -0
  69. collective/documentgenerator/locales/es/LC_MESSAGES/collective.documentgenerator.po +572 -0
  70. collective/documentgenerator/locales/es/LC_MESSAGES/plone.po +32 -0
  71. collective/documentgenerator/locales/fr/LC_MESSAGES/collective.documentgenerator.po +566 -0
  72. collective/documentgenerator/locales/fr/LC_MESSAGES/plone.po +27 -0
  73. collective/documentgenerator/locales/manual.pot +30 -0
  74. collective/documentgenerator/locales/plone-manual.pot +22 -0
  75. collective/documentgenerator/locales/plone.pot +30 -0
  76. collective/documentgenerator/locales/update.sh +22 -0
  77. collective/documentgenerator/migrations/__init__.py +0 -0
  78. collective/documentgenerator/migrations/migrate_to_11.py +52 -0
  79. collective/documentgenerator/migrations/migrate_to_12.py +32 -0
  80. collective/documentgenerator/migrations/migrate_to_13.py +35 -0
  81. collective/documentgenerator/migrations/migrate_to_3.py +36 -0
  82. collective/documentgenerator/migrations/migrate_to_5.py +30 -0
  83. collective/documentgenerator/migrations/migrate_to_6.py +27 -0
  84. collective/documentgenerator/migrations/migrate_to_7.py +34 -0
  85. collective/documentgenerator/migrations/migrate_to_8.py +36 -0
  86. collective/documentgenerator/migrations/migrate_to_9.py +50 -0
  87. collective/documentgenerator/profiles/base/browserlayer.xml +6 -0
  88. collective/documentgenerator/profiles/base/controlpanel.xml +21 -0
  89. collective/documentgenerator/profiles/base/metadata.xml +8 -0
  90. collective/documentgenerator/profiles/base/registry.xml +48 -0
  91. collective/documentgenerator/profiles/base/types/ConfigurablePODTemplate.xml +69 -0
  92. collective/documentgenerator/profiles/base/types/MailingLoopTemplate.xml +68 -0
  93. collective/documentgenerator/profiles/base/types/PODTemplate.xml +68 -0
  94. collective/documentgenerator/profiles/base/types/StyleTemplate.xml +68 -0
  95. collective/documentgenerator/profiles/base/types/SubTemplate.xml +68 -0
  96. collective/documentgenerator/profiles/base/types.xml +22 -0
  97. collective/documentgenerator/profiles/base/viewlets.xml +10 -0
  98. collective/documentgenerator/profiles/demo/browserlayer.xml +6 -0
  99. collective/documentgenerator/profiles/demo/collectivedocumentgenerator_demo_marker.txt +0 -0
  100. collective/documentgenerator/profiles/demo/import_steps.xml +11 -0
  101. collective/documentgenerator/profiles/demo/metadata.xml +7 -0
  102. collective/documentgenerator/profiles/demo/registry.xml +14 -0
  103. collective/documentgenerator/profiles/demo/templates/mailing.odt +0 -0
  104. collective/documentgenerator/profiles/demo/templates/modele_general.ods +0 -0
  105. collective/documentgenerator/profiles/demo/templates/modele_general.odt +0 -0
  106. collective/documentgenerator/profiles/demo/templates/mod/303/250le_collection.odt +0 -0
  107. collective/documentgenerator/profiles/demo/templates/possibly_mailed_model.odt +0 -0
  108. collective/documentgenerator/profiles/demo/templates/styles.odt +0 -0
  109. collective/documentgenerator/profiles/demo/templates/styles_2.odt +0 -0
  110. collective/documentgenerator/profiles/demo/templates/sub_template.odt +0 -0
  111. collective/documentgenerator/profiles/demo/viewlets.xml +3 -0
  112. collective/documentgenerator/profiles/testing/metadata.xml +7 -0
  113. collective/documentgenerator/profiles/testing/types/member.xml +114 -0
  114. collective/documentgenerator/profiles/testing/types.xml +9 -0
  115. collective/documentgenerator/profiles/uninstall/browserlayer.xml +7 -0
  116. collective/documentgenerator/profiles/uninstall/controlpanel.xml +21 -0
  117. collective/documentgenerator/profiles/uninstall/metadata.xml +4 -0
  118. collective/documentgenerator/profiles/uninstall/registry.xml +14 -0
  119. collective/documentgenerator/profiles/uninstall/types.xml +27 -0
  120. collective/documentgenerator/profiles/uninstall/viewlets.xml +8 -0
  121. collective/documentgenerator/profiles.zcml +209 -0
  122. collective/documentgenerator/renderer.zcml +36 -0
  123. collective/documentgenerator/search_replace/__init__.py +0 -0
  124. collective/documentgenerator/search_replace/configure.zcml +21 -0
  125. collective/documentgenerator/search_replace/pod_template.py +161 -0
  126. collective/documentgenerator/search_replace/search_result_form.pt +76 -0
  127. collective/documentgenerator/search_replace/searchreplace_panel.pt +31 -0
  128. collective/documentgenerator/search_replace/searchreplace_panel.py +274 -0
  129. collective/documentgenerator/setuphandlers.py +297 -0
  130. collective/documentgenerator/testing.py +278 -0
  131. collective/documentgenerator/testing.zcml +17 -0
  132. collective/documentgenerator/tests/__init__.py +0 -0
  133. collective/documentgenerator/tests/failing_template.odt +0 -0
  134. collective/documentgenerator/tests/robot/.gitkeep +0 -0
  135. collective/documentgenerator/tests/template_to_clean.odt +0 -0
  136. collective/documentgenerator/tests/template_without_style_page.odt +0 -0
  137. collective/documentgenerator/tests/test_DX_helper_view.py +398 -0
  138. collective/documentgenerator/tests/test_base_helper_view.py +216 -0
  139. collective/documentgenerator/tests/test_check_podtemplates_view.py +138 -0
  140. collective/documentgenerator/tests/test_config.py +119 -0
  141. collective/documentgenerator/tests/test_configurable_pod_template.py +467 -0
  142. collective/documentgenerator/tests/test_demo_profile.py +121 -0
  143. collective/documentgenerator/tests/test_events.py +187 -0
  144. collective/documentgenerator/tests/test_generation_view.py +680 -0
  145. collective/documentgenerator/tests/test_mailing_loop_template.py +48 -0
  146. collective/documentgenerator/tests/test_pod_template.py +190 -0
  147. collective/documentgenerator/tests/test_robot.py +26 -0
  148. collective/documentgenerator/tests/test_search_replace.py +485 -0
  149. collective/documentgenerator/tests/test_setup.py +77 -0
  150. collective/documentgenerator/tests/test_style_template.py +19 -0
  151. collective/documentgenerator/tests/test_sub_template.py +49 -0
  152. collective/documentgenerator/tests/test_templates_listing_view.py +120 -0
  153. collective/documentgenerator/tests/test_utils.py +205 -0
  154. collective/documentgenerator/tests/test_vocabulary.py +169 -0
  155. collective/documentgenerator/utils.py +245 -0
  156. collective/documentgenerator/viewlets/__init__.py +0 -0
  157. collective/documentgenerator/viewlets/batchactions.py +14 -0
  158. collective/documentgenerator/viewlets/configure.zcml +17 -0
  159. collective/documentgenerator/viewlets/generationlinks.pt +46 -0
  160. collective/documentgenerator/viewlets/generationlinks.py +67 -0
  161. collective.documentgenerator-4.0-py3.12-nspkg.pth +1 -0
  162. collective_documentgenerator-4.0.dist-info/METADATA +1136 -0
  163. collective_documentgenerator-4.0.dist-info/RECORD +167 -0
  164. collective_documentgenerator-4.0.dist-info/WHEEL +5 -0
  165. collective_documentgenerator-4.0.dist-info/entry_points.txt +2 -0
  166. collective_documentgenerator-4.0.dist-info/namespace_packages.txt +1 -0
  167. collective_documentgenerator-4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,613 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .. import _
4
+ from AccessControl import Unauthorized
5
+ from appy.pod.renderer import CsvOptions
6
+ from appy.pod.renderer import Renderer
7
+ from appy.pod.styles_manager import TableProperties
8
+ from collective.documentgenerator import config
9
+ from collective.documentgenerator import utils
10
+ from collective.documentgenerator.content.pod_template import IPODTemplate
11
+ from collective.documentgenerator.interfaces import CyclicMergeTemplatesException
12
+ from collective.documentgenerator.interfaces import IDocumentFactory
13
+ from collective.documentgenerator.interfaces import PODTemplateNotFoundError
14
+ from collective.documentgenerator.utils import remove_tmp_file
15
+ from collective.documentgenerator.utils import temporary_file_name
16
+ from plone import api
17
+ from plone.app.uuid.utils import uuidToObject
18
+ from plone.i18n.normalizer.interfaces import IFileNameNormalizer
19
+ from Products.CMFPlone.utils import base_hasattr
20
+ from Products.CMFPlone.utils import safe_unicode
21
+ from Products.Five import BrowserView
22
+ from zope.annotation.interfaces import IAnnotations
23
+ from zope.component import getMultiAdapter
24
+ from zope.component import queryAdapter
25
+ from zope.component import queryUtility
26
+
27
+ import io
28
+ import mimetypes
29
+ import os
30
+ import pkg_resources
31
+ import unicodedata
32
+
33
+
34
+ HAS_FINGERPOINTING = None
35
+
36
+ try:
37
+ pkg_resources.get_distribution("collective.fingerpointing")
38
+ except pkg_resources.DistributionNotFound:
39
+ HAS_FINGERPOINTING = False
40
+ else:
41
+ HAS_FINGERPOINTING = True
42
+
43
+
44
+ class DocumentGenerationView(BrowserView):
45
+ """
46
+ Document generation view.
47
+ """
48
+
49
+ def __init__(self, context, request):
50
+ self.context = context
51
+ self.request = request
52
+ self.pod_template = None
53
+ self.output_format = None
54
+
55
+ def __call__(self, template_uid="", output_format="", **kwargs):
56
+ self.pod_template, self.output_format = self._get_base_args(
57
+ template_uid, output_format
58
+ )
59
+ return self.generate_and_download_doc(
60
+ self.pod_template, self.output_format, **kwargs
61
+ )
62
+
63
+ def _get_base_args(self, template_uid, output_format):
64
+ template_uid = template_uid or self.get_pod_template_uid()
65
+ pod_template = self.get_pod_template(template_uid)
66
+ output_format = output_format or self.get_generation_format()
67
+ if not output_format:
68
+ raise Exception("No 'output_format' found to generate this document")
69
+
70
+ return pod_template, output_format
71
+
72
+ def generate_and_download_doc(self, pod_template, output_format, **kwargs):
73
+ """
74
+ Generate a document of format 'output_format' from the template
75
+ 'pod_template' and return it as a downloadable file.
76
+ """
77
+ if HAS_FINGERPOINTING:
78
+ from collective.fingerpointing.config import AUDIT_MESSAGE
79
+ from collective.fingerpointing.logger import log_info
80
+ from collective.fingerpointing.utils import get_request_information
81
+
82
+ # add logging message to fingerpointing log
83
+ user, ip = get_request_information()
84
+ action = "generate_document"
85
+ extras = "context={0} pod_template={1} output_format={2}".format(
86
+ "/".join(self.context.getPhysicalPath()),
87
+ "/".join(pod_template.getPhysicalPath()),
88
+ output_format,
89
+ )
90
+ allowed_parameters = filter(
91
+ None, os.getenv("DOCUMENTGENERATOR_LOG_PARAMETERS", "").split(",")
92
+ )
93
+ if allowed_parameters:
94
+ for key, value in self.request.form.items():
95
+ if key in allowed_parameters:
96
+ extras = "{0} {1}={2}".format(extras, key, value)
97
+ log_info(AUDIT_MESSAGE.format(user, ip, action, extras))
98
+
99
+ doc, doc_name, gen_context = self._generate_doc(
100
+ pod_template, output_format, **kwargs
101
+ )
102
+ self._set_header_response(doc_name)
103
+ return doc
104
+
105
+ def _generate_doc(self, pod_template, output_format, **kwargs):
106
+ """
107
+ Generate a document of format 'output_format' from the template
108
+ 'pod_template'.
109
+ """
110
+ if not pod_template.can_be_generated(self.context):
111
+ raise Unauthorized("You are not allowed to generate this document.")
112
+
113
+ if output_format not in pod_template.get_available_formats():
114
+ raise Exception(
115
+ "Asked output format '{0}' "
116
+ "is not available for template '{1}'!".format(
117
+ output_format, pod_template.getId()
118
+ )
119
+ )
120
+
121
+ # subtemplates should not refer to each other in a cyclic way.
122
+ self._check_cyclic_merges(pod_template)
123
+
124
+ # Recursive generation of the document and all its subtemplates.
125
+ document_path, gen_context = self._recursive_generate_doc(
126
+ pod_template, output_format, **kwargs
127
+ )
128
+
129
+ rendered_document = open(document_path, "rb")
130
+ rendered = rendered_document.read()
131
+ rendered_document.close()
132
+ remove_tmp_file(document_path)
133
+ filename = self._get_filename()
134
+ return rendered, filename, gen_context
135
+
136
+ def _get_filename(self):
137
+ """ """
138
+ # we limit filename to 120 characters
139
+ first_part = u"{0} {1}".format(
140
+ self.pod_template.title, safe_unicode(self.context.Title())
141
+ )
142
+ # replace unicode special characters with ascii equivalent value
143
+ first_part = unicodedata.normalize("NFKD", first_part).encode("ascii", "ignore")
144
+ util = queryUtility(IFileNameNormalizer)
145
+ # remove '-' from first_part because it is handled by cropName that manages max_length
146
+ # and it behaves weirdly if it encounters '-'
147
+ # moreover avoid more than one blank space at a time
148
+ first_part = u" ".join(
149
+ util.normalize(first_part).replace(u"-", u" ").split()
150
+ ).strip()
151
+ filename = "{0}.{1}".format(
152
+ util.normalize(first_part, max_length=120), self.output_format
153
+ )
154
+ return filename
155
+
156
+ def _recursive_generate_doc(self, pod_template, output_format, **kwargs):
157
+ """
158
+ Generate a document recursively by starting to generate all its
159
+ subtemplates before merging them in the final document.
160
+ Return the file path of the generated document.
161
+ """
162
+ sub_templates = pod_template.get_templates_to_merge()
163
+ sub_documents = {}
164
+ for context_name, (sub_pod, do_rendering) in iter(sub_templates.items()):
165
+ # Force the subtemplate output_format to 'odt' because appy.pod
166
+ # can only merge documents in this format.
167
+ if do_rendering:
168
+ sub_documents[context_name] = self._recursive_generate_doc(
169
+ pod_template=sub_pod, output_format="odt"
170
+ )[0]
171
+ else:
172
+ sub_documents[context_name] = sub_pod
173
+
174
+ document_path, gen_context = self._render_document(
175
+ pod_template, output_format, sub_documents, **kwargs
176
+ )
177
+
178
+ return document_path, gen_context
179
+
180
+ def get_pod_template(self, template_uid):
181
+ """
182
+ Return the default PODTemplate that will be used when calling
183
+ this view.
184
+ """
185
+ catalog = api.portal.get_tool("portal_catalog")
186
+
187
+ template_brains = catalog.unrestrictedSearchResults(
188
+ object_provides=IPODTemplate.__identifier__, UID=template_uid
189
+ )
190
+ if not template_brains:
191
+ raise PODTemplateNotFoundError(
192
+ "Couldn't find POD template with UID '{0}'".format(template_uid)
193
+ )
194
+
195
+ template_path = template_brains[0].getPath()
196
+ pod_template = self.context.unrestrictedTraverse(template_path)
197
+ return pod_template
198
+
199
+ def get_pod_template_uid(self):
200
+ template_uid = self.request.get("template_uid", "")
201
+ return template_uid
202
+
203
+ def get_generation_format(self):
204
+ """
205
+ Return the default document output format that will be used
206
+ when calling this view.
207
+ """
208
+ output_format = self.request.get("output_format")
209
+ return output_format
210
+
211
+ def _render_document(
212
+ self, pod_template, output_format, sub_documents, raiseOnError=False, **kwargs
213
+ ):
214
+ """
215
+ Render a single document of type 'output_format' using the odt file
216
+ 'document_template' as the generation template.
217
+ Subdocuments is a dictionnary of previously generated subtemplate
218
+ that will be merged into the current generated document.
219
+ """
220
+ document_template = pod_template.get_file()
221
+ temp_filename = temporary_file_name(
222
+ ".{extension}".format(extension=output_format)
223
+ )
224
+
225
+ # Prepare rendering context
226
+ helper_view = self.get_generation_context_helper()
227
+ generation_context = self._get_generation_context(
228
+ helper_view, pod_template=pod_template
229
+ )
230
+
231
+ # enrich the generation context with previously generated documents
232
+ utils.update_dict_with_validation(
233
+ generation_context,
234
+ sub_documents,
235
+ _("Error when merging merge_templates in generation context"),
236
+ )
237
+
238
+ # enable optimalColumnWidths if enabled in the config and/or on ConfigurablePodTemplate
239
+ stylesMapping = {}
240
+ optimalColumnWidths = "OCW_.*"
241
+ distributeColumns = "DC_.*"
242
+
243
+ column_modifier = pod_template.get_column_modifier()
244
+ if column_modifier == -1:
245
+ column_modifier = config.get_column_modifier()
246
+
247
+ if column_modifier == "disabled":
248
+ optimalColumnWidths = False
249
+ distributeColumns = False
250
+ else:
251
+ stylesMapping = {
252
+ "table": TableProperties(
253
+ columnModifier=column_modifier != "nothing"
254
+ and column_modifier
255
+ or None
256
+ )
257
+ }
258
+
259
+ # if raiseOnError is not enabled, enabled it in the config excepted if user is a Manager
260
+ # and currently generated document use odt format
261
+ if not raiseOnError:
262
+ if config.get_raiseOnError_for_non_managers():
263
+ raiseOnError = True
264
+ if "Manager" in api.user.get_roles() and output_format == "odt":
265
+ raiseOnError = False
266
+
267
+ # stylesMapping.update({'para[class=None, parent != cell]': 'texte_delibe',
268
+ # 'para[class=xSmallText, parent != cell]': 'bodyXSmall',
269
+ # 'para[class=smallText, parent != cell]': 'bodySmall',
270
+ # 'para[class=largeText, parent != cell]': 'bodyLarge',
271
+ # 'para[class=xLargeText, parent != cell]': 'bodyXLarge',
272
+ # 'para[class=indentation, parent != cell]': 'bodyIndentation',
273
+ # 'para[class=None, parent = cell]': 'cell_delibe',
274
+ # 'table': TableProperties(cellContentStyle='cell_delibe'),
275
+ # 'para[class=xSmallText, parent = cell]': 'cellXSmall',
276
+ # 'para[class=smallText, parent = cell]': 'cellSmall',
277
+ # 'para[class=largeText, parent = cell]': 'cellLarge',
278
+ # 'para[class=xLargeText, parent = cell]': 'cellXLarge',
279
+ # 'para[class=indentation, parent = cell]': 'cellIndentation',
280
+ # })
281
+ # stylesMapping.update({'para[class=None,parent!=cell]': 'texte_delibe',
282
+ # 'para[class=xSmallText,parent!=cell]': 'bodyXSmall',
283
+ # 'para[class=smallText,parent!=cell]': 'bodySmall',
284
+ # 'para[class=largeText,parent!=cell]': 'bodyLarge',
285
+ # 'para[class=xLargeText,parent!=cell]': 'bodyXLarge',
286
+ # 'para[class=indentation,parent!=cell]': 'bodyIndentation',
287
+ # 'para[class=xSmallText,parent=cell]': 'cellXSmall',
288
+ # 'para[class=smallText,parent=cell]': 'cellSmall',
289
+ # 'para[class=largeText,parent=cell]': 'cellLarge',
290
+ # 'para[class=xLargeText,parent=cell]': 'cellXLarge',
291
+ # 'para[class=indentation,parent=cell]': 'cellIndentation',
292
+ # })
293
+
294
+ csvOptions = None
295
+
296
+ if output_format == "csv":
297
+ csvOptions = CsvOptions(
298
+ fieldSeparator=pod_template.csv_field_delimiter,
299
+ textDelimiter=pod_template.csv_string_delimiter,
300
+ )
301
+ renderer = Renderer(
302
+ io.BytesIO(document_template.data),
303
+ generation_context,
304
+ temp_filename,
305
+ pythonWithUnoPath=config.get_uno_path(),
306
+ ooServer=config.get_oo_server(),
307
+ ooPort=config.get_oo_port_list(),
308
+ raiseOnError=raiseOnError,
309
+ findImage=api.portal.get(),
310
+ forceOoCall=True,
311
+ html=True,
312
+ optimalColumnWidths=optimalColumnWidths,
313
+ distributeColumns=distributeColumns,
314
+ stylesMapping=stylesMapping,
315
+ stream=config.get_use_stream(),
316
+ csvOptions=csvOptions,
317
+ # deleteTempFolder=False,
318
+ **kwargs
319
+ )
320
+
321
+ # it is only now that we can initialize helper view's appy pod renderer
322
+ all_helper_views = self.get_views_for_appy_renderer(
323
+ generation_context, helper_view
324
+ )
325
+ for view in all_helper_views:
326
+ view._set_appy_renderer(renderer)
327
+
328
+ renderer.run()
329
+
330
+ # return also generation_context to test ist content in tests
331
+ return temp_filename, generation_context
332
+
333
+ def _get_context_variables(self, pod_template):
334
+ if base_hasattr(pod_template, "get_context_variables"):
335
+ return pod_template.get_context_variables()
336
+ return {}
337
+
338
+ def _get_generation_context(self, helper_view, pod_template):
339
+ """
340
+ Return the generation context for the current document.
341
+ """
342
+ generation_context = self.get_base_generation_context(helper_view, pod_template)
343
+ utils.update_dict_with_validation(
344
+ generation_context,
345
+ {
346
+ "context": getattr(helper_view, "context", None),
347
+ "portal": api.portal.get(),
348
+ "view": helper_view,
349
+ },
350
+ _("Error when merging helper_view in generation context"),
351
+ )
352
+ utils.update_dict_with_validation(
353
+ generation_context,
354
+ self._get_context_variables(pod_template),
355
+ _("Error when merging context_variables in generation context"),
356
+ )
357
+ return generation_context
358
+
359
+ def get_base_generation_context(self, helper_view, pod_template):
360
+ """
361
+ Override this method to provide your own generation context.
362
+ """
363
+ return {}
364
+
365
+ def get_generation_context_helper(self):
366
+ """
367
+ Return the default helper view used for document generation.
368
+ """
369
+ helper_view = getMultiAdapter(
370
+ (self.context, self.request), name="document_generation_helper_view"
371
+ )
372
+ helper_view.pod_template = self.pod_template
373
+ helper_view.output_format = self.output_format
374
+ return helper_view
375
+
376
+ def get_views_for_appy_renderer(self, generation_context, helper_view):
377
+ views = []
378
+ if "view" in generation_context:
379
+ # helper_view has maybe changed in generation context getter
380
+ views.append(generation_context["view"])
381
+ else:
382
+ views.append(helper_view)
383
+
384
+ return views
385
+
386
+ def _set_header_response(self, filename):
387
+ """
388
+ Tell the browser that the resulting page contains ODT.
389
+ """
390
+ response = self.request.RESPONSE
391
+ mimetype = mimetypes.guess_type(filename)[0]
392
+ response.setHeader("Content-type", mimetype)
393
+ response.setHeader(
394
+ "Content-disposition",
395
+ u'inline;filename="{}"'.format(filename).encode("utf-8"),
396
+ )
397
+
398
+ def _check_cyclic_merges(self, pod_template):
399
+ """
400
+ Check if the template 'pod_template' has subtemplates referring to each
401
+ other in a cyclic way.
402
+ """
403
+
404
+ def traverse_check(pod_template, path):
405
+
406
+ if pod_template in path:
407
+ path.append(pod_template)
408
+ start_cycle = path.index(pod_template)
409
+ start_msg = " --> ".join(
410
+ [
411
+ '"{}" {}'.format(t.Title(), "/".join(t.getPhysicalPath()))
412
+ for t in path[:start_cycle]
413
+ ]
414
+ )
415
+ cycle_msg = " <--> ".join(
416
+ [
417
+ '"{}" {}'.format(t.Title(), "/".join(t.getPhysicalPath()))
418
+ for t in path[start_cycle:]
419
+ ]
420
+ )
421
+ msg = "{} -> CYCLE:\n{}".format(start_msg, cycle_msg)
422
+ raise CyclicMergeTemplatesException(msg)
423
+
424
+ new_path = list(path)
425
+ new_path.append(pod_template)
426
+
427
+ sub_templates = pod_template.get_templates_to_merge()
428
+
429
+ for name, (sub_template, do_rendering) in iter(sub_templates.items()):
430
+ traverse_check(sub_template, new_path)
431
+
432
+ traverse_check(pod_template, [])
433
+
434
+
435
+ class PersistentDocumentGenerationView(DocumentGenerationView):
436
+ """
437
+ Persistent document generation view.
438
+ """
439
+
440
+ def __call__(self, template_uid="", output_format="", generated_doc_title=""):
441
+ self.generated_doc_title = generated_doc_title
442
+ self.pod_template, self.output_format = self._get_base_args(
443
+ template_uid, output_format
444
+ )
445
+ persisted_doc = self.generate_persistent_doc(
446
+ self.pod_template, self.output_format
447
+ )
448
+ self.redirects(persisted_doc)
449
+
450
+ def add_mailing_infos(self, doc, gen_context):
451
+ """store mailing informations on generated doc"""
452
+ annot = IAnnotations(doc)
453
+ if "mailed_data" in gen_context or "mailing_list" in gen_context:
454
+ annot["documentgenerator"] = {
455
+ "need_mailing": False,
456
+ "template_uid": self.pod_template.UID(),
457
+ }
458
+ else:
459
+ annot["documentgenerator"] = {
460
+ "need_mailing": True,
461
+ "template_uid": self.pod_template.UID(),
462
+ "output_format": self.output_format,
463
+ "context_uid": self.context.UID(),
464
+ }
465
+
466
+ def _get_title(self, doc_name, gen_context):
467
+ splitted_name = doc_name.split(".")
468
+ title = self.generated_doc_title or self.pod_template.title
469
+ extension = splitted_name[-1]
470
+ return safe_unicode(title), extension
471
+
472
+ def generate_persistent_doc(self, pod_template, output_format):
473
+ """
474
+ Generate a document of format 'output_format' from the template
475
+ 'pod_template' and persist it by creating a File containing the
476
+ generated document on the current context.
477
+ """
478
+
479
+ doc, doc_name, gen_context = self._generate_doc(pod_template, output_format)
480
+
481
+ title, extension = self._get_title(doc_name, gen_context)
482
+
483
+ factory = queryAdapter(self.context, IDocumentFactory)
484
+
485
+ # Bypass any File creation permission of the user. If the user isnt
486
+ # supposed to save generated document on the site, then its the permission
487
+ # to call the generation view that should be changed.
488
+ with api.env.adopt_roles(["Manager"]):
489
+ persisted_doc = factory.create(
490
+ doc_file=doc, title=title, extension=extension
491
+ )
492
+
493
+ # store informations on persisted doc
494
+ self.add_mailing_infos(persisted_doc, gen_context)
495
+
496
+ return persisted_doc
497
+
498
+ def redirects(self, persisted_doc):
499
+ """
500
+ Redirects to the created document.
501
+ """
502
+ filename = persisted_doc.file.filename
503
+ self._set_header_response(filename)
504
+ response = self.request.response
505
+ return response.redirect(persisted_doc.absolute_url() + "/external_edit")
506
+
507
+ def mailing_related_generation_context(self, helper_view, gen_context):
508
+ """
509
+ Add mailing related information in generation context
510
+ """
511
+ # We add mailed_data if we have only one element in mailing list
512
+ mailing_list = helper_view.mailing_list(gen_context)
513
+ if len(mailing_list) == 0:
514
+ utils.update_dict_with_validation(
515
+ gen_context,
516
+ {"mailed_data": None},
517
+ _("Error when merging mailed_data in generation context"),
518
+ )
519
+ elif len(mailing_list) == 1:
520
+ utils.update_dict_with_validation(
521
+ gen_context,
522
+ {"mailed_data": mailing_list[0]},
523
+ _("Error when merging mailed_data in generation context"),
524
+ )
525
+
526
+ def _get_generation_context(self, helper_view, pod_template):
527
+ """ """
528
+ gen_context = super(
529
+ PersistentDocumentGenerationView, self
530
+ )._get_generation_context(helper_view, pod_template)
531
+ self.mailing_related_generation_context(helper_view, gen_context)
532
+ return gen_context
533
+
534
+
535
+ class MailingLoopPersistentDocumentGenerationView(PersistentDocumentGenerationView):
536
+ """
537
+ Mailing persistent document generation view.
538
+ This view use a MailingLoopTemplate to loop on a document when replacing some variables in.
539
+ """
540
+
541
+ def __call__(self, document_uid="", document_url_path="", generated_doc_title=""):
542
+ self.generated_doc_title = generated_doc_title
543
+ document_uid = document_uid or self.request.get("document_uid", "")
544
+ document_url_path = document_url_path or self.request.get(
545
+ "document_url_path", ""
546
+ )
547
+ if not document_uid and not document_url_path:
548
+ raise Exception(
549
+ "No 'document_uid' or 'url_path' found to generate this document"
550
+ )
551
+ elif document_url_path:
552
+ site = api.portal.get()
553
+ self.document = site.restrictedTraverse(document_url_path)
554
+ else:
555
+ self.document = uuidToObject(document_uid)
556
+ if not self.document:
557
+ raise Exception("Cannot find document with UID '{0}'".format(document_uid))
558
+ self.pod_template, self.output_format = self._get_base_args("", "")
559
+ persisted_doc = self.generate_persistent_doc(
560
+ self.pod_template, self.output_format
561
+ )
562
+ self.redirects(persisted_doc)
563
+
564
+ def _get_base_args(self, template_uid, output_format):
565
+ annot = IAnnotations(self.document).get("documentgenerator", "")
566
+ if not annot or "template_uid" not in annot:
567
+ raise Exception(
568
+ "Cannot find 'template_uid' on document '{0}'".format(
569
+ self.document.absolute_url()
570
+ )
571
+ )
572
+ self.orig_template = self.get_pod_template(annot["template_uid"])
573
+ if (
574
+ not base_hasattr(self.orig_template, "mailing_loop_template")
575
+ or not self.orig_template.mailing_loop_template
576
+ ):
577
+ raise Exception(
578
+ "Cannot find 'mailing_loop_template' on template '{0}'".format(
579
+ self.orig_template.absolute_url()
580
+ )
581
+ )
582
+ loop_template = self.get_pod_template(self.orig_template.mailing_loop_template)
583
+
584
+ if "output_format" not in annot:
585
+ raise Exception("No 'output_format' found to generate this document")
586
+ return loop_template, annot["output_format"]
587
+
588
+ def mailing_related_generation_context(self, helper_view, gen_context):
589
+ """
590
+ Add mailing related information in generation context
591
+ """
592
+ # We do nothing here because we have to call mailing_list after original template context variable inclusion
593
+
594
+ def _get_generation_context(self, helper_view, pod_template):
595
+ """ """
596
+ gen_context = super(
597
+ MailingLoopPersistentDocumentGenerationView, self
598
+ )._get_generation_context(helper_view, pod_template)
599
+ # add variable context from original template
600
+ utils.update_dict_with_validation(
601
+ gen_context,
602
+ self._get_context_variables(self.orig_template),
603
+ _("Error when merging context_variables in generation context"),
604
+ )
605
+ # add mailing list in generation context
606
+ dic = {
607
+ "mailing_list": helper_view.mailing_list(gen_context),
608
+ "mailed_doc": self.document,
609
+ }
610
+ utils.update_dict_with_validation(
611
+ gen_context, dic, _("Error when merging mailing_list in generation context")
612
+ )
613
+ return gen_context
@@ -0,0 +1,9 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from collective.documentgenerator.browser.views import ViewConfigurablePodTemplate
4
+ from collective.documentviewer.browser.views import DocumentViewerView
5
+
6
+
7
+ class DGDXDocumentViewerView(ViewConfigurablePodTemplate, DocumentViewerView):
8
+ """The documentviewer view from collective.documentviewer overrides the default DX
9
+ view, so override it again so our own override is taken into account."""