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.

419 lines
14 KiB

  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 Warning as 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: Te 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. @api.model
  58. def _get_format_data(self, 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, type=''):
  66. if not type:
  67. return ''
  68. return """<field name="x_{}" type="{}" />""".format(
  69. name, 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. self.env.cr.execute('''SELECT
  181. g.id
  182. FROM
  183. ir_model_access a
  184. JOIN ir_model m ON (a.model_id=m.id)
  185. JOIN res_groups g ON (a.group_id=g.id)
  186. LEFT JOIN ir_module_category c ON (c.id=g.category_id)
  187. WHERE
  188. m.model=%s AND
  189. a.active IS True AND
  190. a.perm_''' + access_mode, (model_name,))
  191. return [x[0] for x in self.env.cr.fetchall()]
  192. info = json.loads(self._get_format_data(self.data))
  193. models = list(set([f['model'] for f in info]))
  194. read_groups = set.intersection(*[set(
  195. group_ids_with_access(model_name, 'read')
  196. ) for model_name in models])
  197. # read access
  198. for group in read_groups:
  199. self.env['ir.model.access'].sudo().create({
  200. 'name': 'read access to ' + self.model_name,
  201. 'model_id': model.id,
  202. 'group_id': group,
  203. 'perm_read': True,
  204. })
  205. # read and write access
  206. for group in self.group_ids:
  207. self.env['ir.model.access'].sudo().create({
  208. 'name': 'read-write access to ' + self.model_name,
  209. 'model_id': model.id,
  210. 'group_id': group.id,
  211. 'perm_read': True,
  212. 'perm_write': True,
  213. })
  214. @api.model
  215. def _create_sql_view(self):
  216. def get_fields_info(fields_data):
  217. fields_info = []
  218. for field_data in fields_data:
  219. field = self.env['ir.model.fields'].browse(field_data['id'])
  220. vals = {
  221. 'table': self.env[field.model_id.model]._table,
  222. 'table_alias': field_data['table_alias'],
  223. 'select_field': field.name,
  224. 'as_field': 'x_' + field_data['name'],
  225. 'join': False,
  226. 'model': field.model_id.model
  227. }
  228. if field_data.get('join_node'):
  229. vals.update({'join': field_data['join_node']})
  230. fields_info.append(vals)
  231. return fields_info
  232. def get_join_nodes(info):
  233. join_nodes = [
  234. (f['table_alias'],
  235. f['join'],
  236. f['select_field']) for f in info if f['join'] is not False]
  237. return join_nodes
  238. def get_tables(info):
  239. tables = set([(f['table'], f['table_alias']) for f in info])
  240. return tables
  241. def get_fields(info):
  242. fields = [("{}.{}".format(f['table_alias'],
  243. f['select_field']),
  244. f['as_field']) for f in info if 'join_node' not in f]
  245. return fields
  246. def check_empty_data(data):
  247. if not 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. fields = get_fields(info)
  253. tables = get_tables(info)
  254. join_nodes = get_join_nodes(info)
  255. table_name = self.model_name.replace('.', '_')
  256. tools.drop_view_if_exists(self.env.cr, table_name)
  257. # this line is only for robustness in case something goes wrong
  258. self._cr.execute('DROP TABLE IF EXISTS "%s"' % table_name)
  259. basic_fields = [
  260. ("t0.id", "id")
  261. ]
  262. q = """CREATE or REPLACE VIEW %s as (
  263. SELECT %s
  264. FROM %s
  265. WHERE %s
  266. )""" % (table_name, ','.join(
  267. ["{} AS {}".format(f[0], f[1])
  268. for f in basic_fields + fields]), ','.join(
  269. ["{} AS {}".format(t[0], t[1])
  270. for t in list(tables)]), " AND ".join(
  271. ["{}.{} = {}.id".format(j[0], j[2], j[1])
  272. for j in join_nodes] + ["TRUE"]))
  273. self.env.cr.execute(q)
  274. @api.multi
  275. def action_create(self):
  276. self.ensure_one()
  277. def _prepare_field(field_data):
  278. if not field_data['custom']:
  279. field = self.env['ir.model.fields'].browse(field_data['id'])
  280. vals = {
  281. 'name': 'x_' + field_data['name'],
  282. 'complete_name': field.complete_name,
  283. 'model': self.model_name,
  284. 'relation': field.relation,
  285. 'field_description': field_data.get(
  286. 'description', field.field_description),
  287. 'ttype': field.ttype,
  288. 'selection': field.selection,
  289. 'size': field.size,
  290. 'state': 'manual'
  291. }
  292. if vals['ttype'] == 'monetary':
  293. vals.update({'ttype': 'float'})
  294. if field.ttype == 'selection' and not field.selection:
  295. model_obj = self.env[field.model_id.model]
  296. selection = model_obj._fields[field.name].selection
  297. selection_domain = str(selection)
  298. vals.update({'selection': selection_domain})
  299. return vals
  300. # create sql view
  301. self._create_sql_view()
  302. # create model and fields
  303. data = json.loads(self._get_format_data(self.data))
  304. model_vals = {
  305. 'name': self.name,
  306. 'model': self.model_name,
  307. 'state': 'manual',
  308. 'field_id': [
  309. (0, 0, _prepare_field(field))
  310. for field in data
  311. if 'join_node' not in field]
  312. }
  313. model = self.env['ir.model'].sudo().create(model_vals)
  314. # give access rights
  315. self._build_access_rules(model)
  316. # create tree, graph and pivot views
  317. self._create_bve_view()
  318. @api.multi
  319. def open_view(self):
  320. self.ensure_one()
  321. [action] = self.action_id.read()
  322. action['display_name'] = _('BI View')
  323. return action
  324. @api.multi
  325. def copy(self, default=None):
  326. self.ensure_one()
  327. default = dict(default or {}, name=_("%s (copy)") % self.name)
  328. return super(BveView, self).copy(default=default)
  329. @api.multi
  330. def action_reset(self):
  331. self.ensure_one()
  332. has_menus = False
  333. if self.action_id:
  334. action = 'ir.actions.act_window,%d' % (self.action_id.id,)
  335. menus = self.env['ir.ui.menu'].sudo().search(
  336. [('action', '=', action)]
  337. )
  338. has_menus = True if menus else False
  339. menus.sudo().unlink()
  340. if self.action_id.view_id:
  341. self.action_id.view_id.sudo().unlink()
  342. self.action_id.sudo().unlink()
  343. models = self.env['ir.model'].sudo().search(
  344. [('model', '=', self.model_name)])
  345. for model in models:
  346. model.sudo().unlink()
  347. table_name = self.model_name.replace('.', '_')
  348. tools.drop_view_if_exists(self.env.cr, table_name)
  349. self.state = 'draft'
  350. if has_menus:
  351. return {'type': 'ir.actions.client', 'tag': 'reload'}
  352. @api.multi
  353. def unlink(self):
  354. for view in self:
  355. if view.state == 'created':
  356. raise UserError(
  357. _('You cannot delete a created view! '
  358. 'Reset the view to draft first.'))
  359. return super(BveView, self).unlink()