add scope to query old admins

This commit is contained in:
simon lehericey 2022-05-02 14:32:12 +02:00
parent 50f798f54a
commit a2947751e2
2 changed files with 40 additions and 0 deletions

View file

@ -12,6 +12,8 @@
class Administrateur < ApplicationRecord class Administrateur < ApplicationRecord
include ActiveRecord::SecureToken include ActiveRecord::SecureToken
UNUSED_ADMIN_THRESHOLD = 6.months
has_and_belongs_to_many :instructeurs has_and_belongs_to_many :instructeurs
has_and_belongs_to_many :procedures has_and_belongs_to_many :procedures
has_many :services has_many :services
@ -23,6 +25,14 @@ class Administrateur < ApplicationRecord
scope :inactive, -> { joins(:user).where(users: { last_sign_in_at: nil }) } 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 :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) def self.by_email(email)
Administrateur.find_by(users: { email: email }) Administrateur.find_by(users: { email: email })
end end

View file

@ -163,4 +163,34 @@ describe Administrateur, type: :model do
end end
end 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 end