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.

253 lines
8.9 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 functools import wraps
  7. from odoo import api, fields, models, _
  8. import logging
  9. from odoo.exceptions import UserError, ValidationError
  10. from odoo.tools.safe_eval import safe_eval
  11. _logger = logging.getLogger(__name__)
  12. def implemented_by_base_exception(func):
  13. """Call a prefixed function based on 'namespace'."""
  14. @wraps(func)
  15. def wrapper(cls, *args, **kwargs):
  16. fun_name = func.__name__
  17. fun = '_%s%s' % (cls.rule_group, fun_name)
  18. if not hasattr(cls, fun):
  19. fun = '_default%s' % (fun_name)
  20. return getattr(cls, fun)(*args, **kwargs)
  21. return wrapper
  22. class ExceptionRule(models.Model):
  23. _name = 'exception.rule'
  24. _description = "Exception Rules"
  25. _order = 'active desc, sequence asc'
  26. name = fields.Char('Exception Name', required=True, translate=True)
  27. description = fields.Text('Description', translate=True)
  28. sequence = fields.Integer(
  29. string='Sequence',
  30. help="Gives the sequence order when applying the test")
  31. rule_group = fields.Selection(
  32. selection=[],
  33. help="Rule group is used to group the rules that must validated "
  34. "at same time for a target object. Ex: "
  35. "validate sale.order.line rules with sale order rules.",
  36. required=True)
  37. model = fields.Selection(
  38. selection=[],
  39. string='Apply on', required=True)
  40. active = fields.Boolean('Active')
  41. next_state = fields.Char(
  42. 'Next state',
  43. help="If we detect exception we set the state of object (ex purchase) "
  44. "to the next_state (ex 'to approve'). If there are more than one "
  45. "exception detected and all have a value for next_state, we use"
  46. "the exception having the smallest sequence value")
  47. code = fields.Text(
  48. 'Python Code',
  49. help="Python code executed to check if the exception apply or "
  50. "not. Use failed = True to block the exception",
  51. default="""
  52. # Python code. Use failed = True to block the base.exception.
  53. # You can use the following variables :
  54. # - self: ORM model of the record which is checked
  55. # - "rule_group" or "rule_group_"line:
  56. # browse_record of the base.exception or
  57. # base.exception line (ex rule_group = sale for sale order)
  58. # - object: same as order or line, browse_record of the base.exception or
  59. # base.exception line
  60. # - env: Odoo Environment (i.e. self.env)
  61. # - time: Python time module
  62. # - cr: database cursor
  63. # - uid: current user id
  64. # - context: current context
  65. """)
  66. @api.constrains('next_state')
  67. def _check_next_state_value(self):
  68. """ Ensure that the next_state value is in the state values of
  69. destination model """
  70. for rule in self:
  71. if rule.next_state:
  72. select_vals = self.env[
  73. rule.model].fields_get()[
  74. 'state']['selection']
  75. select_vals_code = [s[0] for s in select_vals]
  76. if rule.next_state not in select_vals_code:
  77. raise ValidationError(
  78. _('The value "%s" you choose for the "next state" '
  79. 'field state of "%s" is wrong.'
  80. ' Value must be in this list %s')
  81. % (rule.next_state,
  82. rule.model,
  83. select_vals)
  84. )
  85. class BaseException(models.AbstractModel):
  86. _name = 'base.exception'
  87. _order = 'main_exception_id asc'
  88. main_exception_id = fields.Many2one(
  89. 'exception.rule',
  90. compute='_compute_main_error',
  91. string='Main Exception',
  92. store=True)
  93. rule_group = fields.Selection(
  94. [],
  95. readonly=True,
  96. )
  97. exception_ids = fields.Many2many(
  98. 'exception.rule',
  99. string='Exceptions')
  100. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  101. @api.depends('exception_ids', 'ignore_exception')
  102. def _compute_main_error(self):
  103. for obj in self:
  104. if not obj.ignore_exception and obj.exception_ids:
  105. obj.main_exception_id = obj.exception_ids[0]
  106. else:
  107. obj.main_exception_id = False
  108. @api.multi
  109. def _popup_exceptions(self):
  110. action = self._get_popup_action()
  111. action_data = action.read()[0]
  112. action_data.update({
  113. 'context': {
  114. 'active_id': self.ids[0],
  115. 'active_ids': self.ids
  116. }
  117. })
  118. return action_data
  119. @api.model
  120. def _get_popup_action(self):
  121. action = self.env.ref('base_exception.action_exception_rule_confirm')
  122. return action
  123. @api.multi
  124. def _check_exception(self):
  125. """
  126. This method must be used in a constraint that must be created in the
  127. object that inherits for base.exception.
  128. for sale :
  129. @api.constrains('ignore_exception',)
  130. def sale_check_exception(self):
  131. ...
  132. ...
  133. self._check_exception
  134. """
  135. exception_ids = self.detect_exceptions()
  136. if exception_ids:
  137. exceptions = self.env['exception.rule'].browse(exception_ids)
  138. raise ValidationError('\n'.join(exceptions.mapped('name')))
  139. @api.multi
  140. def test_exceptions(self):
  141. """
  142. Condition method for the workflow from draft to confirm
  143. """
  144. if self.detect_exceptions():
  145. return False
  146. return True
  147. @api.multi
  148. def detect_exceptions(self):
  149. """returns the list of exception_ids for all the considered base.exceptions
  150. """
  151. if not self:
  152. return []
  153. exception_obj = self.env['exception.rule']
  154. all_exceptions = exception_obj.sudo().search(
  155. [('rule_group', '=', self[0].rule_group)])
  156. model_exceptions = all_exceptions.filtered(
  157. lambda ex: ex.model == self._name)
  158. sub_exceptions = all_exceptions.filtered(
  159. lambda ex: ex.model != self._name)
  160. all_exception_ids = []
  161. for obj in self:
  162. if obj.ignore_exception:
  163. continue
  164. exception_ids = obj._detect_exceptions(
  165. model_exceptions, sub_exceptions)
  166. obj.exception_ids = [(6, 0, exception_ids)]
  167. all_exception_ids += exception_ids
  168. return all_exception_ids
  169. @api.model
  170. def _exception_rule_eval_context(self, obj_name, rec):
  171. return {obj_name: rec,
  172. 'self': self.env[rec._name],
  173. 'object': rec,
  174. 'obj': rec,
  175. 'env': self.env,
  176. 'cr': self.env.cr,
  177. 'uid': self.env.user.id,
  178. 'user': self.env.user,
  179. 'time': time,
  180. # copy context to prevent side-effects of eval
  181. 'context': self.env.context.copy()}
  182. @api.model
  183. def _rule_eval(self, rule, obj_name, rec):
  184. expr = rule.code
  185. space = self._exception_rule_eval_context(obj_name, rec)
  186. try:
  187. safe_eval(expr,
  188. space,
  189. mode='exec',
  190. nocopy=True) # nocopy allows to return 'result'
  191. except Exception as e:
  192. raise UserError(
  193. _('Error when evaluating the exception.rule '
  194. 'rule:\n %s \n(%s)') % (rule.name, e))
  195. return space.get('failed', False)
  196. @api.multi
  197. def _detect_exceptions(self, model_exceptions,
  198. sub_exceptions):
  199. self.ensure_one()
  200. exception_ids = []
  201. next_state_rule = False
  202. for rule in model_exceptions:
  203. if self._rule_eval(rule, self.rule_group, self):
  204. exception_ids.append(rule.id)
  205. if rule.next_state:
  206. if not next_state_rule or\
  207. rule.sequence < next_state_rule.sequence:
  208. next_state_rule = rule
  209. if sub_exceptions:
  210. for obj_line in self._get_lines():
  211. for rule in sub_exceptions:
  212. if rule.id in exception_ids:
  213. # we do not matter if the exception as already been
  214. # found for an line of this object
  215. # (ex sale order line if obj is sale order)
  216. continue
  217. group_line = self.rule_group + '_line'
  218. if self._rule_eval(rule, group_line, obj_line):
  219. exception_ids.append(rule.id)
  220. # set object to next state
  221. if next_state_rule:
  222. self.state = next_state_rule.next_state
  223. return exception_ids
  224. @implemented_by_base_exception
  225. def _get_lines(self):
  226. pass
  227. def _default_get_lines(self):
  228. return []