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