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.

182 lines
8.6 KiB

  1. ###################################################################################
  2. #
  3. # Copyright (C) 2018 MuK IT GmbH
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. ###################################################################################
  19. import logging
  20. from odoo import api, models, fields
  21. from odoo.osv import expression
  22. from odoo.addons.muk_utils.tools import utils
  23. _logger = logging.getLogger(__name__)
  24. class Base(models.AbstractModel):
  25. _inherit = 'base'
  26. #----------------------------------------------------------
  27. # Helper Methods
  28. #----------------------------------------------------------
  29. @api.model
  30. def _check_parent_field(self):
  31. if self._parent_name not in self._fields:
  32. raise TypeError("The parent (%s) field does not exist." % self._parent_name)
  33. @api.model
  34. def _build_search_childs_domain(self, parent_id, domain=[]):
  35. self._check_parent_field()
  36. parent_domain = [[self._parent_name, '=', parent_id]]
  37. return expression.AND([parent_domain, domain]) if domain else parent_domain
  38. @api.model
  39. def _check_context_bin_size(self, field):
  40. return any(key in self.env.context for key in ['bin_size', 'bin_size_%s' % (field)])
  41. #----------------------------------------------------------
  42. # Security
  43. #----------------------------------------------------------
  44. @api.multi
  45. def _filter_access(self, operation):
  46. if self.check_access_rights(operation, False):
  47. return self._filter_access_rules(operation)
  48. return self.env[self._name]
  49. @api.multi
  50. def _filter_access_ids(self, operation):
  51. return self._filter_access(operation).ids
  52. @api.multi
  53. def check_access(self, operation, raise_exception=False):
  54. try:
  55. access_right = self.check_access_rights(operation, raise_exception)
  56. access_rule = self.check_access_rule(operation) is None
  57. return access_right and access_rule
  58. except AccessError:
  59. if raise_exception:
  60. raise
  61. return False
  62. #----------------------------------------------------------
  63. # Hierarchy Methods
  64. #----------------------------------------------------------
  65. @api.model
  66. def search_parents(self, domain=[], offset=0, limit=None, order=None, count=False):
  67. """ This method finds the top level elements of the hierarchy for a given search query.
  68. :param domain: a search domain <reference/orm/domains> (default: empty list)
  69. :param order: a string to define the sort order of the query (default: none)
  70. :returns: the top level elements for the given search query
  71. """
  72. res = self._search_parents(domain=domain, offset=offset, limit=limit, order=order, count=count)
  73. return res if count else self.browse(res)
  74. @api.model
  75. def search_read_parents(self, domain=[], fields=None, offset=0, limit=None, order=None):
  76. """ This method finds the top level elements of the hierarchy for a given search query.
  77. :param domain: a search domain <reference/orm/domains> (default: empty list)
  78. :param fields: a list of fields to read (default: all fields of the model)
  79. :param order: a string to define the sort order of the query (default: none)
  80. :returns: the top level elements for the given search query
  81. """
  82. records = self.search_parents(domain=domain, offset=offset, limit=limit, order=order)
  83. if not records:
  84. return []
  85. if fields and fields == ['id']:
  86. return [{'id': record.id} for record in records]
  87. result = records.read(fields)
  88. if len(result) <= 1:
  89. return result
  90. index = {vals['id']: vals for vals in result}
  91. return [index[record.id] for record in records if record.id in index]
  92. @api.model
  93. def _search_parents(self, domain=[], offset=0, limit=None, order=None, count=False):
  94. self._check_parent_field()
  95. self.check_access_rights('read')
  96. if expression.is_false(self, domain):
  97. return []
  98. query = self._where_calc(domain)
  99. self._apply_ir_rules(query, 'read')
  100. from_clause, where_clause, where_clause_arguments = query.get_sql()
  101. parent_where = where_clause and (" WHERE %s" % where_clause) or ''
  102. parent_query = 'SELECT "%s".id FROM ' % self._table + from_clause + parent_where
  103. no_parent_clause ='"{table}"."{field}" IS NULL'.format(
  104. table=self._table,
  105. field=self._parent_name
  106. )
  107. no_access_clause ='"{table}"."{field}" NOT IN ({query})'.format(
  108. table=self._table,
  109. field=self._parent_name,
  110. query=parent_query
  111. )
  112. parent_clause = '({0} OR {1})'.format(
  113. no_parent_clause,
  114. no_access_clause
  115. )
  116. order_by = self._generate_order_by(order, query)
  117. from_clause, where_clause, where_clause_params = query.get_sql()
  118. where_str = (
  119. where_clause and
  120. (" WHERE %s AND %s" % (where_clause, parent_clause)) or
  121. (" WHERE %s" % parent_clause)
  122. )
  123. if count:
  124. query_str = 'SELECT count(1) FROM ' + from_clause + where_str
  125. self._cr.execute(query_str, where_clause_params)
  126. return self._cr.fetchone()[0]
  127. limit_str = limit and ' limit %d' % limit or ''
  128. offset_str = offset and ' offset %d' % offset or ''
  129. query_str = 'SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str
  130. complete_where_clause_params = where_clause_params + where_clause_arguments
  131. self._cr.execute(query_str, complete_where_clause_params)
  132. return utils.uniquify_list([x[0] for x in self._cr.fetchall()])
  133. @api.model
  134. def search_childs(self, parent_id, domain=[], offset=0, limit=None, order=None, count=False):
  135. """ This method finds the direct child elements of the parent record for a given search query.
  136. :param parent_id: the integer representing the ID of the parent record
  137. :param domain: a search domain <reference/orm/domains> (default: empty list)
  138. :param offset: the number of results to ignore (default: none)
  139. :param limit: maximum number of records to return (default: all)
  140. :param order: a string to define the sort order of the query (default: none)
  141. :param count: counts and returns the number of matching records (default: False)
  142. :returns: the top level elements for the given search query
  143. """
  144. domain = self._build_search_childs_domain(parent_id, domain=domain)
  145. return self.search(domain, offset=offset, limit=limit, order=order, count=count)
  146. @api.model
  147. def search_read_childs(self, parent_id, domain=[], fields=None, offset=0, limit=None, order=None):
  148. """ This method finds the direct child elements of the parent record for a given search query.
  149. :param parent_id: the integer representing the ID of the parent record
  150. :param domain: a search domain <reference/orm/domains> (default: empty list)
  151. :param fields: a list of fields to read (default: all fields of the model)
  152. :param offset: the number of results to ignore (default: none)
  153. :param limit: maximum number of records to return (default: all)
  154. :param order: a string to define the sort order of the query (default: none)
  155. :returns: the top level elements for the given search query
  156. """
  157. domain = self._build_search_childs_domain(parent_id, domain=domain)
  158. return self.search_read(domain=domain, fields=fields, offset=offset, limit=limit, order=order)