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.

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