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.

236 lines
8.3 KiB

7 years ago
7 years ago
  1. # Copyright 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
  2. # Copyright 2017 Akretion (http://www.akretion.com)
  3. # Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
  4. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  5. import time
  6. from odoo import api, fields, models, _
  7. from odoo.exceptions import UserError, ValidationError
  8. from odoo.tools.safe_eval import safe_eval
  9. from odoo import osv
  10. class ExceptionRule(models.Model):
  11. _name = 'exception.rule'
  12. _description = 'Exception Rule'
  13. _order = 'active desc, sequence asc'
  14. name = fields.Char('Exception Name', required=True, translate=True)
  15. description = fields.Text('Description', translate=True)
  16. sequence = fields.Integer(
  17. string='Sequence',
  18. help="Gives the sequence order when applying the test",
  19. )
  20. model = fields.Selection(selection=[], string='Apply on', required=True)
  21. exception_type = fields.Selection(
  22. selection=[('by_domain', 'By domain'),
  23. ('by_py_code', 'By python code')],
  24. string='Exception Type', required=True, default='by_py_code',
  25. help="By python code: allow to define any arbitrary check\n"
  26. "By domain: limited to a selection by an odoo domain:\n"
  27. " performance can be better when exceptions "
  28. " are evaluated with several records")
  29. domain = fields.Char('Domain')
  30. active = fields.Boolean('Active', default=True)
  31. code = fields.Text(
  32. 'Python Code',
  33. help="Python code executed to check if the exception apply or "
  34. "not. Use failed = True to block the exception",
  35. )
  36. @api.constrains('exception_type', 'domain', 'code')
  37. def check_exception_type_consistency(self):
  38. for rule in self:
  39. if ((rule.exception_type == 'by_py_code' and not rule.code) or
  40. (rule.exception_type == 'by_domain' and not rule.domain)):
  41. raise ValidationError(
  42. _("There is a problem of configuration, python code or "
  43. "domain is missing to match the exception type.")
  44. )
  45. @api.multi
  46. def _get_domain(self):
  47. """ override me to customize domains according exceptions cases """
  48. self.ensure_one()
  49. return safe_eval(self.domain)
  50. class BaseExceptionMethod(models.AbstractModel):
  51. _name = 'base.exception.method'
  52. _description = 'Exception Rule Methods'
  53. @api.multi
  54. def _get_main_records(self):
  55. """
  56. Used in case we check exceptions on a record but write these
  57. exceptions on a parent record. Typical example is with
  58. sale.order.line. We check exceptions on some sale order lines but
  59. write these exceptions on the sale order, so they are visible.
  60. """
  61. return self
  62. @api.multi
  63. def _reverse_field(self):
  64. raise NotImplementedError()
  65. def _rule_domain(self):
  66. """Filter exception.rules.
  67. By default, only the rules with the correct model
  68. will be used.
  69. """
  70. return [('model', '=', self._name)]
  71. @api.multi
  72. def detect_exceptions(self):
  73. """List all exception_ids applied on self
  74. Exception ids are also written on records
  75. If self is empty, check exceptions on all active records.
  76. """
  77. rules = self.env['exception.rule'].sudo().search(
  78. self._rule_domain())
  79. all_exception_ids = []
  80. for rule in rules:
  81. records_with_exception = self._detect_exceptions(rule)
  82. reverse_field = self._reverse_field()
  83. if self:
  84. main_records = self._get_main_records()
  85. commons = main_records & rule[reverse_field]
  86. to_remove = commons - records_with_exception
  87. to_add = records_with_exception - commons
  88. to_remove_list = [(3, x.id, _) for x in to_remove]
  89. to_add_list = [(4, x.id, _) for x in to_add]
  90. rule.write({reverse_field: to_remove_list + to_add_list})
  91. else:
  92. rule.write({
  93. reverse_field: [(6, 0, records_with_exception.ids)]
  94. })
  95. if records_with_exception:
  96. all_exception_ids.append(rule.id)
  97. return all_exception_ids
  98. @api.model
  99. def _exception_rule_eval_context(self, rec):
  100. return {
  101. 'time': time,
  102. 'self': rec,
  103. # object, obj: deprecated.
  104. # should be removed in future migrations
  105. 'object': rec,
  106. 'obj': rec,
  107. # copy context to prevent side-effects of eval
  108. # should be deprecated too, accesible through self.
  109. 'context': self.env.context.copy()
  110. }
  111. @api.model
  112. def _rule_eval(self, rule, rec):
  113. expr = rule.code
  114. space = self._exception_rule_eval_context(rec)
  115. try:
  116. safe_eval(expr,
  117. space,
  118. mode='exec',
  119. nocopy=True) # nocopy allows to return 'result'
  120. except Exception as e:
  121. raise UserError(
  122. _('Error when evaluating the exception.rule '
  123. 'rule:\n %s \n(%s)') % (rule.name, e))
  124. return space.get('failed', False)
  125. @api.multi
  126. def _detect_exceptions(self, rule):
  127. if rule.exception_type == 'by_py_code':
  128. return self._detect_exceptions_by_py_code(rule)
  129. elif rule.exception_type == 'by_domain':
  130. return self._detect_exceptions_by_domain(rule)
  131. @api.multi
  132. def _get_base_domain(self):
  133. domain = [('ignore_exception', '=', False)]
  134. if self:
  135. domain = osv.expression.AND([domain, [('id', 'in', self.ids)]])
  136. return domain
  137. @api.multi
  138. def _detect_exceptions_by_py_code(self, rule):
  139. """
  140. Find exceptions found on self.
  141. If self is empty, check on all records.
  142. """
  143. domain = self._get_base_domain()
  144. records = self.search(domain)
  145. records_with_exception = self.env[self._name]
  146. for record in records:
  147. if self._rule_eval(rule, record):
  148. records_with_exception |= record
  149. return records_with_exception
  150. @api.multi
  151. def _detect_exceptions_by_domain(self, rule):
  152. """
  153. Find exceptions found on self.
  154. If self is empty, check on all records.
  155. """
  156. base_domain = self._get_base_domain()
  157. rule_domain = rule._get_domain()
  158. domain = osv.expression.AND([base_domain, rule_domain])
  159. return self.search(domain)
  160. class BaseException(models.AbstractModel):
  161. _inherit = 'base.exception.method'
  162. _name = 'base.exception'
  163. _order = 'main_exception_id asc'
  164. _description = 'Exception'
  165. main_exception_id = fields.Many2one(
  166. 'exception.rule',
  167. compute='_compute_main_error',
  168. string='Main Exception',
  169. store=True,
  170. )
  171. exception_ids = fields.Many2many('exception.rule', string='Exceptions')
  172. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  173. @api.depends('exception_ids', 'ignore_exception')
  174. def _compute_main_error(self):
  175. for rec in self:
  176. if not rec.ignore_exception and rec.exception_ids:
  177. rec.main_exception_id = rec.exception_ids[0]
  178. else:
  179. rec.main_exception_id = False
  180. @api.multi
  181. def _popup_exceptions(self):
  182. action = self._get_popup_action().read()[0]
  183. action.update({
  184. 'context': {
  185. 'active_id': self.ids[0],
  186. 'active_ids': self.ids,
  187. 'active_model': self._name,
  188. }
  189. })
  190. return action
  191. @api.model
  192. def _get_popup_action(self):
  193. return self.env.ref('base_exception.action_exception_rule_confirm')
  194. @api.multi
  195. def _check_exception(self):
  196. """
  197. This method must be used in a constraint that must be created in the
  198. object that inherits for base.exception.
  199. for sale :
  200. @api.constrains('ignore_exception',)
  201. def sale_check_exception(self):
  202. ...
  203. ...
  204. self._check_exception
  205. """
  206. exception_ids = self.detect_exceptions()
  207. if exception_ids:
  208. exceptions = self.env['exception.rule'].browse(exception_ids)
  209. raise ValidationError('\n'.join(exceptions.mapped('name')))