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.

165 lines
6.5 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.multi
  83. def write(self, vals):
  84. for rec in self:
  85. if (getattr(rec, self._state_field) in self._state_from and
  86. vals.get(self._state_field) in self._state_to):
  87. if rec.need_validation:
  88. # try to validate operation
  89. reviews = rec.request_validation()
  90. rec._validate_tier(reviews)
  91. if not self._calc_reviews_validated(reviews):
  92. raise ValidationError(_(
  93. "This action needs to be validated for at least "
  94. "one record. \nPlease request a validation."))
  95. if not rec.validated:
  96. raise ValidationError(_(
  97. "A validation process is still open for at least "
  98. "one record."))
  99. if (rec.review_ids and getattr(rec, self._state_field) in
  100. self._state_from and not vals.get(self._state_field) in
  101. (self._state_to + [self._cancel_state])):
  102. raise ValidationError(_("The operation is under validation."))
  103. if vals.get(self._state_field) in self._state_from:
  104. self.mapped('review_ids').sudo().unlink()
  105. return super(TierValidation, self).write(vals)
  106. def _validate_tier(self, tiers=False):
  107. self.ensure_one()
  108. tier_reviews = tiers or self.review_ids
  109. user_reviews = tier_reviews.filtered(
  110. lambda r: r.status in ('pending', 'rejected') and
  111. (r.reviewer_id == self.env.user or
  112. r.reviewer_group_id in self.env.user.groups_id))
  113. user_reviews.write({'status': 'approved'})
  114. @api.multi
  115. def validate_tier(self):
  116. for rec in self:
  117. rec._validate_tier()
  118. @api.multi
  119. def reject_tier(self):
  120. for rec in self:
  121. user_reviews = rec.review_ids.filtered(
  122. lambda r: r.status in ('pending', 'approved') and
  123. (r.reviewer_id == self.env.user or
  124. r.reviewer_group_id in self.env.user.groups_id))
  125. user_reviews.write({'status': 'rejected'})
  126. @api.multi
  127. def request_validation(self):
  128. td_obj = self.env['tier.definition']
  129. tr_obj = created_trs = self.env['tier.review']
  130. for rec in self:
  131. if getattr(rec, self._state_field) in self._state_from:
  132. if rec.need_validation:
  133. tier_definitions = td_obj.search([
  134. ('model', '=', self._name)], order="sequence desc")
  135. sequence = 0
  136. for td in tier_definitions:
  137. if self.evaluate_tier(td):
  138. sequence += 1
  139. created_trs += tr_obj.create({
  140. 'model': self._name,
  141. 'res_id': rec.id,
  142. 'definition_id': td.id,
  143. 'sequence': sequence,
  144. })
  145. # TODO: notify? post some msg in chatter?
  146. return created_trs