[#2179] Move code to DossierSearchService

This commit is contained in:
Frederic Merizen 2018-07-31 12:03:01 +02:00
parent 650a740642
commit 57fd59b8d5
2 changed files with 41 additions and 35 deletions

View file

@ -2,41 +2,7 @@ module NewGestionnaire
class RechercheController < GestionnaireController class RechercheController < GestionnaireController
def index def index
@search_terms = params[:q] @search_terms = params[:q]
@dossiers = DossierSearchService.matching_dossiers_for_gestionnaire(@search_terms)
# exact id match?
id = @search_terms.to_i
if id != 0 && id_compatible?(id) # Sometimes gestionnaire is searching dossiers with a big number (ex: SIRET), ActiveRecord can't deal with them and throws ActiveModel::RangeError. id_compatible? prevents this.
@dossiers = dossiers_by_id(id)
end
if @dossiers.nil?
@dossiers = Dossier.none
end
# full text search
if @dossiers.empty?
@dossiers = Search.new(
gestionnaire: current_gestionnaire,
query: @search_terms
).results
end
end
private
def dossiers_by_id(id)
dossiers = current_gestionnaire.dossiers.where(id: id) +
current_gestionnaire.dossiers_from_avis.where(id: id)
dossiers.uniq
end
def id_compatible?(number)
begin
ActiveRecord::Type::Integer.new.serialize(number)
true
rescue ActiveModel::RangeError
false
end
end end
end end
end end

View file

@ -0,0 +1,40 @@
class DossierSearchService
def self.matching_dossiers_for_gestionnaire(search_terms)
# exact id match?
id = search_terms.to_i
if id != 0 && id_compatible?(id) # Sometimes gestionnaire is searching dossiers with a big number (ex: SIRET), ActiveRecord can't deal with them and throws ActiveModel::RangeError. id_compatible? prevents this.
dossiers = dossiers_by_id(id)
end
if dossiers.nil?
dossiers = Dossier.none
end
# full text search
if dossiers.empty?
dossiers = Search.new(
gestionnaire: current_gestionnaire,
query: search_terms
).results
end
dossiers
end
private
def self.dossiers_by_id(id)
dossiers = current_gestionnaire.dossiers.where(id: id) +
current_gestionnaire.dossiers_from_avis.where(id: id)
dossiers.uniq
end
def self.id_compatible?(number)
begin
ActiveRecord::Type::Integer.new.serialize(number)
true
rescue ActiveModel::RangeError
false
end
end
end