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.

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