module Teams class StaffEmailValidator def self.assert_available!(team:, email:, except_user: nil, staff_kind: nil) new(team: team, email: email, except_user: except_user).assert_available! end def initialize(team:, email:, except_user: nil) @team = team @email = email.to_s.downcase.strip @except_user = except_user end def assert_available! user_scope = @team.user_teams.joins(:user).where(users: { email: @email }).where.not(staff_kind: nil) user_scope = user_scope.where.not(user_id: @except_user.id) if @except_user if user_scope.exists? raise StaffAssignmentError, "L'email #{@email} è già assegnata come responsabile trasmissione per questa squadra." end inv = @team.team_invitations.pending.where("LOWER(email) = ?", @email) return unless inv.exists? raise StaffAssignmentError, "Esiste già un invito in sospeso per #{@email}." end end end