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.

251 lines
9.4 KiB

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