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.

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