search.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. module Organization::Search
  3. =begin
  4. search organizations
  5. result = Organization.search(
  6. :current_user => User.find(123),
  7. :query => 'search something',
  8. :limit => 15,
  9. )
  10. returns
  11. result = [organization_model1, organization_model2]
  12. =end
  13. def search(params)
  14. # get params
  15. query = params[:query]
  16. limit = params[:limit] || 10
  17. current_user = params[:current_user]
  18. # enable search only for agents and admins
  19. return [] if !current_user.is_role('Agent') && !current_user.is_role('Admin')
  20. # try search index backend
  21. if SearchIndexBackend.enabled?
  22. items = SearchIndexBackend.search( query, limit, 'Organization' )
  23. organizations = []
  24. items.each { |item|
  25. organizations.push Organization.lookup( :id => item[:id] )
  26. }
  27. return organizations
  28. end
  29. # fallback do sql query
  30. # - stip out * we already search for *query* -
  31. query.gsub! '*', ''
  32. organizations = Organization.where(
  33. 'name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"
  34. ).order('name').limit(limit)
  35. # if only a few organizations are found, search for names of users
  36. if organizations.length <= 3
  37. organizations_by_user = Organization.select('DISTINCT(organizations.id)').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
  38. 'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
  39. ).order('organizations.name').limit(limit)
  40. organizations_by_user.each {|organization_by_user|
  41. organization_exists = false
  42. organizations.each {|organization|
  43. if organization.id == organization_by_user.id
  44. organization_exists = true
  45. end
  46. }
  47. # get model with full data
  48. if !organization_exists
  49. organizations.push Organization.find(organization_by_user)
  50. end
  51. }
  52. end
  53. organizations
  54. end
  55. end