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.

308 lines
11 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2015-2016 ONESTEiN BV (<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 tools
  6. from openerp import SUPERUSER_ID
  7. from openerp import models, fields, api
  8. from openerp.exceptions import Warning as UserError
  9. from openerp.modules.registry import RegistryManager
  10. from openerp.tools.translate import _
  11. class BveView(models.Model):
  12. _name = 'bve.view'
  13. _description = "BI View Editor"
  14. @api.depends('group_ids')
  15. @api.multi
  16. def _compute_users(self):
  17. for bve_view in self:
  18. if bve_view.sudo().group_ids:
  19. bve_view.user_ids = self.env['res.users'].sudo().browse(
  20. list(set([u.id for group in bve_view.sudo().group_ids
  21. for u in group.users])))
  22. else:
  23. bve_view.user_ids = self.env['res.users'].sudo().search([])
  24. name = fields.Char(size=128, string="Name", required=True)
  25. model_name = fields.Char(size=128, string="Model Name")
  26. note = fields.Text(string="Notes")
  27. state = fields.Selection(
  28. [('draft', 'Draft'),
  29. ('created', 'Created')],
  30. string="State",
  31. default="draft")
  32. data = fields.Text(
  33. string="Data",
  34. help="Use the special query builder to define the query "
  35. "to generate your report dataset. "
  36. "NOTE: Te be edited, the query should be in 'Draft' status.")
  37. action_id = fields.Many2one('ir.actions.act_window', string="Action")
  38. view_id = fields.Many2one('ir.ui.view', string="View")
  39. group_ids = fields.Many2many(
  40. 'res.groups',
  41. string="Groups",
  42. help="User groups allowed to see the generated report; "
  43. "if NO groups are specified the report will be public "
  44. "for everyone.")
  45. user_ids = fields.Many2many(
  46. 'res.users',
  47. string="Users",
  48. compute=_compute_users,
  49. store=True)
  50. _sql_constraints = [
  51. ('name_uniq',
  52. 'unique(name)',
  53. 'Custom BI View names must be unique!'),
  54. ]
  55. @api.multi
  56. def unlink(self):
  57. for view in self:
  58. if view.state == 'created':
  59. raise UserError(
  60. _('You cannot delete a created view! '
  61. 'Reset the view to draft first.'))
  62. super(BveView, self).unlink()
  63. @api.multi
  64. def action_edit_query(self):
  65. return {
  66. 'type': 'ir.actions.client',
  67. 'tag': 'bi_view_editor.open',
  68. 'target': 'new',
  69. 'params': {'bve_view_id': self.id}
  70. }
  71. @api.multi
  72. def action_reset(self):
  73. if self.action_id:
  74. if self.action_id.view_id:
  75. self.action_id.view_id.sudo().unlink()
  76. self.action_id.sudo().unlink()
  77. models = self.env['ir.model'].sudo().search(
  78. [('model', '=', self.model_name)])
  79. for model in models:
  80. model.sudo().unlink()
  81. table_name = self.model_name.replace(".", "_")
  82. tools.drop_view_if_exists(self.env.cr, table_name)
  83. self.write({
  84. 'state': 'draft'
  85. })
  86. return True
  87. def _create_graph_view(self):
  88. fields_info = json.loads(self.data)
  89. return ["""<field name="x_{}" type="{}" />""".format(
  90. field_info['name'],
  91. (field_info['row'] and 'row') or
  92. (field_info['column'] and 'col') or
  93. (field_info['measure'] and 'measure'))
  94. for field_info in fields_info if field_info['row'] or
  95. field_info['column'] or field_info['measure']]
  96. @api.multi
  97. def action_create(self):
  98. def _get_fields_info(fields_data):
  99. fields_info = []
  100. for field_data in fields_data:
  101. field = self.env['ir.model.fields'].browse(field_data["id"])
  102. vals = {
  103. "table": self.env[field.model_id.model]._table,
  104. "table_alias": field_data["table_alias"],
  105. "select_field": field.name,
  106. "as_field": "x_" + field_data["name"],
  107. "join": False,
  108. "model": field.model_id.model
  109. }
  110. if field_data.get("join_node"):
  111. vals.update({"join": field_data["join_node"]})
  112. fields_info.append(vals)
  113. return fields_info
  114. def _build_query():
  115. data = self.data
  116. if not data:
  117. raise UserError(_('No data to process.'))
  118. info = _get_fields_info(json.loads(data))
  119. fields = [("{}.{}".format(f["table_alias"],
  120. f["select_field"]),
  121. f["as_field"]) for f in info if 'join_node' not in f]
  122. tables = set([(f["table"], f["table_alias"]) for f in info])
  123. join_nodes = [
  124. (f["table_alias"],
  125. f["join"],
  126. f["select_field"]) for f in info if f["join"] is not False]
  127. table_name = self.model_name.replace(".", "_")
  128. tools.drop_view_if_exists(self.env.cr, table_name)
  129. basic_fields = [
  130. ("t0.id", "id"),
  131. ("t0.write_uid", "write_uid"),
  132. ("t0.write_date", "write_date"),
  133. ("t0.create_uid", "create_uid"),
  134. ("t0.create_date", "create_date")
  135. ]
  136. q = """CREATE or REPLACE VIEW %s as (
  137. SELECT %s
  138. FROM %s
  139. WHERE %s
  140. )""" % (table_name, ','.join(
  141. ["{} AS {}".format(f[0], f[1])
  142. for f in basic_fields + fields]), ','.join(
  143. ["{} AS {}".format(t[0], t[1])
  144. for t in list(tables)]), " AND ".join(
  145. ["{}.{} = {}.id".format(j[0], j[2], j[1])
  146. for j in join_nodes] + ["TRUE"]))
  147. self.env.cr.execute(q)
  148. def _prepare_field(field_data):
  149. if not field_data["custom"]:
  150. field = self.env['ir.model.fields'].browse(field_data["id"])
  151. vals = {
  152. "name": "x_" + field_data["name"],
  153. "complete_name": field.complete_name,
  154. 'model': self.model_name,
  155. 'relation': field.relation,
  156. "field_description": field_data.get(
  157. "description", field.field_description),
  158. "ttype": field.ttype,
  159. "selection": field.selection,
  160. "size": field.size,
  161. 'state': "manual"
  162. }
  163. if vals['ttype'] == 'monetary':
  164. vals.update({'ttype': 'float'})
  165. if field.ttype == 'selection' and not field.selection:
  166. model_obj = self.env[field.model_id.model]
  167. selection = model_obj._columns[field.name].selection
  168. selection_domain = str(selection)
  169. vals.update({"selection": selection_domain})
  170. return vals
  171. def _prepare_object():
  172. return {
  173. 'name': self.name,
  174. 'model': self.model_name,
  175. 'field_id': [
  176. (0, 0, _prepare_field(field))
  177. for field in json.loads(self.data)
  178. if 'join_node' not in field]
  179. }
  180. def _build_object():
  181. res_id = self.env['ir.model'].sudo().create(_prepare_object())
  182. return res_id
  183. # read access
  184. def group_ids_with_access(model_name, access_mode):
  185. self.env.cr.execute('''SELECT
  186. g.id
  187. FROM
  188. ir_model_access a
  189. JOIN ir_model m ON (a.model_id=m.id)
  190. JOIN res_groups g ON (a.group_id=g.id)
  191. LEFT JOIN ir_module_category c ON (c.id=g.category_id)
  192. WHERE
  193. m.model=%s AND
  194. a.active IS True AND
  195. a.perm_''' + access_mode, (model_name,))
  196. return [x[0] for x in self.env.cr.fetchall()]
  197. def _build_access_rules(obj):
  198. info = json.loads(self.data)
  199. models = list(set([f["model"] for f in info]))
  200. read_groups = set.intersection(*[set(
  201. group_ids_with_access(model, 'read')) for model in models])
  202. for group in read_groups:
  203. self.env['ir.model.access'].sudo().create({
  204. 'name': 'read access to ' + self.model_name,
  205. 'model_id': obj.id,
  206. 'group_id': group,
  207. 'perm_read': True,
  208. })
  209. # edit access
  210. for group in self.group_ids:
  211. self.env['ir.model.access'].sudo().create({
  212. 'name': 'read access to ' + self.model_name,
  213. 'model_id': obj.id,
  214. 'group_id': group.id,
  215. 'perm_read': True,
  216. 'perm_write': True,
  217. })
  218. return
  219. self.model_name = "x_bve." + ''.join(
  220. [x for x in self.name.lower()
  221. if x.isalnum()]).replace("_", ".").replace(" ", ".")
  222. _build_query()
  223. obj = _build_object()
  224. _build_access_rules(obj)
  225. self.env.cr.commit()
  226. self.env.registry = RegistryManager.new(self.env.cr.dbname)
  227. RegistryManager.signal_registry_change(self.env.cr.dbname)
  228. self.pool = self.env.registry
  229. view_id = self.pool.get('ir.ui.view').create(
  230. self.env.cr, SUPERUSER_ID,
  231. {'name': "Analysis",
  232. 'type': 'graph',
  233. 'model': self.model_name,
  234. 'priority': 16,
  235. 'arch': """<?xml version="1.0"?>
  236. <graph string="Analysis"
  237. type="pivot"
  238. stacked="True"> {} </graph>
  239. """.format("".join(self._create_graph_view()))
  240. }, context={})
  241. view_ids = [view_id]
  242. action_vals = {'name': self.name,
  243. 'res_model': self.model_name,
  244. 'type': 'ir.actions.act_window',
  245. 'view_type': 'form',
  246. 'view_mode': 'graph',
  247. 'view_id': view_ids and view_ids[0] or 0,
  248. 'context': "{'service_name': '%s'}" % self.name,
  249. }
  250. act_window = self.env['ir.actions.act_window']
  251. action_id = act_window.sudo().create(action_vals)
  252. self.write({
  253. 'action_id': action_id.id,
  254. 'view_id': view_id,
  255. 'state': 'created'
  256. })
  257. return True
  258. @api.multi
  259. def open_view(self):
  260. return {
  261. 'type': 'ir.actions.act_window',
  262. 'res_model': self.model_name,
  263. 'view_type': 'graph',
  264. 'view_mode': 'graph',
  265. }