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.

185 lines
8.4 KiB

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