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.

389 lines
13 KiB

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