search.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Organization
  3. module Search
  4. =begin
  5. search organizations preferences
  6. result = Organization.search_preferences(user_model)
  7. returns if user has permissions to search
  8. result = {
  9. prio: 1000,
  10. direct_search_index: true
  11. }
  12. returns if user has no permissions to search
  13. result = false
  14. =end
  15. def search_preferences(current_user)
  16. return false if !current_user.permissions?('ticket.agent') && !current_user.permissions?('admin.organization')
  17. {
  18. prio: 1000,
  19. direct_search_index: true,
  20. }
  21. end
  22. =begin
  23. search organizations
  24. result = Organization.search(
  25. current_user: User.find(123),
  26. query: 'search something',
  27. limit: 15,
  28. )
  29. returns
  30. result = [organization_model1, organization_model2]
  31. =end
  32. def search(params)
  33. # get params
  34. query = params[:query]
  35. limit = params[:limit] || 10
  36. current_user = params[:current_user]
  37. # enable search only for agents and admins
  38. return [] if !search_preferences(current_user)
  39. # try search index backend
  40. if SearchIndexBackend.enabled?
  41. items = SearchIndexBackend.search(query, limit, 'Organization')
  42. organizations = []
  43. items.each do |item|
  44. organization = Organization.lookup(id: item[:id])
  45. next if !organization
  46. organizations.push organization
  47. end
  48. return organizations
  49. end
  50. # fallback do sql query
  51. # - stip out * we already search for *query* -
  52. query.delete! '*'
  53. organizations = Organization.where(
  54. 'name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"
  55. ).order('name').limit(limit).to_a
  56. # if only a few organizations are found, search for names of users
  57. if organizations.length <= 3
  58. organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
  59. 'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
  60. ).order('organizations.name').limit(limit)
  61. organizations_by_user.each do |organization_by_user|
  62. organization_exists = false
  63. organizations.each do |organization|
  64. if organization.id == organization_by_user.id
  65. organization_exists = true
  66. end
  67. end
  68. # get model with full data
  69. if !organization_exists
  70. organizations.push Organization.find(organization_by_user.id)
  71. end
  72. end
  73. end
  74. organizations
  75. end
  76. end
  77. end