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.

151 lines
6.0 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(compute="_compute_validated_rejected")
  22. need_validation = fields.Boolean(compute="_compute_need_validation")
  23. rejected = fields.Boolean(compute="_compute_validated_rejected")
  24. reviewer_ids = fields.Many2many(
  25. string="Reviewers", comodel_name="res.users",
  26. compute="_compute_reviewer_ids",
  27. search="_search_reviewer_ids",
  28. )
  29. @api.multi
  30. @api.depends('review_ids')
  31. def _compute_reviewer_ids(self):
  32. for rec in self:
  33. rec.reviewer_ids = rec.review_ids.filtered(
  34. lambda r: r.status == 'pending').mapped('reviewer_ids')
  35. @api.model
  36. def _search_reviewer_ids(self, operator, value):
  37. reviews = self.env['tier.review'].search([
  38. ('model', '=', self._name), ('reviewer_ids', operator, value)])
  39. return [('id', 'in', list(set(reviews.mapped('res_id'))))]
  40. @api.multi
  41. def _compute_validated_rejected(self):
  42. for rec in self:
  43. rec.validated = self._calc_reviews_validated(rec.review_ids)
  44. rec.rejected = self._calc_reviews_rejected(rec.review_ids)
  45. @api.model
  46. def _calc_reviews_validated(self, reviews):
  47. """Override for different validation policy."""
  48. return not any([s != 'approved' for s in reviews.mapped('status')])
  49. @api.model
  50. def _calc_reviews_rejected(self, reviews):
  51. """Override for different rejection policy."""
  52. return any([s == 'rejected' for s in reviews.mapped('status')])
  53. @api.multi
  54. def _compute_need_validation(self):
  55. for rec in self:
  56. tiers = self.env[
  57. 'tier.definition'].search([('model', '=', self._name)])
  58. valid_tiers = any([self.evaluate_tier(tier) for tier in tiers])
  59. rec.need_validation = not self.review_ids and valid_tiers and \
  60. getattr(rec, self._state_field) in self._state_from
  61. @api.multi
  62. def evaluate_tier(self, tier):
  63. try:
  64. res = safe_eval(tier.python_code, globals_dict={'rec': self})
  65. except Exception, error:
  66. raise UserError(_(
  67. "Error evaluating tier validation conditions.\n %s") % error)
  68. return res
  69. @api.multi
  70. def write(self, vals):
  71. for rec in self:
  72. if (getattr(rec, self._state_field) in self._state_from and
  73. vals.get(self._state_field) in self._state_to):
  74. if rec.need_validation:
  75. # try to validate operation
  76. reviews = rec.request_validation()
  77. rec._validate_tier(reviews)
  78. if not self._calc_reviews_validated(reviews):
  79. raise ValidationError(_(
  80. "This action needs to be validated for at least "
  81. "one record. \nPlease request a validation."))
  82. if not rec.validated:
  83. raise ValidationError(_(
  84. "A validation process is still open for at least "
  85. "one record."))
  86. if (rec.review_ids and getattr(rec, self._state_field) in
  87. self._state_from and not vals.get(self._state_field) in
  88. (self._state_to + [self._cancel_state])):
  89. raise ValidationError(_("The operation is under validation."))
  90. if vals.get(self._state_field) in self._state_from:
  91. self.mapped('review_ids').sudo().unlink()
  92. return super(TierValidation, self).write(vals)
  93. def _validate_tier(self, tiers=False):
  94. self.ensure_one()
  95. tier_reviews = tiers or self.review_ids
  96. user_reviews = tier_reviews.filtered(
  97. lambda r: r.status in ('pending', 'rejected') and
  98. (r.reviewer_id == self.env.user or
  99. r.reviewer_group_id in self.env.user.groups_id))
  100. user_reviews.write({'status': 'approved'})
  101. @api.multi
  102. def validate_tier(self):
  103. for rec in self:
  104. rec._validate_tier()
  105. @api.multi
  106. def reject_tier(self):
  107. for rec in self:
  108. user_reviews = rec.review_ids.filtered(
  109. lambda r: r.status in ('pending', 'approved') and
  110. (r.reviewer_id == self.env.user or
  111. r.reviewer_group_id in self.env.user.groups_id))
  112. user_reviews.write({'status': 'rejected'})
  113. @api.multi
  114. def request_validation(self):
  115. td_obj = self.env['tier.definition']
  116. tr_obj = created_trs = self.env['tier.review']
  117. for rec in self:
  118. if getattr(rec, self._state_field) in self._state_from:
  119. if rec.need_validation:
  120. tier_definitions = td_obj.search([
  121. ('model', '=', self._name)], order="sequence desc")
  122. sequence = 0
  123. for td in tier_definitions:
  124. if self.evaluate_tier(td):
  125. sequence += 1
  126. created_trs += tr_obj.create({
  127. 'model': self._name,
  128. 'res_id': rec.id,
  129. 'definition_id': td.id,
  130. 'sequence': sequence,
  131. })
  132. # TODO: notify? post some msg in chatter?
  133. return created_trs