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.

236 lines
8.8 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
  5. from ast import literal_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([rec.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. domain = []
  83. if tier.definition_domain:
  84. domain = literal_eval(tier.definition_domain)
  85. return self.search([('id', '=', self.id)] + domain)
  86. @api.model
  87. def _get_under_validation_exceptions(self):
  88. """Extend for more field exceptions."""
  89. return ['message_follower_ids']
  90. @api.multi
  91. def _check_allow_write_under_validation(self, vals):
  92. """Allow to add exceptions for fields that are allowed to be written
  93. even when the record is under validation."""
  94. exceptions = self._get_under_validation_exceptions()
  95. for val in vals:
  96. if val not in exceptions:
  97. return False
  98. return True
  99. @api.multi
  100. def write(self, vals):
  101. for rec in self:
  102. if (getattr(rec, self._state_field) in self._state_from and
  103. vals.get(self._state_field) in self._state_to):
  104. if rec.need_validation:
  105. # try to validate operation
  106. reviews = rec.request_validation()
  107. rec._validate_tier(reviews)
  108. if not self._calc_reviews_validated(reviews):
  109. raise ValidationError(_(
  110. "This action needs to be validated for at least "
  111. "one record. \nPlease request a validation."))
  112. if rec.review_ids and not rec.validated:
  113. raise ValidationError(_(
  114. "A validation process is still open for at least "
  115. "one record."))
  116. if (rec.review_ids and getattr(rec, self._state_field) in
  117. self._state_from and not vals.get(self._state_field) in
  118. (self._state_to + [self._cancel_state]) and not
  119. self._check_allow_write_under_validation(vals)):
  120. raise ValidationError(_("The operation is under validation."))
  121. if vals.get(self._state_field) in self._state_from:
  122. self.mapped('review_ids').unlink()
  123. return super(TierValidation, self).write(vals)
  124. def _validate_tier(self, tiers=False):
  125. self.ensure_one()
  126. tier_reviews = tiers or self.review_ids
  127. user_reviews = tier_reviews.filtered(
  128. lambda r: r.status in ('pending', 'rejected') and
  129. (self.env.user in r.reviewer_ids))
  130. user_reviews.write({
  131. 'status': 'approved',
  132. 'done_by': self.env.user.id,
  133. 'reviewed_date': fields.Datetime.now(),
  134. })
  135. for review in user_reviews:
  136. rec = self.env[review.model].browse(review.res_id)
  137. rec._notify_accepted_reviews()
  138. def _notify_accepted_reviews(self):
  139. if hasattr(self, 'message_post'):
  140. # Notify state change
  141. getattr(self, 'message_post')(
  142. subtype='mt_comment',
  143. body=self._notify_accepted_reviews_body()
  144. )
  145. def _notify_accepted_reviews_body(self):
  146. return _('A review was accepted')
  147. @api.multi
  148. def validate_tier(self):
  149. for rec in self:
  150. rec._validate_tier()
  151. self._update_counter()
  152. @api.multi
  153. def reject_tier(self):
  154. for rec in self:
  155. user_reviews = rec.review_ids.filtered(
  156. lambda r: r.status in ('pending', 'approved') and
  157. (r.reviewer_id == self.env.user or
  158. r.reviewer_group_id in self.env.user.groups_id))
  159. user_reviews.write({
  160. 'status': 'rejected',
  161. 'done_by': self.env.user.id,
  162. 'reviewed_date': fields.Datetime.now(),
  163. })
  164. rec._notify_rejected_review()
  165. self._update_counter()
  166. def _notify_rejected_review_body(self):
  167. return _('A review was rejected by %s.') % (self.env.user.name)
  168. def _notify_rejected_review(self):
  169. if hasattr(self, 'message_post'):
  170. # Notify state change
  171. getattr(self, 'message_post')(
  172. subtype='mt_comment',
  173. body=self._notify_rejected_review_body()
  174. )
  175. @api.multi
  176. def request_validation(self):
  177. td_obj = self.env['tier.definition']
  178. tr_obj = created_trs = self.env['tier.review']
  179. for rec in self:
  180. if getattr(rec, self._state_field) in self._state_from:
  181. if rec.need_validation:
  182. tier_definitions = td_obj.search([
  183. ('model', '=', self._name)], order="sequence desc")
  184. sequence = 0
  185. for td in tier_definitions:
  186. if self.evaluate_tier(td):
  187. sequence += 1
  188. created_trs += tr_obj.create({
  189. 'model': self._name,
  190. 'res_id': rec.id,
  191. 'definition_id': td.id,
  192. 'sequence': sequence,
  193. 'requested_by': self.env.uid,
  194. })
  195. self._update_counter()
  196. return created_trs
  197. @api.multi
  198. def restart_validation(self):
  199. for rec in self:
  200. if getattr(rec, self._state_field) in self._state_from:
  201. rec.mapped('review_ids').unlink()
  202. self._update_counter()
  203. @api.model
  204. def _update_counter(self):
  205. notifications = []
  206. channel = 'base.tier.validation'
  207. notifications.append([channel, {}])
  208. self.env['bus.bus'].sendmany(notifications)