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.

234 lines
8.1 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2013 XCG Consulting (http://odoo.consulting)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
  4. from cStringIO import StringIO
  5. import json
  6. import pkg_resources
  7. import os
  8. import sys
  9. from base64 import b64decode
  10. import requests
  11. from tempfile import NamedTemporaryFile
  12. from openerp import _
  13. from openerp import exceptions
  14. from openerp.report.report_sxw import report_sxw, rml_parse
  15. from openerp import registry
  16. from py3o.template.helpers import Py3oConvertor
  17. from py3o.template import Template
  18. _extender_functions = {}
  19. class TemplateNotFound(Exception):
  20. pass
  21. def py3o_report_extender(report_name):
  22. """
  23. A decorator to define function to extend the context sent to a template.
  24. This will be called at the creation of the report.
  25. The following arguments will be passed to it:
  26. - pool: the model pool
  27. - cr: the database cursor
  28. - uid: the id of the user that call the renderer
  29. - localcontext: The context that will be passed to the report engine
  30. - context: the Odoo context
  31. Method copied from CampToCamp report_webkit module.
  32. :param report_name: xml id of the report
  33. :return: a decorated class
  34. """
  35. def fct1(fct):
  36. lst = _extender_functions.get(report_name)
  37. if not lst:
  38. lst = []
  39. _extender_functions[report_name] = lst
  40. lst.append(fct)
  41. return fct
  42. return fct1
  43. class Py3oParser(report_sxw):
  44. """Custom class that use Py3o to render libroffice reports.
  45. Code partially taken from CampToCamp's webkit_report."""
  46. def __init__(self, name, table, rml=False, parser=rml_parse,
  47. header=False, store=False, register=True):
  48. self.localcontext = {}
  49. super(Py3oParser, self).__init__(
  50. name, table, rml=rml, parser=parser,
  51. header=header, store=store, register=register
  52. )
  53. def get_template(self, report_obj):
  54. """private helper to fetch the template data either from the database
  55. or from the default template file provided by the implementer.
  56. ATM this method takes a report definition recordset
  57. to try and fetch the report template from database. If not found it
  58. will fallback to the template file referenced in the report definition.
  59. @param report_obj: a recordset representing the report defintion
  60. @type report_obj: openerp.model.recordset instance
  61. @returns: string or buffer containing the template data
  62. @raises: TemplateNotFound which is a subclass of
  63. openerp.exceptions.DeferredException
  64. """
  65. tmpl_data = None
  66. if report_obj.py3o_template_id and report_obj.py3o_template_id.id:
  67. # if a user gave a report template
  68. tmpl_data = b64decode(
  69. report_obj.py3o_template_id.py3o_template_data
  70. )
  71. elif report_obj.py3o_template_fallback and report_obj.module:
  72. # if the default is defined
  73. flbk_filename = pkg_resources.resource_filename(
  74. "openerp.addons.%s" % report_obj.module,
  75. report_obj.py3o_template_fallback,
  76. )
  77. if os.path.exists(flbk_filename):
  78. # and it exists on the fileystem
  79. with open(flbk_filename, 'r') as tmpl:
  80. tmpl_data = tmpl.read()
  81. if tmpl_data is None:
  82. # if for any reason the template is not found
  83. raise TemplateNotFound(
  84. _(u'No template found. Aborting.'),
  85. sys.exc_info(),
  86. )
  87. return tmpl_data
  88. def create_single_pdf(self, cr, uid, ids, data, report_xml, context=None):
  89. """ Overide this function to generate our py3o report
  90. """
  91. if report_xml.report_type != 'py3o':
  92. return super(Py3oParser, self).create_single_pdf(
  93. cr, uid, ids, data, report_xml, context=context
  94. )
  95. pool = registry(cr.dbname)
  96. model_data_ids = pool['ir.model.data'].search(
  97. cr, uid, [
  98. ('model', '=', 'ir.actions.report.xml'),
  99. ('res_id', '=', report_xml.id),
  100. ]
  101. )
  102. xml_id = None
  103. if model_data_ids:
  104. model_data = pool['ir.model.data'].browse(
  105. cr, uid, model_data_ids[0], context=context
  106. )
  107. xml_id = '%s.%s' % (model_data.module, model_data.name)
  108. parser_instance = self.parser(cr, uid, self.name2, context=context)
  109. parser_instance.set_context(
  110. self.getObjects(cr, uid, ids, context),
  111. data, ids, report_xml.report_type
  112. )
  113. if xml_id in _extender_functions:
  114. for fct in _extender_functions[xml_id]:
  115. fct(pool, cr, uid, parser_instance.localcontext, context)
  116. tmpl_data = self.get_template(report_xml)
  117. in_stream = StringIO(tmpl_data)
  118. out_stream = StringIO()
  119. template = Template(in_stream, out_stream)
  120. expressions = template.get_all_user_python_expression()
  121. py_expression = template.convert_py3o_to_python_ast(expressions)
  122. convertor = Py3oConvertor()
  123. data_struct = convertor(py_expression)
  124. filetype = report_xml.py3o_fusion_filetype
  125. datadict = parser_instance.localcontext
  126. parsed_datadict = data_struct.render(datadict)
  127. fusion_server_obj = pool.get('py3o.server')
  128. fusion_server_ids = fusion_server_obj.search(
  129. cr, uid, [('is_active', '=', True)], context=context, limit=1
  130. )
  131. if not fusion_server_ids:
  132. if filetype.fusion_ext == report_xml.py3o_template_id.filetype:
  133. # No format conversion is needed, render the template directly
  134. template.render(parsed_datadict)
  135. res = out_stream.getvalue()
  136. else:
  137. raise exceptions.MissingError(
  138. _(u"No Py3o server configuration found")
  139. )
  140. else: # Call py3o.server to render the template in the desired format
  141. fusion_server_id = fusion_server_ids[0]
  142. fusion_server = fusion_server_obj.browse(
  143. cr, uid, fusion_server_id, context=context
  144. )
  145. in_stream.seek(0)
  146. files = {
  147. 'tmpl_file': in_stream,
  148. }
  149. fields = {
  150. "targetformat": filetype.fusion_ext,
  151. "datadict": json.dumps(parsed_datadict),
  152. "image_mapping": "{}",
  153. }
  154. r = requests.post(fusion_server.url, data=fields, files=files)
  155. if r.status_code != 200:
  156. # server says we have an issue... let's tell that to enduser
  157. raise exceptions.Warning(
  158. _('Fusion server error %s') % r.text,
  159. )
  160. # Here is a little joke about Odoo
  161. # we do nice chunked reading from the network...
  162. chunk_size = 1024
  163. with NamedTemporaryFile(
  164. suffix=filetype.human_ext,
  165. prefix='py3o-template-'
  166. ) as fd:
  167. for chunk in r.iter_content(chunk_size):
  168. fd.write(chunk)
  169. fd.seek(0)
  170. # ... but odoo wants the whole data in memory anyways :)
  171. res = fd.read()
  172. return res, filetype.human_ext
  173. def create(self, cr, uid, ids, data, context=None):
  174. """ Override this function to handle our py3o report
  175. """
  176. pool = registry(cr.dbname)
  177. ir_action_report_obj = pool['ir.actions.report.xml']
  178. report_xml_ids = ir_action_report_obj.search(
  179. cr, uid, [('report_name', '=', self.name[7:])], context=context
  180. )
  181. if not report_xml_ids:
  182. return super(Py3oParser, self).create(
  183. cr, uid, ids, data, context=context
  184. )
  185. report_xml = ir_action_report_obj.browse(
  186. cr, uid, report_xml_ids[0], context=context
  187. )
  188. result = self.create_source_pdf(
  189. cr, uid, ids, data, report_xml, context
  190. )
  191. if not result:
  192. return False, False
  193. return result