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.

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