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.0 KiB

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