diff --git a/app/models/administrateur.rb b/app/models/administrateur.rb index a35e77098..d6bbbe258 100644 --- a/app/models/administrateur.rb +++ b/app/models/administrateur.rb @@ -12,6 +12,8 @@ class Administrateur < ApplicationRecord include ActiveRecord::SecureToken + UNUSED_ADMIN_THRESHOLD = 6.months + has_and_belongs_to_many :instructeurs has_and_belongs_to_many :procedures has_many :services @@ -23,6 +25,14 @@ class Administrateur < ApplicationRecord scope :inactive, -> { joins(:user).where(users: { last_sign_in_at: nil }) } scope :with_publiees_ou_closes, -> { joins(:procedures).where(procedures: { aasm_state: [:publiee, :close, :depubliee] }) } + scope :unused, -> do + joins(:user) + .where.missing(:services) + .left_outer_joins(:administrateurs_procedures) # needed to bypass procedure hidden default scope + .where(administrateurs_procedures: { procedure_id: nil }) + .where("users.last_sign_in_at < ? ", UNUSED_ADMIN_THRESHOLD.ago) + end + def self.by_email(email) Administrateur.find_by(users: { email: email }) end diff --git a/spec/models/administrateur_spec.rb b/spec/models/administrateur_spec.rb index ce21fb67a..9da4b2c0c 100644 --- a/spec/models/administrateur_spec.rb +++ b/spec/models/administrateur_spec.rb @@ -163,4 +163,34 @@ describe Administrateur, type: :model do end end end + + describe 'unused' do + subject { Administrateur.unused } + + let(:new_admin) { create(:administrateur) } + let(:unused_admin) { create(:administrateur) } + + before do + new_admin.user.update(last_sign_in_at: (6.months - 1.day).ago) + unused_admin.user.update(last_sign_in_at: (6.months + 1.day).ago) + end + + it { is_expected.to match([unused_admin]) } + + context 'with a hidden procedure' do + let(:procedure) { create(:procedure, hidden_at: 1.month.ago) } + + before { unused_admin.procedures << procedure } + + it { is_expected.to be_empty } + end + + context 'with a service' do + let(:service) { create(:service) } + + before { unused_admin.services << service } + + it { is_expected.to be_empty } + end + end end