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.

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