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.

187 lines
7.2 KiB

  1. # Copyright 2017 Eficent Business and IT Consulting Services S.L.
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. from odoo import api, fields, models, _
  4. from odoo.exceptions import ValidationError, UserError
  5. from odoo.tools.safe_eval import safe_eval
  6. class TierValidation(models.AbstractModel):
  7. _name = "tier.validation"
  8. _state_field = 'state'
  9. _state_from = ['draft']
  10. _state_to = ['confirmed']
  11. _cancel_state = 'cancel'
  12. # TODO: step by step validation?
  13. review_ids = fields.One2many(
  14. comodel_name='tier.review', inverse_name='res_id',
  15. string='Validations',
  16. domain=lambda self: [('model', '=', self._name)],
  17. auto_join=True,
  18. )
  19. validated = fields.Boolean(
  20. compute="_compute_validated_rejected",
  21. search="_search_validated",
  22. )
  23. need_validation = fields.Boolean(compute="_compute_need_validation")
  24. rejected = fields.Boolean(compute="_compute_validated_rejected")
  25. reviewer_ids = fields.Many2many(
  26. string="Reviewers", comodel_name="res.users",
  27. compute="_compute_reviewer_ids",
  28. search="_search_reviewer_ids",
  29. )
  30. @api.multi
  31. @api.depends('review_ids')
  32. def _compute_reviewer_ids(self):
  33. for rec in self:
  34. rec.reviewer_ids = rec.review_ids.filtered(
  35. lambda r: r.status == 'pending').mapped('reviewer_ids')
  36. @api.model
  37. def _search_validated(self, operator, value):
  38. assert operator in ('=', '!='), 'Invalid domain operator'
  39. assert value in (True, False), 'Invalid domain value'
  40. pos = self.search([
  41. (self._state_field, 'in', self._state_from)]).filtered(
  42. lambda r: r.review_ids and r.validated == value)
  43. return [('id', 'in', pos.ids)]
  44. @api.model
  45. def _search_reviewer_ids(self, operator, value):
  46. reviews = self.env['tier.review'].search([
  47. ('model', '=', self._name),
  48. ('reviewer_ids', operator, value),
  49. ('status', '=', 'pending')])
  50. return [('id', 'in', list(set(reviews.mapped('res_id'))))]
  51. @api.multi
  52. def _compute_validated_rejected(self):
  53. for rec in self:
  54. rec.validated = self._calc_reviews_validated(rec.review_ids)
  55. rec.rejected = self._calc_reviews_rejected(rec.review_ids)
  56. @api.model
  57. def _calc_reviews_validated(self, reviews):
  58. """Override for different validation policy."""
  59. if not reviews:
  60. return False
  61. return not any([s != 'approved' for s in reviews.mapped('status')])
  62. @api.model
  63. def _calc_reviews_rejected(self, reviews):
  64. """Override for different rejection policy."""
  65. return any([s == 'rejected' for s in reviews.mapped('status')])
  66. @api.multi
  67. def _compute_need_validation(self):
  68. for rec in self:
  69. tiers = self.env[
  70. 'tier.definition'].search([('model', '=', self._name)])
  71. valid_tiers = any([self.evaluate_tier(tier) for tier in tiers])
  72. rec.need_validation = not self.review_ids and valid_tiers and \
  73. getattr(rec, self._state_field) in self._state_from
  74. @api.multi
  75. def evaluate_tier(self, tier):
  76. try:
  77. res = safe_eval(tier.python_code, globals_dict={'rec': self})
  78. except Exception as error:
  79. raise UserError(_(
  80. "Error evaluating tier validation conditions.\n %s") % error)
  81. return res
  82. @api.model
  83. def _get_under_validation_exceptions(self):
  84. """Extend for more field exceptions."""
  85. return ['message_follower_ids']
  86. @api.multi
  87. def _check_allow_write_under_validation(self, vals):
  88. """Allow to add exceptions for fields that are allowed to be written
  89. even when the record is under validation."""
  90. exceptions = self._get_under_validation_exceptions()
  91. for val in vals:
  92. if val not in exceptions:
  93. return False
  94. return True
  95. @api.multi
  96. def write(self, vals):
  97. for rec in self:
  98. if (getattr(rec, self._state_field) in self._state_from and
  99. vals.get(self._state_field) in self._state_to):
  100. if rec.need_validation:
  101. # try to validate operation
  102. reviews = rec.request_validation()
  103. rec._validate_tier(reviews)
  104. if not self._calc_reviews_validated(reviews):
  105. raise ValidationError(_(
  106. "This action needs to be validated for at least "
  107. "one record. \nPlease request a validation."))
  108. if rec.review_ids and not rec.validated:
  109. raise ValidationError(_(
  110. "A validation process is still open for at least "
  111. "one record."))
  112. if (rec.review_ids and getattr(rec, self._state_field) in
  113. self._state_from and not vals.get(self._state_field) in
  114. (self._state_to + [self._cancel_state]) and not
  115. self._check_allow_write_under_validation(vals)):
  116. raise ValidationError(_("The operation is under validation."))
  117. if vals.get(self._state_field) in self._state_from:
  118. self.mapped('review_ids').unlink()
  119. return super(TierValidation, self).write(vals)
  120. def _validate_tier(self, tiers=False):
  121. self.ensure_one()
  122. tier_reviews = tiers or self.review_ids
  123. user_reviews = tier_reviews.filtered(
  124. lambda r: r.status in ('pending', 'rejected') and
  125. (r.reviewer_id == self.env.user or
  126. r.reviewer_group_id in self.env.user.groups_id))
  127. user_reviews.write({'status': 'approved'})
  128. @api.multi
  129. def validate_tier(self):
  130. for rec in self:
  131. rec._validate_tier()
  132. @api.multi
  133. def reject_tier(self):
  134. for rec in self:
  135. user_reviews = rec.review_ids.filtered(
  136. lambda r: r.status in ('pending', 'approved') and
  137. (r.reviewer_id == self.env.user or
  138. r.reviewer_group_id in self.env.user.groups_id))
  139. user_reviews.write({'status': 'rejected'})
  140. @api.multi
  141. def request_validation(self):
  142. td_obj = self.env['tier.definition']
  143. tr_obj = created_trs = self.env['tier.review']
  144. for rec in self:
  145. if getattr(rec, self._state_field) in self._state_from:
  146. if rec.need_validation:
  147. tier_definitions = td_obj.search([
  148. ('model', '=', self._name)], order="sequence desc")
  149. sequence = 0
  150. for td in tier_definitions:
  151. if self.evaluate_tier(td):
  152. sequence += 1
  153. created_trs += tr_obj.create({
  154. 'model': self._name,
  155. 'res_id': rec.id,
  156. 'definition_id': td.id,
  157. 'sequence': sequence,
  158. })
  159. # TODO: notify? post some msg in chatter?
  160. return created_trs
  161. @api.multi
  162. def restart_validation(self):
  163. for rec in self:
  164. if getattr(rec, self._state_field) in self._state_from:
  165. rec.mapped('review_ids').unlink()