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.

247 lines
8.6 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. """
  77. rules = self.env['exception.rule'].sudo().search(
  78. self._rule_domain())
  79. all_exception_ids = []
  80. for rule in rules:
  81. records_with_exception = self._detect_exceptions(rule)
  82. reverse_field = self._reverse_field()
  83. main_records = self._get_main_records()
  84. commons = main_records & rule[reverse_field]
  85. to_remove = commons - records_with_exception
  86. to_add = records_with_exception - commons
  87. to_remove_list = [(3, x.id, _) for x in to_remove]
  88. to_add_list = [(4, x.id, _) for x in to_add]
  89. rule.write({reverse_field: to_remove_list + to_add_list})
  90. if records_with_exception:
  91. all_exception_ids.append(rule.id)
  92. return all_exception_ids
  93. @api.model
  94. def _exception_rule_eval_context(self, rec):
  95. return {
  96. 'time': time,
  97. 'self': rec,
  98. # object, obj: deprecated.
  99. # should be removed in future migrations
  100. 'object': rec,
  101. 'obj': rec,
  102. # copy context to prevent side-effects of eval
  103. # should be deprecated too, accesible through self.
  104. 'context': self.env.context.copy()
  105. }
  106. @api.model
  107. def _rule_eval(self, rule, rec):
  108. expr = rule.code
  109. space = self._exception_rule_eval_context(rec)
  110. try:
  111. safe_eval(expr,
  112. space,
  113. mode='exec',
  114. nocopy=True) # nocopy allows to return 'result'
  115. except Exception as e:
  116. raise UserError(
  117. _('Error when evaluating the exception.rule '
  118. 'rule:\n %s \n(%s)') % (rule.name, e))
  119. return space.get('failed', False)
  120. @api.multi
  121. def _detect_exceptions(self, rule):
  122. if rule.exception_type == 'by_py_code':
  123. return self._detect_exceptions_by_py_code(rule)
  124. elif rule.exception_type == 'by_domain':
  125. return self._detect_exceptions_by_domain(rule)
  126. @api.multi
  127. def _get_base_domain(self):
  128. return [('ignore_exception', '=', False), ('id', 'in', self.ids)]
  129. @api.multi
  130. def _detect_exceptions_by_py_code(self, rule):
  131. """
  132. Find exceptions found on self.
  133. """
  134. domain = self._get_base_domain()
  135. records = self.search(domain)
  136. records_with_exception = self.env[self._name]
  137. for record in records:
  138. if self._rule_eval(rule, record):
  139. records_with_exception |= record
  140. return records_with_exception
  141. @api.multi
  142. def _detect_exceptions_by_domain(self, rule):
  143. """
  144. Find exceptions found on self.
  145. """
  146. base_domain = self._get_base_domain()
  147. rule_domain = rule._get_domain()
  148. domain = osv.expression.AND([base_domain, rule_domain])
  149. return self.search(domain)
  150. class BaseException(models.AbstractModel):
  151. _inherit = 'base.exception.method'
  152. _name = 'base.exception'
  153. _order = 'main_exception_id asc'
  154. _description = 'Exception'
  155. main_exception_id = fields.Many2one(
  156. 'exception.rule',
  157. compute='_compute_main_error',
  158. string='Main Exception',
  159. store=True,
  160. )
  161. exceptions_summary = fields.Html(
  162. 'Exceptions Summary',
  163. compute='_compute_exceptions_summary',
  164. )
  165. exception_ids = fields.Many2many(
  166. 'exception.rule',
  167. string='Exceptions',
  168. copy=False,
  169. )
  170. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  171. @api.multi
  172. def action_ignore_exceptions(self):
  173. self.write({'ignore_exception': True})
  174. return True
  175. @api.depends('exception_ids', 'ignore_exception')
  176. def _compute_main_error(self):
  177. for rec in self:
  178. if not rec.ignore_exception and rec.exception_ids:
  179. rec.main_exception_id = rec.exception_ids[0]
  180. else:
  181. rec.main_exception_id = False
  182. @api.depends('exception_ids', 'ignore_exception')
  183. def _compute_exceptions_summary(self):
  184. for rec in self:
  185. if rec.exception_ids and not rec.ignore_exception:
  186. rec.exceptions_summary = '<ul>%s</ul>' % ''.join([
  187. '<li>%s: <i>%s</i></li>' % tuple(map(html.escape, (
  188. e.name, e.description))) for e in rec.exception_ids])
  189. @api.multi
  190. def _popup_exceptions(self):
  191. action = self._get_popup_action().read()[0]
  192. action.update({
  193. 'context': {
  194. 'active_id': self.ids[0],
  195. 'active_ids': self.ids,
  196. 'active_model': self._name,
  197. }
  198. })
  199. return action
  200. @api.model
  201. def _get_popup_action(self):
  202. return self.env.ref('base_exception.action_exception_rule_confirm')
  203. @api.multi
  204. def _check_exception(self):
  205. """
  206. This method must be used in a constraint that must be created in the
  207. object that inherits for base.exception.
  208. for sale :
  209. @api.constrains('ignore_exception',)
  210. def sale_check_exception(self):
  211. ...
  212. ...
  213. self._check_exception
  214. """
  215. exception_ids = self.detect_exceptions()
  216. if exception_ids:
  217. exceptions = self.env['exception.rule'].browse(exception_ids)
  218. raise ValidationError('\n'.join(exceptions.mapped('name')))