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.

217 lines
7.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import time
  5. from functools import wraps
  6. from odoo import api, models, fields, _
  7. from odoo.exceptions import UserError, ValidationError
  8. from odoo.tools.safe_eval import safe_eval
  9. def implemented_by_base_exception(func):
  10. """Call a prefixed function based on 'namespace'."""
  11. @wraps(func)
  12. def wrapper(cls, *args, **kwargs):
  13. fun_name = func.__name__
  14. fun = '_%s%s' % (cls.rule_group, fun_name)
  15. if not hasattr(cls, fun):
  16. fun = '_default%s' % (fun_name)
  17. return getattr(cls, fun)(*args, **kwargs)
  18. return wrapper
  19. class ExceptionRule(models.Model):
  20. _name = 'exception.rule'
  21. _description = "Exception Rules"
  22. _order = 'active desc, sequence asc'
  23. name = fields.Char('Exception Name', required=True, translate=True)
  24. description = fields.Text('Description', translate=True)
  25. sequence = fields.Integer(
  26. string='Sequence',
  27. help="Gives the sequence order when applying the test")
  28. rule_group = fields.Selection(
  29. selection=[],
  30. help="Rule group is used to group the rules that must validated "
  31. "at same time for a target object. Ex: "
  32. "validate sale.order.line rules with sale order rules.",
  33. required=True)
  34. model = fields.Selection(
  35. selection=[],
  36. string='Apply on', required=True)
  37. active = fields.Boolean('Active')
  38. code = fields.Text(
  39. 'Python Code',
  40. help="Python code executed to check if the exception apply or "
  41. "not. The code must apply block = True to apply the "
  42. "exception.",
  43. default="""
  44. # Python code. Use failed = True to block the base.exception.
  45. # You can use the following variables :
  46. # - self: ORM model of the record which is checked
  47. # - "rule_group" or "rule_group_"line:
  48. # browse_record of the base.exception or
  49. # base.exception line (ex rule_group = sale for sale order)
  50. # - object: same as order or line, browse_record of the base.exception or
  51. # base.exception line
  52. # - pool: ORM model pool (i.e. self.pool)
  53. # - time: Python time module
  54. # - cr: database cursor
  55. # - uid: current user id
  56. # - context: current context
  57. """)
  58. class BaseException(models.AbstractModel):
  59. _name = 'base.exception'
  60. _order = 'main_exception_id asc'
  61. main_exception_id = fields.Many2one(
  62. 'exception.rule',
  63. compute='_compute_main_error',
  64. string='Main Exception',
  65. store=True)
  66. rule_group = fields.Selection(
  67. [],
  68. readonly=True,
  69. )
  70. exception_ids = fields.Many2many(
  71. 'exception.rule',
  72. string='Exceptions')
  73. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  74. @api.depends('exception_ids', 'ignore_exception')
  75. def _compute_main_error(self):
  76. for obj in self:
  77. if not obj.ignore_exception and obj.exception_ids:
  78. obj.main_exception_id = obj.exception_ids[0]
  79. else:
  80. obj.main_exception_id = False
  81. @api.multi
  82. def _popup_exceptions(self):
  83. action = self._get_popup_action()
  84. action = action.read()[0]
  85. action.update({
  86. 'context': {
  87. 'active_id': self.ids[0],
  88. 'active_ids': self.ids
  89. }
  90. })
  91. return action
  92. @api.model
  93. def _get_popup_action(self):
  94. action = self.env.ref('base_exception.action_exception_rule_confirm')
  95. return action
  96. @api.multi
  97. def _check_exception(self):
  98. """
  99. This method must be used in a constraint that must be created in the
  100. object that inherits for base.exception.
  101. for sale :
  102. @api.constrains('ignore_exception',)
  103. def sale_check_exception(self):
  104. ...
  105. ...
  106. self._check_exception
  107. """
  108. exception_ids = self.detect_exceptions()
  109. if exception_ids:
  110. exceptions = self.env['exception.rule'].browse(exception_ids)
  111. raise ValidationError('\n'.join(exceptions.mapped('name')))
  112. @api.multi
  113. def test_exceptions(self):
  114. """
  115. Condition method for the workflow from draft to confirm
  116. """
  117. if self.detect_exceptions():
  118. return False
  119. return True
  120. @api.multi
  121. def detect_exceptions(self):
  122. """returns the list of exception_ids for all the considered base.exceptions
  123. """
  124. if not self:
  125. return []
  126. exception_obj = self.env['exception.rule']
  127. all_exceptions = exception_obj.sudo().search(
  128. [('rule_group', '=', self[0].rule_group)])
  129. model_exceptions = all_exceptions.filtered(
  130. lambda ex: ex.model == self._name)
  131. sub_exceptions = all_exceptions.filtered(
  132. lambda ex: ex.model != self._name)
  133. all_exception_ids = []
  134. for obj in self:
  135. if obj.ignore_exception:
  136. continue
  137. exception_ids = obj._detect_exceptions(
  138. model_exceptions, sub_exceptions)
  139. obj.exception_ids = [(6, 0, exception_ids)]
  140. all_exception_ids += exception_ids
  141. return all_exception_ids
  142. @api.model
  143. def _exception_rule_eval_context(self, obj_name, rec):
  144. user = self.env['res.users'].browse(self._uid)
  145. return {obj_name: rec,
  146. 'self': self.pool.get(rec._name),
  147. 'object': rec,
  148. 'obj': rec,
  149. 'pool': self.pool,
  150. 'cr': self._cr,
  151. 'uid': self._uid,
  152. 'user': user,
  153. 'time': time,
  154. # copy context to prevent side-effects of eval
  155. 'context': self._context.copy()}
  156. @api.model
  157. def _rule_eval(self, rule, obj_name, rec):
  158. expr = rule.code
  159. space = self._exception_rule_eval_context(obj_name, rec)
  160. try:
  161. safe_eval(expr,
  162. space,
  163. mode='exec',
  164. nocopy=True) # nocopy allows to return 'result'
  165. except Exception, e:
  166. raise UserError(
  167. _('Error when evaluating the exception.rule '
  168. 'rule:\n %s \n(%s)') % (rule.name, e))
  169. return space.get('failed', False)
  170. @api.multi
  171. def _detect_exceptions(self, model_exceptions,
  172. sub_exceptions):
  173. self.ensure_one()
  174. exception_ids = []
  175. for rule in model_exceptions:
  176. if self._rule_eval(rule, self.rule_group, self):
  177. exception_ids.append(rule.id)
  178. if sub_exceptions:
  179. for obj_line in self._get_lines():
  180. for rule in sub_exceptions:
  181. if rule.id in exception_ids:
  182. # we do not matter if the exception as already been
  183. # found for an line of this object
  184. # (ex sale order line if obj is sale order)
  185. continue
  186. group_line = self.rule_group + '_line'
  187. if self._rule_eval(rule, group_line, obj_line):
  188. exception_ids.append(rule.id)
  189. return exception_ids
  190. @implemented_by_base_exception
  191. def _get_lines(self):
  192. pass
  193. def _default_get_lines(self):
  194. return []