search.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # Copyright (C) 2012-2014 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.role?('Agent') && !current_user.role?(Z_ROLENAME_ADMIN)
  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 { |item|
  44. organizations.push Organization.lookup(id: item[:id])
  45. }
  46. return organizations
  47. end
  48. # fallback do sql query
  49. # - stip out * we already search for *query* -
  50. query.delete! '*'
  51. organizations = Organization.where(
  52. 'name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"
  53. ).order('name').limit(limit)
  54. # if only a few organizations are found, search for names of users
  55. if organizations.length <= 3
  56. organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
  57. 'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
  58. ).order('organizations.name').limit(limit)
  59. organizations_by_user.each {|organization_by_user|
  60. organization_exists = false
  61. organizations.each {|organization|
  62. if organization.id == organization_by_user.id
  63. organization_exists = true
  64. end
  65. }
  66. # get model with full data
  67. if !organization_exists
  68. organizations.push Organization.find(organization_by_user.id)
  69. end
  70. }
  71. end
  72. organizations
  73. end
  74. end
  75. end