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.

428 lines
14 KiB

8 years ago
8 years ago
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015-2017 Onestein (<http://www.onestein.eu>)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import json
  5. from odoo import api, fields, models, tools
  6. from odoo.exceptions import UserError
  7. from odoo.tools.translate import _
  8. class BveView(models.Model):
  9. _name = 'bve.view'
  10. _description = 'BI View Editor'
  11. @api.depends('group_ids')
  12. @api.multi
  13. def _compute_users(self):
  14. for bve_view in self:
  15. group_ids = bve_view.sudo().group_ids
  16. if group_ids:
  17. bve_view.user_ids = group_ids.mapped('users')
  18. else:
  19. bve_view.user_ids = self.env['res.users'].sudo().search([])
  20. @api.depends('name')
  21. @api.multi
  22. def _compute_model_name(self):
  23. for bve_view in self:
  24. name = [x for x in bve_view.name.lower() if x.isalnum()]
  25. model_name = ''.join(name).replace('_', '.').replace(' ', '.')
  26. bve_view.model_name = 'x_bve.' + model_name
  27. name = fields.Char(required=True, copy=False)
  28. model_name = fields.Char(compute='_compute_model_name', store=True)
  29. note = fields.Text(string='Notes')
  30. state = fields.Selection(
  31. [('draft', 'Draft'),
  32. ('created', 'Created')],
  33. default='draft',
  34. copy=False)
  35. data = fields.Text(
  36. help="Use the special query builder to define the query "
  37. "to generate your report dataset. "
  38. "NOTE: To be edited, the query should be in 'Draft' status.")
  39. action_id = fields.Many2one('ir.actions.act_window', string='Action')
  40. view_id = fields.Many2one('ir.ui.view', string='View')
  41. group_ids = fields.Many2many(
  42. 'res.groups',
  43. string='Groups',
  44. help="User groups allowed to see the generated report; "
  45. "if NO groups are specified the report will be public "
  46. "for everyone.")
  47. user_ids = fields.Many2many(
  48. 'res.users',
  49. string='Users',
  50. compute='_compute_users',
  51. store=True)
  52. _sql_constraints = [
  53. ('name_uniq',
  54. 'unique(name)',
  55. _('Custom BI View names must be unique!')),
  56. ]
  57. @classmethod
  58. def _get_format_data(cls, data):
  59. data = data.replace('\'', '"')
  60. data = data.replace(': u"', ':"')
  61. return data
  62. @api.multi
  63. def _create_view_arch(self):
  64. self.ensure_one()
  65. def _get_field_def(name, def_type=''):
  66. if not def_type:
  67. return ''
  68. return """<field name="x_{}" type="{}" />""".format(
  69. name, def_type
  70. )
  71. def _get_field_type(field_info):
  72. row = field_info['row'] and 'row'
  73. column = field_info['column'] and 'col'
  74. measure = field_info['measure'] and 'measure'
  75. return row or column or measure
  76. def _get_field_list(fields_info):
  77. view_fields = []
  78. for field_info in fields_info:
  79. field_name = field_info['name']
  80. def_type = _get_field_type(field_info)
  81. if def_type:
  82. field_def = _get_field_def(field_name, def_type)
  83. view_fields.append(field_def)
  84. return view_fields
  85. fields_info = json.loads(self._get_format_data(self.data))
  86. view_fields = _get_field_list(fields_info)
  87. return view_fields
  88. @api.multi
  89. def _create_tree_view_arch(self):
  90. self.ensure_one()
  91. def _get_field_def(name):
  92. return """<field name="x_{}" />""".format(
  93. name
  94. )
  95. def _get_field_list(fields_info):
  96. view_fields = []
  97. for field_info in fields_info:
  98. field_name = field_info['name']
  99. if field_info['list'] and 'join_node' not in field_info:
  100. field_def = _get_field_def(field_name)
  101. view_fields.append(field_def)
  102. return view_fields
  103. fields_info = json.loads(self._get_format_data(self.data))
  104. view_fields = _get_field_list(fields_info)
  105. return view_fields
  106. @api.multi
  107. def _create_bve_view(self):
  108. self.ensure_one()
  109. # create views
  110. View = self.env['ir.ui.view']
  111. old_views = View.sudo().search([('model', '=', self.model_name)])
  112. old_views.sudo().unlink()
  113. view_vals = [{
  114. 'name': 'Pivot Analysis',
  115. 'type': 'pivot',
  116. 'model': self.model_name,
  117. 'priority': 16,
  118. 'arch': """<?xml version="1.0"?>
  119. <pivot string="Pivot Analysis">
  120. {}
  121. </pivot>
  122. """.format("".join(self._create_view_arch()))
  123. }, {
  124. 'name': 'Graph Analysis',
  125. 'type': 'graph',
  126. 'model': self.model_name,
  127. 'priority': 16,
  128. 'arch': """<?xml version="1.0"?>
  129. <graph string="Graph Analysis"
  130. type="bar" stacked="True">
  131. {}
  132. </graph>
  133. """.format("".join(self._create_view_arch()))
  134. }, {
  135. 'name': 'Search BI View',
  136. 'type': 'search',
  137. 'model': self.model_name,
  138. 'priority': 16,
  139. 'arch': """<?xml version="1.0"?>
  140. <search string="Search BI View">
  141. {}
  142. </search>
  143. """.format("".join(self._create_view_arch()))
  144. }]
  145. for vals in view_vals:
  146. View.sudo().create(vals)
  147. # create Tree view
  148. tree_view = View.sudo().create({
  149. 'name': 'Tree Analysis',
  150. 'type': 'tree',
  151. 'model': self.model_name,
  152. 'priority': 16,
  153. 'arch': """<?xml version="1.0"?>
  154. <tree string="List Analysis" create="false">
  155. {}
  156. </tree>
  157. """.format("".join(self._create_tree_view_arch()))
  158. })
  159. # set the Tree view as the default one
  160. action_vals = {
  161. 'name': self.name,
  162. 'res_model': self.model_name,
  163. 'type': 'ir.actions.act_window',
  164. 'view_type': 'form',
  165. 'view_mode': 'tree,graph,pivot',
  166. 'view_id': tree_view.id,
  167. 'context': "{'service_name': '%s'}" % self.name,
  168. }
  169. ActWindow = self.env['ir.actions.act_window']
  170. action_id = ActWindow.sudo().create(action_vals)
  171. self.write({
  172. 'action_id': action_id.id,
  173. 'view_id': tree_view.id,
  174. 'state': 'created'
  175. })
  176. @api.multi
  177. def _build_access_rules(self, model):
  178. self.ensure_one()
  179. def group_ids_with_access(model_name, access_mode):
  180. # pylint: disable=sql-injection
  181. self.env.cr.execute('''SELECT
  182. g.id
  183. FROM
  184. ir_model_access a
  185. JOIN ir_model m ON (a.model_id=m.id)
  186. JOIN res_groups g ON (a.group_id=g.id)
  187. LEFT JOIN ir_module_category c ON (c.id=g.category_id)
  188. WHERE
  189. m.model=%s AND
  190. a.active IS True AND
  191. a.perm_''' + access_mode, (model_name,))
  192. return [x[0] for x in self.env.cr.fetchall()]
  193. info = json.loads(self._get_format_data(self.data))
  194. model_names = list(set([f['model'] for f in info]))
  195. read_groups = set.intersection(*[set(
  196. group_ids_with_access(model_name, 'read')
  197. ) for model_name in model_names])
  198. # read access
  199. for group in read_groups:
  200. self.env['ir.model.access'].sudo().create({
  201. 'name': 'read access to ' + self.model_name,
  202. 'model_id': model.id,
  203. 'group_id': group,
  204. 'perm_read': True,
  205. })
  206. # read and write access
  207. for group in self.group_ids:
  208. self.env['ir.model.access'].sudo().create({
  209. 'name': 'read-write access to ' + self.model_name,
  210. 'model_id': model.id,
  211. 'group_id': group.id,
  212. 'perm_read': True,
  213. 'perm_write': True,
  214. })
  215. @api.model
  216. def _create_sql_view(self):
  217. def get_fields_info(fields_data):
  218. fields_info = []
  219. for field_data in fields_data:
  220. field = self.env['ir.model.fields'].browse(field_data['id'])
  221. vals = {
  222. 'table': self.env[field.model_id.model]._table,
  223. 'table_alias': field_data['table_alias'],
  224. 'select_field': field.name,
  225. 'as_field': 'x_' + field_data['name'],
  226. 'join': False,
  227. 'model': field.model_id.model
  228. }
  229. if field_data.get('join_node'):
  230. vals.update({'join': field_data['join_node']})
  231. fields_info.append(vals)
  232. return fields_info
  233. def get_join_nodes(info):
  234. join_nodes = [
  235. (f['table_alias'],
  236. f['join'],
  237. f['select_field']) for f in info if f['join'] is not False]
  238. return join_nodes
  239. def get_tables(info):
  240. tables = set([(f['table'], f['table_alias']) for f in info])
  241. return tables
  242. def get_fields(info):
  243. return [("{}.{}".format(f['table_alias'],
  244. f['select_field']),
  245. f['as_field']) for f in info if 'join_node' not in f]
  246. def check_empty_data(data):
  247. if not data or data == '[]':
  248. raise UserError(_('No data to process.'))
  249. check_empty_data(self.data)
  250. formatted_data = json.loads(self._get_format_data(self.data))
  251. info = get_fields_info(formatted_data)
  252. select_fields = get_fields(info)
  253. tables = get_tables(info)
  254. join_nodes = get_join_nodes(info)
  255. table_name = self.model_name.replace('.', '_')
  256. # robustness in case something went wrong
  257. # pylint: disable=sql-injection
  258. self._cr.execute('DROP TABLE IF EXISTS "%s"' % table_name)
  259. basic_fields = [
  260. ("t0.id", "id")
  261. ]
  262. # pylint: disable=sql-injection
  263. q = """CREATE or REPLACE VIEW %s as (
  264. SELECT %s
  265. FROM %s
  266. WHERE %s
  267. )""" % (table_name, ','.join(
  268. ["{} AS {}".format(f[0], f[1])
  269. for f in basic_fields + select_fields]), ','.join(
  270. ["{} AS {}".format(t[0], t[1])
  271. for t in list(tables)]), " AND ".join(
  272. ["{}.{} = {}.id".format(j[0], j[2], j[1])
  273. for j in join_nodes] + ["TRUE"]))
  274. self.env.cr.execute(q)
  275. @api.multi
  276. def action_create(self):
  277. self.ensure_one()
  278. def _prepare_field(field_data):
  279. if not field_data['custom']:
  280. field = self.env['ir.model.fields'].browse(field_data['id'])
  281. vals = {
  282. 'name': 'x_' + field_data['name'],
  283. 'complete_name': field.complete_name,
  284. 'model': self.model_name,
  285. 'relation': field.relation,
  286. 'field_description': field_data.get(
  287. 'description', field.field_description),
  288. 'ttype': field.ttype,
  289. 'selection': field.selection,
  290. 'size': field.size,
  291. 'state': 'manual'
  292. }
  293. if vals['ttype'] == 'monetary':
  294. vals.update({'ttype': 'float'})
  295. if field.ttype == 'selection' and not field.selection:
  296. model_obj = self.env[field.model_id.model]
  297. selection = model_obj._fields[field.name].selection
  298. if callable(selection):
  299. selection_domain = selection(model_obj)
  300. else:
  301. selection_domain = selection
  302. vals.update({'selection': str(selection_domain)})
  303. return vals
  304. # clean dirty view (in case something went wrong)
  305. self.action_reset()
  306. # create sql view
  307. self._create_sql_view()
  308. # create model and fields
  309. data = json.loads(self._get_format_data(self.data))
  310. model_vals = {
  311. 'name': self.name,
  312. 'model': self.model_name,
  313. 'state': 'manual',
  314. 'field_id': [
  315. (0, 0, _prepare_field(field))
  316. for field in data
  317. if 'join_node' not in field]
  318. }
  319. Model = self.env['ir.model'].sudo().with_context(bve=True)
  320. model = Model.create(model_vals)
  321. # give access rights
  322. self._build_access_rules(model)
  323. # create tree, graph and pivot views
  324. self._create_bve_view()
  325. @api.multi
  326. def open_view(self):
  327. self.ensure_one()
  328. [action] = self.action_id.read()
  329. action['display_name'] = _('BI View')
  330. return action
  331. @api.multi
  332. def copy(self, default=None):
  333. self.ensure_one()
  334. default = dict(default or {}, name=_("%s (copy)") % self.name)
  335. return super(BveView, self).copy(default=default)
  336. @api.multi
  337. def action_reset(self):
  338. self.ensure_one()
  339. has_menus = False
  340. if self.action_id:
  341. action = 'ir.actions.act_window,%d' % (self.action_id.id,)
  342. menus = self.env['ir.ui.menu'].sudo().search(
  343. [('action', '=', action)]
  344. )
  345. has_menus = True if menus else False
  346. menus.sudo().unlink()
  347. if self.action_id.view_id:
  348. self.action_id.view_id.sudo().unlink()
  349. self.action_id.sudo().unlink()
  350. self.env['ir.ui.view'].sudo().search(
  351. [('model', '=', self.model_name)]).unlink()
  352. ir_models = self.env['ir.model'].sudo().search(
  353. [('model', '=', self.model_name)])
  354. for model in ir_models:
  355. model.sudo().unlink()
  356. table_name = self.model_name.replace('.', '_')
  357. tools.drop_view_if_exists(self.env.cr, table_name)
  358. self.state = 'draft'
  359. if has_menus:
  360. return {'type': 'ir.actions.client', 'tag': 'reload'}
  361. @api.multi
  362. def unlink(self):
  363. for view in self:
  364. if view.state == 'created':
  365. raise UserError(
  366. _('You cannot delete a created view! '
  367. 'Reset the view to draft first.'))
  368. return super(BveView, self).unlink()