demarches-normaliennes/app/models/administrateur.rb

103 lines
2.5 KiB
Ruby
Raw Normal View History

2020-08-06 16:35:45 +02:00
# == Schema Information
#
# Table name: administrateurs
#
# id :integer not null, primary key
# active :boolean default(FALSE)
# encrypted_token :string
# created_at :datetime
# updated_at :datetime
#
2018-03-06 13:44:29 +01:00
class Administrateur < ApplicationRecord
include ActiveRecord::SecureToken
has_and_belongs_to_many :instructeurs
has_many :administrateurs_procedures
has_many :procedures, through: :administrateurs_procedures
2018-04-17 16:11:49 +02:00
has_many :services
2015-12-14 17:28:36 +01:00
has_one :user, dependent: :nullify
2019-08-09 09:45:11 +02:00
default_scope { eager_load(:user) }
scope :inactive, -> { joins(:user).where(users: { last_sign_in_at: nil }) }
2019-12-18 13:28:29 +01:00
scope :with_publiees_ou_closes, -> { joins(:procedures).where(procedures: { aasm_state: [:publiee, :close, :depubliee] }) }
def self.by_email(email)
Administrateur.find_by(users: { email: email })
end
2020-02-03 11:07:53 +01:00
def email
2020-03-24 14:45:53 +01:00
user&.email
2020-02-03 11:07:53 +01:00
end
def self.find_inactive_by_token(reset_password_token)
self.inactive.with_reset_password_token(reset_password_token)
end
def self.find_inactive_by_id(id)
self.inactive.find(id)
end
2015-12-14 17:28:36 +01:00
def renew_api_token
api_token = Administrateur.generate_unique_secure_token
encrypted_token = BCrypt::Password.create(api_token)
update(encrypted_token: encrypted_token)
api_token
2015-12-14 17:28:36 +01:00
end
def valid_api_token?(api_token)
BCrypt::Password.new(encrypted_token) == api_token
rescue BCrypt::Errors::InvalidHash
false
end
def registration_state
2019-11-05 10:05:59 +01:00
if user.active?
'Actif'
2019-08-19 09:48:55 +02:00
elsif user.reset_password_period_valid?
'En attente'
else
'Expiré'
end
end
def invitation_expired?
2019-11-05 10:05:59 +01:00
!user.active? && !user.reset_password_period_valid?
end
2018-05-17 15:39:37 +02:00
def owns?(procedure)
procedure.administrateurs.include?(self)
2018-05-17 15:39:37 +02:00
end
def instructeur
user.instructeur
end
def can_be_deleted?
procedures.all? { |p| p.administrateurs.count > 1 }
end
def delete_and_transfer_services
if !can_be_deleted?
2020-02-03 17:46:24 +01:00
fail "Impossible de supprimer cet administrateur car il a des démarches où il est le seul administrateur"
end
procedures.with_discarded.each do |procedure|
next_administrateur = procedure.administrateurs.where.not(id: self.id).first
procedure.service.update(administrateur: next_administrateur)
end
services.each do |service|
# We can't destroy a service if it has procedures, even if those procedures are archived
service.destroy unless service.procedures.with_discarded.any?
end
destroy
end
# required to display feature flags field in manager
def features
end
end