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.

181 lines
7.1 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Eficent Business and IT Consulting Services S.L.
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  4. from openerp import api, fields, models, _
  5. from openerp.exceptions import ValidationError, UserError
  6. from openerp.tools.safe_eval import safe_eval
  7. class TierValidation(models.AbstractModel):
  8. _name = "tier.validation"
  9. _state_field = 'state'
  10. _state_from = ['draft']
  11. _state_to = ['confirmed']
  12. _cancel_state = 'cancel'
  13. # TODO: reset validation?
  14. # TODO: step by step validation?
  15. review_ids = fields.One2many(
  16. comodel_name='tier.review', inverse_name='res_id',
  17. string='Validations',
  18. domain=lambda self: [('model', '=', self._name)],
  19. auto_join=True,
  20. )
  21. validated = fields.Boolean(
  22. compute="_compute_validated_rejected",
  23. search="_search_validated",
  24. )
  25. need_validation = fields.Boolean(compute="_compute_need_validation")
  26. rejected = fields.Boolean(compute="_compute_validated_rejected")
  27. reviewer_ids = fields.Many2many(
  28. string="Reviewers", comodel_name="res.users",
  29. compute="_compute_reviewer_ids",
  30. search="_search_reviewer_ids",
  31. )
  32. @api.multi
  33. @api.depends('review_ids')
  34. def _compute_reviewer_ids(self):
  35. for rec in self:
  36. rec.reviewer_ids = rec.review_ids.filtered(
  37. lambda r: r.status == 'pending').mapped('reviewer_ids')
  38. @api.model
  39. def _search_validated(self, operator, value):
  40. assert operator in ('=', '!='), 'Invalid domain operator'
  41. assert value in (True, False), 'Invalid domain value'
  42. pos = self.search([
  43. (self._state_field, 'in', self._state_from)]).filtered(
  44. lambda r: r.review_ids and r.validated == value)
  45. return [('id', 'in', pos.ids)]
  46. @api.model
  47. def _search_reviewer_ids(self, operator, value):
  48. reviews = self.env['tier.review'].search([
  49. ('model', '=', self._name),
  50. ('reviewer_ids', operator, value),
  51. ('status', '=', 'pending')])
  52. return [('id', 'in', list(set(reviews.mapped('res_id'))))]
  53. @api.multi
  54. def _compute_validated_rejected(self):
  55. for rec in self:
  56. rec.validated = self._calc_reviews_validated(rec.review_ids)
  57. rec.rejected = self._calc_reviews_rejected(rec.review_ids)
  58. @api.model
  59. def _calc_reviews_validated(self, reviews):
  60. """Override for different validation policy."""
  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, 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 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').sudo().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