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.

255 lines
9.5 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. #
  6. # Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved.
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import cStringIO
  23. from datetime import datetime
  24. from openerp.osv.fields import datetime as datetime_field
  25. from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
  26. import inspect
  27. from types import CodeType
  28. from openerp.report.report_sxw import report_sxw
  29. from openerp.modules.registry import RegistryManager
  30. import logging
  31. _logger = logging.getLogger(__name__)
  32. xls_types_default = {
  33. 'bool': False,
  34. 'date': None,
  35. 'text': '',
  36. 'number': 0,
  37. }
  38. try:
  39. import xlwt
  40. from xlwt.Style import default_style
  41. xls_types = {
  42. 'bool': xlwt.Row.set_cell_boolean,
  43. 'date': xlwt.Row.set_cell_date,
  44. 'text': xlwt.Row.set_cell_text,
  45. 'number': xlwt.Row.set_cell_number,
  46. }
  47. except ImportError: # pragma: no cover
  48. _logger.debug("Cannot import xlwt. This module will not be functional.")
  49. xls_types = xls_types_default
  50. default_style = None
  51. class AttrDict(dict):
  52. def __init__(self, *args, **kwargs):
  53. super(AttrDict, self).__init__(*args, **kwargs)
  54. self.__dict__ = self
  55. class report_xls(report_sxw):
  56. # TO DO: move parameters infra to configurable data
  57. # header/footer
  58. hf_params = {
  59. 'font_size': 8,
  60. 'font_style': 'I', # B: Bold, I: Italic, U: Underline
  61. }
  62. # styles
  63. _pfc = '26' # default pattern fore_color
  64. _bc = '22' # borders color
  65. decimal_format = '#,##0.00'
  66. date_format = 'YYYY-MM-DD'
  67. xls_styles = {
  68. 'xls_title': 'font: bold true, height 240;',
  69. 'bold': 'font: bold true;',
  70. 'underline': 'font: underline true;',
  71. 'italic': 'font: italic true;',
  72. 'fill': 'pattern: pattern solid, fore_color %s;' % _pfc,
  73. 'fill_blue': 'pattern: pattern solid, fore_color 27;',
  74. 'fill_grey': 'pattern: pattern solid, fore_color 22;',
  75. 'borders_all':
  76. 'borders: '
  77. 'left thin, right thin, top thin, bottom thin, '
  78. 'left_colour %s, right_colour %s, '
  79. 'top_colour %s, bottom_colour %s;'
  80. % (_bc, _bc, _bc, _bc),
  81. 'left': 'align: horz left;',
  82. 'center': 'align: horz center;',
  83. 'right': 'align: horz right;',
  84. 'wrap': 'align: wrap true;',
  85. 'top': 'align: vert top;',
  86. 'bottom': 'align: vert bottom;',
  87. }
  88. # TO DO: move parameters supra to configurable data
  89. def create(self, cr, uid, ids, data, context=None):
  90. self.pool = RegistryManager.get(cr.dbname)
  91. self.cr = cr
  92. self.uid = uid
  93. report_obj = self.pool.get('ir.actions.report.xml')
  94. report_ids = report_obj.search(
  95. cr, uid, [('report_name', '=', self.name[7:])], context=context)
  96. if report_ids:
  97. report_xml = report_obj.browse(
  98. cr, uid, report_ids[0], context=context)
  99. self.title = report_xml.name
  100. if report_xml.report_type == 'xls':
  101. return self.create_source_xls(cr, uid, ids, data, context)
  102. elif context.get('xls_export'):
  103. # use model from 'data' when no ir.actions.report.xml entry
  104. self.table = data.get('model') or self.table
  105. return self.create_source_xls(cr, uid, ids, data, context)
  106. return super(report_xls, self).create(cr, uid, ids, data, context)
  107. def create_source_xls(self, cr, uid, ids, data, context=None):
  108. if not context:
  109. context = {}
  110. parser_instance = self.parser(cr, uid, self.name2, context)
  111. self.parser_instance = parser_instance
  112. self.context = context
  113. objs = self.getObjects(cr, uid, ids, context)
  114. parser_instance.set_context(objs, data, ids, 'xls')
  115. objs = parser_instance.localcontext['objects']
  116. n = cStringIO.StringIO()
  117. # prevent style make error
  118. # http://stackoverflow.com/questions/17130516/xlwt-set-style-making-error-more-than-4094-xfs-styles
  119. wb = xlwt.Workbook(encoding='utf-8', style_compression=2)
  120. _p = AttrDict(parser_instance.localcontext)
  121. _xs = self.xls_styles
  122. self.xls_headers = {
  123. 'standard': '',
  124. }
  125. report_date = datetime_field.context_timestamp(
  126. cr, uid, datetime.now(), context)
  127. report_date = report_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
  128. self.xls_footers = {
  129. 'standard': (
  130. '&L&%(font_size)s&%(font_style)s' + report_date +
  131. '&R&%(font_size)s&%(font_style)s&P / &N'
  132. ) % self.hf_params,
  133. }
  134. self.generate_xls_report(_p, _xs, data, objs, wb)
  135. wb.save(n)
  136. n.seek(0)
  137. return (n.read(), 'xls')
  138. def render(self, wanted, col_specs, rowtype, render_space='empty'):
  139. """
  140. returns 'evaluated' col_specs
  141. Input:
  142. - wanted: element from the wanted_list
  143. - col_specs : cf. specs[1:] documented in xls_row_template method
  144. - rowtype : 'header' or 'data'
  145. - render_space : type dict, (caller_space + localcontext)
  146. if not specified
  147. """
  148. if render_space == 'empty':
  149. render_space = {}
  150. caller_space = inspect.currentframe().f_back.f_back.f_locals
  151. localcontext = self.parser_instance.localcontext
  152. render_space.update(caller_space)
  153. render_space.update(localcontext)
  154. row = col_specs[wanted][rowtype][:]
  155. for i in range(len(row)):
  156. if isinstance(row[i], CodeType):
  157. # TODO Use safe_eval or document why not and remove pylint hack
  158. row[i] = eval(row[i], render_space) # pylint: disable=W0123
  159. row.insert(0, wanted)
  160. return row
  161. def generate_xls_report(self, parser, xls_styles, data, objects, wb):
  162. """ override this method to create your excel file """
  163. raise NotImplementedError()
  164. def xls_row_template(self, specs, wanted_list):
  165. """
  166. Returns a row template.
  167. Input :
  168. - 'wanted_list': list of Columns that will be returned in the
  169. row_template
  170. - 'specs': list with Column Characteristics
  171. 0: Column Name (from wanted_list)
  172. 1: Column Colspan
  173. 2: Column Size (unit = the width of the character 0
  174. as it appears in the sheets default font)
  175. 3: Column Type
  176. 4: Column Data
  177. 5: Column Formula (or 'None' for Data)
  178. 6: Column Style
  179. """
  180. r = []
  181. col = 0
  182. for w in wanted_list:
  183. found = False
  184. for s in specs:
  185. if s[0] == w:
  186. found = True
  187. s_len = len(s)
  188. c = list(s[:5])
  189. # set write_cell_func or formula
  190. if s_len > 5 and s[5] is not None:
  191. c.append({'formula': s[5]})
  192. else:
  193. c.append({
  194. 'write_cell_func': xls_types[c[3]]})
  195. # Set custom cell style
  196. if s_len > 6 and s[6] is not None:
  197. c.append(s[6])
  198. else:
  199. c.append(None)
  200. # Set cell formula
  201. if s_len > 7 and s[7] is not None:
  202. c.append(s[7])
  203. else:
  204. c.append(None)
  205. r.append((col, c[1], c))
  206. col += c[1]
  207. break
  208. if not found:
  209. _logger.warn("report_xls.xls_row_template, "
  210. "column '%s' not found in specs", w)
  211. return r
  212. def xls_write_row(self, ws, row_pos, row_data,
  213. row_style=default_style, set_column_size=False):
  214. r = ws.row(row_pos)
  215. for col, size, spec in row_data:
  216. data = spec[4]
  217. formula = spec[5].get('formula') and \
  218. xlwt.Formula(spec[5]['formula']) or None
  219. style = spec[6] and spec[6] or row_style
  220. if not data:
  221. # if no data, use default values
  222. data = xls_types_default[spec[3]]
  223. if size != 1:
  224. if formula:
  225. ws.write_merge(
  226. row_pos, row_pos, col, col + size - 1, data, style)
  227. else:
  228. ws.write_merge(
  229. row_pos, row_pos, col, col + size - 1, data, style)
  230. else:
  231. if formula:
  232. ws.write(row_pos, col, formula, style)
  233. else:
  234. spec[5]['write_cell_func'](r, col, data, style)
  235. if set_column_size:
  236. ws.col(col).width = spec[2] * 256
  237. return row_pos + 1