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.

343 lines
12 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. exception_type = fields.Selection(
  38. selection=[('by_domain', 'By domain'),
  39. ('by_py_code', 'By python code')],
  40. string='Exception Type', required=True, default='by_py_code',
  41. help="By python code: allow to define any arbitrary check\n"
  42. "By domain: limited to a selection by an odoo domain:\n"
  43. " performance can be better when exceptions "
  44. " are evaluated with several records")
  45. domain = fields.Char('Domain')
  46. active = fields.Boolean('Active')
  47. code = fields.Text(
  48. 'Python Code',
  49. help="Python code executed to check if the exception apply or "
  50. "not. The code must apply failed = True to apply the "
  51. "exception.",
  52. default="""
  53. # Python code. Use failed = True to block the base.exception.
  54. # You can use the following variables :
  55. # - self: ORM model of the record which is checked
  56. # - "rule_group" or "rule_group_"line:
  57. # browse_record of the base.exception or
  58. # base.exception line (ex rule_group = sale for sale order)
  59. # - object: same as order or line, browse_record of the base.exception or
  60. # base.exception line
  61. # - pool: ORM model pool (i.e. self.pool, deprecated in new api)
  62. # - obj: same as object
  63. # - env: ORM model pool (i.e. self.env)
  64. # - time: Python time module
  65. # - cr: database cursor
  66. # - uid: current user id
  67. # - context: current context
  68. """)
  69. @api.multi
  70. def _get_domain(self):
  71. """ override me to customize domains according exceptions cases """
  72. self.ensure_one()
  73. return safe_eval(self.domain)
  74. class BaseException(models.AbstractModel):
  75. _name = 'base.exception'
  76. _order = 'main_exception_id asc'
  77. main_exception_id = fields.Many2one(
  78. 'exception.rule',
  79. compute='_compute_main_error',
  80. string='Main Exception',
  81. store=True)
  82. rule_group = fields.Selection(
  83. [],
  84. readonly=True,
  85. )
  86. exception_ids = fields.Many2many(
  87. 'exception.rule',
  88. string='Exceptions')
  89. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  90. @api.depends('exception_ids', 'ignore_exception')
  91. def _compute_main_error(self):
  92. for obj in self:
  93. if not obj.ignore_exception and obj.exception_ids:
  94. obj.main_exception_id = obj.exception_ids[0]
  95. else:
  96. obj.main_exception_id = False
  97. @api.multi
  98. def _popup_exceptions(self):
  99. action = self._get_popup_action()
  100. action = action.read()[0]
  101. action.update({
  102. 'context': {
  103. 'active_model': self._name,
  104. 'active_id': self.ids[0],
  105. 'active_ids': self.ids
  106. }
  107. })
  108. return action
  109. @api.model
  110. def _get_popup_action(self):
  111. action = self.env.ref('base_exception.action_exception_rule_confirm')
  112. return action
  113. @api.multi
  114. def _check_exception(self):
  115. """
  116. This method must be used in a constraint that must be created in the
  117. object that inherits for base.exception.
  118. for sale :
  119. @api.constrains('ignore_exception',)
  120. def sale_check_exception(self):
  121. ...
  122. ...
  123. self._check_exception
  124. """
  125. exception_ids = self.detect_exceptions()
  126. if exception_ids:
  127. exceptions = self.env['exception.rule'].browse(exception_ids)
  128. raise ValidationError('\n'.join(exceptions.mapped('name')))
  129. @api.multi
  130. def test_exceptions(self):
  131. """
  132. Condition method for the workflow from draft to confirm
  133. """
  134. if self.detect_exceptions():
  135. return False
  136. return True
  137. @api.multi
  138. def _reverse_field(self):
  139. """Name of the many2many field from exception rule to self.
  140. In order to take advantage of domain optimisation, exception rule
  141. model should have a many2many field to inherited object.
  142. The opposit relation already exists in the name of exception_ids
  143. Example:
  144. class ExceptionRule(models.Model):
  145. _inherit = 'exception.rule'
  146. model = fields.Selection(
  147. selection_add=[
  148. ('sale.order', 'Sale order'),
  149. [...]
  150. ])
  151. sale_ids = fields.Many2many(
  152. 'sale.order',
  153. string='Sales')
  154. [...]
  155. """
  156. exception_obj = self.env['exception.rule']
  157. reverse_fields = self.env['ir.model.fields'].search([
  158. ['model', '=', 'exception.rule'],
  159. ['ttype', '=', 'many2many'],
  160. ['relation', '=', self[0]._name],
  161. ])
  162. # ir.model.fields may contain old variable name
  163. # so we check if the field exists on exception rule
  164. return ([
  165. field.name for field in reverse_fields
  166. if hasattr(exception_obj, field.name)
  167. ] or [None])[0]
  168. @api.multi
  169. def detect_exceptions(self):
  170. """List all exception_ids applied on self
  171. Exception ids are also written on records
  172. """
  173. if not self:
  174. return []
  175. exception_obj = self.env['exception.rule']
  176. all_exceptions = exception_obj.sudo().search(
  177. [('rule_group', '=', self[0].rule_group)])
  178. # TODO fix self[0] : it may not be the same on all ids in self
  179. model_exceptions = all_exceptions.filtered(
  180. lambda ex: ex.model == self._name)
  181. sub_exceptions = all_exceptions.filtered(
  182. lambda ex: ex.model != self._name)
  183. reverse_field = self._reverse_field()
  184. if reverse_field:
  185. optimize = True
  186. else:
  187. optimize = False
  188. exception_by_rec, exception_by_rule = self._detect_exceptions(
  189. model_exceptions, sub_exceptions, optimize)
  190. all_exception_ids = []
  191. for obj, exception_ids in exception_by_rec.iteritems():
  192. obj.exception_ids = [(6, 0, exception_ids)]
  193. all_exception_ids += exception_ids
  194. for rule, exception_ids in exception_by_rule.iteritems():
  195. rule[reverse_field] = [(6, 0, exception_ids.ids)]
  196. if exception_ids:
  197. all_exception_ids += [rule.id]
  198. return list(set(all_exception_ids))
  199. @api.model
  200. def _exception_rule_eval_context(self, obj_name, rec):
  201. return {obj_name: rec,
  202. 'self': self.pool.get(rec._name),
  203. 'object': rec,
  204. 'obj': rec,
  205. 'pool': self.pool,
  206. 'env': self.env,
  207. 'cr': self.env.cr,
  208. 'uid': self.env.uid,
  209. 'user': self.env.user,
  210. 'time': time,
  211. # copy context to prevent side-effects of eval
  212. 'context': self.env.context.copy()}
  213. @api.model
  214. def _rule_eval(self, rule, obj_name, rec):
  215. expr = rule.code
  216. space = self._exception_rule_eval_context(obj_name, rec)
  217. try:
  218. safe_eval(expr,
  219. space,
  220. mode='exec',
  221. nocopy=True) # nocopy allows to return 'result'
  222. except Exception, e:
  223. raise UserError(
  224. _('Error when evaluating the exception.rule '
  225. 'rule:\n %s \n(%s)') % (rule.name, e))
  226. return space.get('failed', False)
  227. @api.multi
  228. def _detect_exceptions(
  229. self, model_exceptions, sub_exceptions,
  230. optimize=False,
  231. ):
  232. """Find exceptions found on self.
  233. @returns
  234. exception_by_rec: (record_id, exception_ids)
  235. exception_by_rule: (rule_id, record_ids)
  236. """
  237. exception_by_rec = {}
  238. exception_by_rule = {}
  239. exception_set = set()
  240. python_rules = []
  241. dom_rules = []
  242. optim_rules = []
  243. for rule in model_exceptions:
  244. if rule.exception_type == 'by_py_code':
  245. python_rules.append(rule)
  246. elif rule.exception_type == 'by_domain' and rule.domain:
  247. if optimize:
  248. optim_rules.append(rule)
  249. else:
  250. dom_rules.append(rule)
  251. for rule in optim_rules:
  252. domain = rule._get_domain()
  253. domain.append(['ignore_exception', '=', False])
  254. domain.append(['id', 'in', self.ids])
  255. records_with_exception = self.search(domain)
  256. exception_by_rule[rule] = records_with_exception
  257. if records_with_exception:
  258. exception_set.add(rule.id)
  259. if len(python_rules) or len(dom_rules) or sub_exceptions:
  260. for rec in self:
  261. for rule in python_rules:
  262. if (
  263. not rec.ignore_exception and
  264. self._rule_eval(rule, rec.rule_group, rec)
  265. ):
  266. exception_by_rec.setdefault(rec, []).append(rule.id)
  267. exception_set.add(rule.id)
  268. for rule in dom_rules:
  269. # there is no reverse many2many, so this rule
  270. # can't be optimized, see _reverse_field
  271. domain = rule._get_domain()
  272. domain.append(['ignore_exception', '=', False])
  273. domain.append(['id', '=', rec.id])
  274. if self.search_count(domain):
  275. exception_by_rec.setdefault(
  276. rec, []).append(rule.id)
  277. exception_set.add(rule.id)
  278. if sub_exceptions:
  279. group_line = rec.rule_group + '_line'
  280. for obj_line in rec._get_lines():
  281. for rule in sub_exceptions:
  282. if rule.id in exception_set:
  283. # we do not matter if the exception as
  284. # already been
  285. # found for an line of this object
  286. # (ex sale order line if obj is sale order)
  287. continue
  288. if rule.exception_type == 'by_py_code':
  289. if self._rule_eval(
  290. rule, group_line, obj_line
  291. ):
  292. exception_by_rec.setdefault(
  293. rec, []).append(rule.id)
  294. elif (
  295. rule.exception_type == 'by_domain' and
  296. rule.domain
  297. ):
  298. # sub_exception are currently not optimizable
  299. domain = rule._get_domain()
  300. domain.append(('id', '=', obj_line.id))
  301. if obj_line.search_count(domain):
  302. exception_by_rec.setdefault(
  303. rec, []).append(rule.id)
  304. return exception_by_rec, exception_by_rule
  305. @implemented_by_base_exception
  306. def _get_lines(self):
  307. pass
  308. def _default_get_lines(self):
  309. return []