demarches-normaliennes/app/models/groupe_instructeur.rb

59 lines
2.1 KiB
Ruby
Raw Normal View History

2020-08-06 16:35:45 +02:00
# == Schema Information
#
# Table name: groupe_instructeurs
#
# id :bigint not null, primary key
# closed :boolean default(FALSE)
2020-08-06 16:35:45 +02:00
# label :text not null
# created_at :datetime not null
# updated_at :datetime not null
# procedure_id :bigint not null
#
2019-08-19 16:12:30 +02:00
class GroupeInstructeur < ApplicationRecord
DEFAUT_LABEL = 'défaut'
belongs_to :procedure, -> { with_discarded }, inverse_of: :groupe_instructeurs, optional: false
2020-06-11 10:08:04 +02:00
has_many :assign_tos, dependent: :destroy
has_many :instructeurs, through: :assign_tos
2019-08-22 17:58:31 +02:00
has_many :dossiers
has_and_belongs_to_many :exports, dependent: :destroy
has_and_belongs_to_many :bulk_messages, dependent: :destroy
2019-10-09 18:05:43 +02:00
validates :label, presence: { message: 'doit être renseigné' }, allow_nil: false
validates :label, uniqueness: { scope: :procedure, message: 'existe déjà' }
2022-10-17 11:01:55 +02:00
validates :closed, acceptance: { accept: [false], message: "Modification impossible : il doit y avoir au moins un groupe instructeur actif sur chaque procédure" }, if: -> { self.procedure.groupe_instructeurs.actif.one? }
2019-10-09 18:05:43 +02:00
before_validation -> { label&.strip! }
after_save :toggle_routing
scope :without_group, -> (group) { where.not(id: group) }
scope :for_api_v2, -> { includes(procedure: [:administrateurs]) }
scope :actif, -> { where(closed: false) }
def add(instructeur)
return if in?(instructeur.groupe_instructeurs)
default_notification_settings = instructeur.notification_settings(procedure_id)
instructeur.assign_to.create(groupe_instructeur: self, **default_notification_settings)
end
def remove(instructeur)
return if !in?(instructeur.groupe_instructeurs)
instructeur.groupe_instructeurs.destroy(self)
instructeur.follows
.joins(:dossier)
.where(dossiers: { groupe_instructeur: self })
.update_all(unfollowed_at: Time.zone.now)
end
2022-10-20 18:24:27 +02:00
def can_delete?
dossiers.empty? && (procedure.groupe_instructeurs.actif.many? || (procedure.groupe_instructeurs.actif.one? && closed))
end
private
def toggle_routing
procedure.update!(routing_enabled: procedure.groupe_instructeurs.actif.many?)
end
2019-08-19 16:12:30 +02:00
end