2014-02-03 19:23:00 +00:00
|
|
|
# Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
|
2013-08-19 06:29:49 +00:00
|
|
|
|
|
|
|
module Organization::Search
|
|
|
|
|
|
|
|
=begin
|
|
|
|
|
|
|
|
search organizations
|
|
|
|
|
|
|
|
result = Organization.search(
|
|
|
|
:current_user => User.find(123),
|
|
|
|
:query => 'search something',
|
|
|
|
:limit => 15,
|
|
|
|
)
|
|
|
|
|
|
|
|
returns
|
|
|
|
|
|
|
|
result = [organization_model1, organization_model2]
|
|
|
|
|
|
|
|
=end
|
|
|
|
|
|
|
|
def search(params)
|
|
|
|
|
|
|
|
# get params
|
|
|
|
query = params[:query]
|
|
|
|
limit = params[:limit] || 10
|
|
|
|
current_user = params[:current_user]
|
|
|
|
|
|
|
|
# enable search only for agents and admins
|
2015-02-15 09:12:27 +00:00
|
|
|
return [] if !current_user.is_role('Agent') && !current_user.is_role(Z_ROLENAME_ADMIN)
|
2013-08-19 06:29:49 +00:00
|
|
|
|
2014-01-29 23:55:25 +00:00
|
|
|
# try search index backend
|
2014-02-02 18:58:31 +00:00
|
|
|
if SearchIndexBackend.enabled?
|
2014-09-19 21:35:40 +00:00
|
|
|
items = SearchIndexBackend.search( query, limit, 'Organization' )
|
2014-01-29 23:55:25 +00:00
|
|
|
organizations = []
|
2014-09-19 21:35:40 +00:00
|
|
|
items.each { |item|
|
2015-04-27 13:42:53 +00:00
|
|
|
organizations.push Organization.lookup( id: item[:id] )
|
2014-01-29 23:55:25 +00:00
|
|
|
}
|
|
|
|
return organizations
|
|
|
|
end
|
|
|
|
|
|
|
|
# fallback do sql query
|
2014-02-11 13:09:23 +00:00
|
|
|
# - stip out * we already search for *query* -
|
|
|
|
query.gsub! '*', ''
|
2014-05-20 19:49:48 +00:00
|
|
|
organizations = Organization.where(
|
|
|
|
'name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"
|
|
|
|
).order('name').limit(limit)
|
2013-08-19 06:29:49 +00:00
|
|
|
|
|
|
|
# if only a few organizations are found, search for names of users
|
|
|
|
if organizations.length <= 3
|
2014-05-20 19:49:48 +00:00
|
|
|
organizations_by_user = Organization.select('DISTINCT(organizations.id)').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
|
|
|
|
'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
|
|
|
|
).order('organizations.name').limit(limit)
|
2013-08-19 06:29:49 +00:00
|
|
|
organizations_by_user.each {|organization_by_user|
|
|
|
|
organization_exists = false
|
|
|
|
organizations.each {|organization|
|
|
|
|
if organization.id == organization_by_user.id
|
|
|
|
organization_exists = true
|
|
|
|
end
|
|
|
|
}
|
2013-10-01 18:31:36 +00:00
|
|
|
|
|
|
|
# get model with full data
|
2013-08-19 06:29:49 +00:00
|
|
|
if !organization_exists
|
2013-10-01 18:31:36 +00:00
|
|
|
organizations.push Organization.find(organization_by_user)
|
2013-08-19 06:29:49 +00:00
|
|
|
end
|
|
|
|
}
|
|
|
|
end
|
|
|
|
organizations
|
|
|
|
end
|
2014-02-03 19:23:00 +00:00
|
|
|
end
|