trabajo-afectivo/app/models/organization/search.rb

101 lines
2.6 KiB
Ruby
Raw Normal View History

2016-10-19 03:11:36 +00:00
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
2015-04-27 21:44:41 +00:00
class Organization
module Search
=begin
search organizations preferences
result = Organization.search_preferences(user_model)
returns if user has permissions to search
result = {
prio: 1000,
direct_search_index: true
}
returns if user has no permissions to search
result = false
=end
def search_preferences(current_user)
return false if !current_user.permissions?('ticket.agent') && !current_user.permissions?('admin.organization')
{
prio: 1000,
direct_search_index: true,
}
end
=begin
search organizations
result = Organization.search(
2016-01-20 01:48:54 +00:00
current_user: User.find(123),
query: 'search something',
limit: 15,
)
returns
result = [organization_model1, organization_model2]
=end
2015-04-27 21:44:41 +00:00
def search(params)
2015-04-27 21:44:41 +00:00
# get params
query = params[:query]
limit = params[:limit] || 10
current_user = params[:current_user]
2015-04-27 21:44:41 +00:00
# enable search only for agents and admins
return [] if !search_preferences(current_user)
2015-04-27 21:44:41 +00:00
# try search index backend
if SearchIndexBackend.enabled?
2016-01-20 01:48:54 +00:00
items = SearchIndexBackend.search(query, limit, 'Organization')
2015-04-27 21:44:41 +00:00
organizations = []
items.each { |item|
organization = Organization.lookup(id: item[:id])
next if !organization
organizations.push organization
2015-04-27 21:44:41 +00:00
}
return organizations
end
2014-01-29 23:55:25 +00:00
2015-04-27 21:44:41 +00:00
# fallback do sql query
# - stip out * we already search for *query* -
2015-08-21 23:55:59 +00:00
query.delete! '*'
2015-04-27 21:44:41 +00:00
organizations = Organization.where(
'name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"
2017-09-08 08:28:34 +00:00
).order('name').limit(limit).to_a
2015-04-27 21:44:41 +00:00
# if only a few organizations are found, search for names of users
if organizations.length <= 3
2016-01-20 01:48:54 +00:00
organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
2015-04-27 21:44:41 +00:00
'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
).order('organizations.name').limit(limit)
2016-06-30 20:04:48 +00:00
organizations_by_user.each { |organization_by_user|
2015-04-27 21:44:41 +00:00
organization_exists = false
2016-06-30 20:04:48 +00:00
organizations.each { |organization|
2015-04-27 21:44:41 +00:00
if organization.id == organization_by_user.id
organization_exists = true
end
}
# get model with full data
if !organization_exists
organizations.push Organization.find(organization_by_user.id)
end
}
2015-04-27 21:44:41 +00:00
end
organizations
end
end
2014-02-03 19:23:00 +00:00
end