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.

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