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.

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