OCA reporting engine fork for dev and update.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

370 lines
14 KiB

  1. # Copyright 2013 XCG Consulting (http://odoo.consulting)
  2. # Copyright 2016 ACSONE SA/NV
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
  4. import base64
  5. import logging
  6. import os
  7. import subprocess
  8. import sys
  9. import tempfile
  10. from base64 import b64decode
  11. from contextlib import closing
  12. from io import BytesIO
  13. from zipfile import ZIP_DEFLATED, ZipFile
  14. import pkg_resources
  15. from odoo import _, api, fields, models, tools
  16. from ._py3o_parser_context import Py3oParserContext
  17. logger = logging.getLogger(__name__)
  18. try:
  19. from py3o.template import Template
  20. from py3o import formats
  21. except ImportError:
  22. logger.debug("Cannot import py3o.template")
  23. try:
  24. from py3o.formats import Formats, UnkownFormatException
  25. except ImportError:
  26. logger.debug("Cannot import py3o.formats")
  27. try:
  28. from PyPDF2 import PdfFileWriter, PdfFileReader
  29. except ImportError:
  30. logger.debug("Cannot import PyPDF2")
  31. _extender_functions = {}
  32. class TemplateNotFound(Exception):
  33. pass
  34. def py3o_report_extender(report_xml_id=None):
  35. """
  36. A decorator to define function to extend the context sent to a template.
  37. This will be called at the creation of the report.
  38. The following arguments will be passed to it:
  39. - ir_report: report instance
  40. - localcontext: The context that will be passed to the report engine
  41. If no report_xml_id is given the extender is registered for all py3o
  42. reports
  43. Idea copied from CampToCamp report_webkit module.
  44. :param report_xml_id: xml id of the report
  45. :return: a decorated class
  46. """
  47. global _extender_functions
  48. def fct1(fct):
  49. _extender_functions.setdefault(report_xml_id, []).append(fct)
  50. return fct
  51. return fct1
  52. @py3o_report_extender()
  53. def default_extend(report_xml, context):
  54. context["report_xml"] = report_xml
  55. class Py3oReport(models.TransientModel):
  56. _name = "py3o.report"
  57. _description = "Report Py30"
  58. ir_actions_report_id = fields.Many2one(
  59. comodel_name="ir.actions.report", required=True
  60. )
  61. def _is_valid_template_path(self, path):
  62. """ Check if the path is a trusted path for py3o templates.
  63. """
  64. real_path = os.path.realpath(path)
  65. root_path = tools.config.get_misc("report_py3o", "root_tmpl_path")
  66. if not root_path:
  67. logger.warning(
  68. "You must provide a root template path into odoo.cfg to be "
  69. "able to use py3o template configured with an absolute path "
  70. "%s",
  71. real_path,
  72. )
  73. return False
  74. is_valid = real_path.startswith(root_path + os.path.sep)
  75. if not is_valid:
  76. logger.warning(
  77. "Py3o template path is not valid. %s is not a child of root " "path %s",
  78. real_path,
  79. root_path,
  80. )
  81. return is_valid
  82. def _is_valid_template_filename(self, filename):
  83. """ Check if the filename can be used as py3o template
  84. """
  85. if filename and os.path.isfile(filename):
  86. fname, ext = os.path.splitext(filename)
  87. ext = ext.replace(".", "")
  88. try:
  89. fformat = Formats().get_format(ext)
  90. if fformat and fformat.native:
  91. return True
  92. except UnkownFormatException:
  93. logger.warning("Invalid py3o template %s", filename, exc_info=1)
  94. logger.warning("%s is not a valid Py3o template filename", filename)
  95. return False
  96. def _get_template_from_path(self, tmpl_name):
  97. """ Return the template from the path to root of the module if specied
  98. or an absolute path on your server
  99. """
  100. if not tmpl_name:
  101. return None
  102. report_xml = self.ir_actions_report_id
  103. flbk_filename = None
  104. if report_xml.module:
  105. # if the default is defined
  106. flbk_filename = pkg_resources.resource_filename(
  107. "odoo.addons.%s" % report_xml.module, tmpl_name
  108. )
  109. elif self._is_valid_template_path(tmpl_name):
  110. flbk_filename = os.path.realpath(tmpl_name)
  111. if self._is_valid_template_filename(flbk_filename):
  112. with open(flbk_filename, "rb") as tmpl:
  113. return tmpl.read()
  114. return None
  115. def _get_template_fallback(self, model_instance):
  116. """
  117. Return the template referenced in the report definition
  118. :return:
  119. """
  120. self.ensure_one()
  121. report_xml = self.ir_actions_report_id
  122. return self._get_template_from_path(report_xml.py3o_template_fallback)
  123. def get_template(self, model_instance):
  124. """private helper to fetch the template data either from the database
  125. or from the default template file provided by the implementer.
  126. ATM this method takes a report definition recordset
  127. to try and fetch the report template from database. If not found it
  128. will fallback to the template file referenced in the report definition.
  129. @returns: string or buffer containing the template data
  130. @raises: TemplateNotFound which is a subclass of
  131. odoo.exceptions.DeferredException
  132. """
  133. self.ensure_one()
  134. report_xml = self.ir_actions_report_id
  135. if report_xml.py3o_template_id.py3o_template_data:
  136. # if a user gave a report template
  137. tmpl_data = b64decode(report_xml.py3o_template_id.py3o_template_data)
  138. else:
  139. tmpl_data = self._get_template_fallback(model_instance)
  140. if tmpl_data is None:
  141. # if for any reason the template is not found
  142. raise TemplateNotFound(_("No template found. Aborting."), sys.exc_info())
  143. return tmpl_data
  144. def _extend_parser_context(self, context, report_xml):
  145. # add default extenders
  146. for fct in _extender_functions.get(None, []):
  147. fct(report_xml, context)
  148. # add extenders for registered on the template
  149. xml_id = report_xml.get_external_id().get(report_xml.id)
  150. if xml_id in _extender_functions:
  151. for fct in _extender_functions[xml_id]:
  152. fct(report_xml, context)
  153. def _get_parser_context(self, model_instance, data):
  154. report_xml = self.ir_actions_report_id
  155. context = Py3oParserContext(self.env).localcontext
  156. context.update(report_xml._get_rendering_context(model_instance.ids, data))
  157. context["objects"] = model_instance
  158. self._extend_parser_context(context, report_xml)
  159. return context
  160. def _postprocess_report(self, model_instance, result_path):
  161. if len(model_instance) == 1 and self.ir_actions_report_id.attachment:
  162. with open(result_path, "rb") as f:
  163. # we do all the generation process using files to avoid memory
  164. # consumption...
  165. # ... but odoo wants the whole data in memory anyways :)
  166. buffer = BytesIO(f.read())
  167. self.ir_actions_report_id._postprocess_pdf_report(model_instance, buffer)
  168. return result_path
  169. def _create_single_report(self, model_instance, data):
  170. """ This function to generate our py3o report
  171. """
  172. self.ensure_one()
  173. result_fd, result_path = tempfile.mkstemp(
  174. suffix=".ods", prefix="p3o.report.tmp."
  175. )
  176. tmpl_data = self.get_template(model_instance)
  177. in_stream = BytesIO(tmpl_data)
  178. with closing(os.fdopen(result_fd, "wb+")) as out_stream:
  179. template = Template(in_stream, out_stream, escape_false=True)
  180. localcontext = self._get_parser_context(model_instance, data)
  181. template.render(localcontext)
  182. out_stream.seek(0)
  183. tmpl_data = out_stream.read()
  184. if self.env.context.get("report_py3o_skip_conversion"):
  185. return result_path
  186. result_path = self._convert_single_report(result_path, model_instance, data)
  187. return self._postprocess_report(model_instance, result_path)
  188. def _convert_single_report(self, result_path, model_instance, data):
  189. """Run a command to convert to our target format"""
  190. if not self.ir_actions_report_id.is_py3o_native_format:
  191. with tempfile.TemporaryDirectory() as tmp_user_installation:
  192. command = self._convert_single_report_cmd(
  193. result_path,
  194. model_instance,
  195. data,
  196. user_installation=tmp_user_installation,
  197. )
  198. logger.debug("Running command %s", command)
  199. output = subprocess.check_output(
  200. command, cwd=os.path.dirname(result_path)
  201. )
  202. logger.debug("Output was %s", output)
  203. self._cleanup_tempfiles([result_path])
  204. result_path, result_filename = os.path.split(result_path)
  205. result_path = os.path.join(
  206. result_path,
  207. "%s.%s"
  208. % (
  209. os.path.splitext(result_filename)[0],
  210. self.ir_actions_report_id.py3o_filetype,
  211. ),
  212. )
  213. return result_path
  214. def _convert_single_report_cmd(
  215. self, result_path, model_instance, data, user_installation=None
  216. ):
  217. """Return a command list suitable for use in subprocess.call"""
  218. lo_bin = self.ir_actions_report_id.lo_bin_path
  219. if not lo_bin:
  220. raise RuntimeError(
  221. _(
  222. "Libreoffice runtime not available. "
  223. "Please contact your administrator."
  224. )
  225. )
  226. cmd = [
  227. lo_bin,
  228. "--headless",
  229. "--convert-to",
  230. self.ir_actions_report_id.py3o_filetype,
  231. result_path,
  232. ]
  233. if user_installation:
  234. cmd.append("-env:UserInstallation=file:%s" % user_installation)
  235. return cmd
  236. def _get_or_create_single_report(
  237. self, model_instance, data, existing_reports_attachment
  238. ):
  239. self.ensure_one()
  240. attachment = existing_reports_attachment.get(model_instance.id)
  241. if attachment and self.ir_actions_report_id.attachment_use:
  242. content = base64.b64decode(attachment.datas)
  243. report_file = tempfile.mktemp("." + self.ir_actions_report_id.py3o_filetype)
  244. with open(report_file, "wb") as f:
  245. f.write(content)
  246. return report_file
  247. return self._create_single_report(model_instance, data)
  248. def _zip_results(self, reports_path):
  249. self.ensure_one()
  250. zfname_prefix = self.ir_actions_report_id.name
  251. result_path = tempfile.mktemp(suffix="zip", prefix="py3o-zip-result")
  252. with ZipFile(result_path, "w", ZIP_DEFLATED) as zf:
  253. cpt = 0
  254. for report in reports_path:
  255. fname = "%s_%d.%s" % (zfname_prefix, cpt, report.split(".")[-1])
  256. zf.write(report, fname)
  257. cpt += 1
  258. return result_path
  259. @api.model
  260. def _merge_pdf(self, reports_path):
  261. """ Merge PDF files into one.
  262. :param reports_path: list of path of pdf files
  263. :returns: path of the merged pdf
  264. """
  265. writer = PdfFileWriter()
  266. for path in reports_path:
  267. reader = PdfFileReader(path)
  268. writer.appendPagesFromReader(reader)
  269. merged_file_fd, merged_file_path = tempfile.mkstemp(
  270. suffix=".pdf", prefix="report.merged.tmp."
  271. )
  272. with closing(os.fdopen(merged_file_fd, "wb")) as merged_file:
  273. writer.write(merged_file)
  274. return merged_file_path
  275. def _merge_results(self, reports_path):
  276. self.ensure_one()
  277. filetype = self.ir_actions_report_id.py3o_filetype
  278. if not reports_path:
  279. return False, False
  280. if len(reports_path) == 1:
  281. return reports_path[0], filetype
  282. if filetype == formats.FORMAT_PDF:
  283. return self._merge_pdf(reports_path), formats.FORMAT_PDF
  284. else:
  285. return self._zip_results(reports_path), "zip"
  286. @api.model
  287. def _cleanup_tempfiles(self, temporary_files):
  288. # Manual cleanup of the temporary files
  289. for temporary_file in temporary_files:
  290. try:
  291. os.unlink(temporary_file)
  292. except (OSError, IOError):
  293. logger.error("Error when trying to remove file %s" % temporary_file)
  294. def create_report(self, res_ids, data):
  295. """ Override this function to handle our py3o report
  296. """
  297. model_instances = self.env[self.ir_actions_report_id.model].browse(res_ids)
  298. reports_path = []
  299. if len(res_ids) > 1 and self.ir_actions_report_id.py3o_multi_in_one:
  300. reports_path.append(self._create_single_report(model_instances, data))
  301. else:
  302. existing_reports_attachment = self.ir_actions_report_id._get_attachments(
  303. res_ids
  304. )
  305. for model_instance in model_instances:
  306. reports_path.append(
  307. self._get_or_create_single_report(
  308. model_instance, data, existing_reports_attachment
  309. )
  310. )
  311. result_path, filetype = self._merge_results(reports_path)
  312. reports_path.append(result_path)
  313. # Here is a little joke about Odoo
  314. # we do all the generation process using files to avoid memory
  315. # consumption...
  316. # ... but odoo wants the whole data in memory anyways :)
  317. with open(result_path, "r+b") as fd:
  318. res = fd.read()
  319. self._cleanup_tempfiles(set(reports_path))
  320. return res, filetype