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.

218 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_model': self._name,
  88. 'active_id': self.ids[0],
  89. 'active_ids': self.ids
  90. }
  91. })
  92. return action
  93. @api.model
  94. def _get_popup_action(self):
  95. action = self.env.ref('base_exception.action_exception_rule_confirm')
  96. return action
  97. @api.multi
  98. def _check_exception(self):
  99. """
  100. This method must be used in a constraint that must be created in the
  101. object that inherits for base.exception.
  102. for sale :
  103. @api.constrains('ignore_exception',)
  104. def sale_check_exception(self):
  105. ...
  106. ...
  107. self._check_exception
  108. """
  109. exception_ids = self.detect_exceptions()
  110. if exception_ids:
  111. exceptions = self.env['exception.rule'].browse(exception_ids)
  112. raise ValidationError('\n'.join(exceptions.mapped('name')))
  113. @api.multi
  114. def test_exceptions(self):
  115. """
  116. Condition method for the workflow from draft to confirm
  117. """
  118. if self.detect_exceptions():
  119. return False
  120. return True
  121. @api.multi
  122. def detect_exceptions(self):
  123. """returns the list of exception_ids for all the considered base.exceptions
  124. """
  125. if not self:
  126. return []
  127. exception_obj = self.env['exception.rule']
  128. all_exceptions = exception_obj.sudo().search(
  129. [('rule_group', '=', self[0].rule_group)])
  130. model_exceptions = all_exceptions.filtered(
  131. lambda ex: ex.model == self._name)
  132. sub_exceptions = all_exceptions.filtered(
  133. lambda ex: ex.model != self._name)
  134. all_exception_ids = []
  135. for obj in self:
  136. if obj.ignore_exception:
  137. continue
  138. exception_ids = obj._detect_exceptions(
  139. model_exceptions, sub_exceptions)
  140. obj.exception_ids = [(6, 0, exception_ids)]
  141. all_exception_ids += exception_ids
  142. return all_exception_ids
  143. @api.model
  144. def _exception_rule_eval_context(self, obj_name, rec):
  145. user = self.env['res.users'].browse(self._uid)
  146. return {obj_name: rec,
  147. 'self': self.pool.get(rec._name),
  148. 'object': rec,
  149. 'obj': rec,
  150. 'pool': self.pool,
  151. 'cr': self._cr,
  152. 'uid': self._uid,
  153. 'user': user,
  154. 'time': time,
  155. # copy context to prevent side-effects of eval
  156. 'context': self._context.copy()}
  157. @api.model
  158. def _rule_eval(self, rule, obj_name, rec):
  159. expr = rule.code
  160. space = self._exception_rule_eval_context(obj_name, rec)
  161. try:
  162. safe_eval(expr,
  163. space,
  164. mode='exec',
  165. nocopy=True) # nocopy allows to return 'result'
  166. except Exception, e:
  167. raise UserError(
  168. _('Error when evaluating the exception.rule '
  169. 'rule:\n %s \n(%s)') % (rule.name, e))
  170. return space.get('failed', False)
  171. @api.multi
  172. def _detect_exceptions(self, model_exceptions,
  173. sub_exceptions):
  174. self.ensure_one()
  175. exception_ids = []
  176. for rule in model_exceptions:
  177. if self._rule_eval(rule, self.rule_group, self):
  178. exception_ids.append(rule.id)
  179. if sub_exceptions:
  180. for obj_line in self._get_lines():
  181. for rule in sub_exceptions:
  182. if rule.id in exception_ids:
  183. # we do not matter if the exception as already been
  184. # found for an line of this object
  185. # (ex sale order line if obj is sale order)
  186. continue
  187. group_line = self.rule_group + '_line'
  188. if self._rule_eval(rule, group_line, obj_line):
  189. exception_ids.append(rule.id)
  190. return exception_ids
  191. @implemented_by_base_exception
  192. def _get_lines(self):
  193. pass
  194. def _default_get_lines(self):
  195. return []