search.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright (C) 2012-2013 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 Setting.get('es_url')
  22. ids = SearchIndexBackend.search( query, limit, 'Organization' )
  23. organizations = []
  24. ids.each { |id|
  25. organizations.push Organization.lookup( :id => id )
  26. }
  27. return organizations
  28. end
  29. # fallback do sql query
  30. # do query
  31. organizations = Organization.find(
  32. :all,
  33. :limit => limit,
  34. :conditions => ['name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"],
  35. :order => 'name'
  36. )
  37. # if only a few organizations are found, search for names of users
  38. if organizations.length <= 3
  39. organizations_by_user = Organization.select('DISTINCT(organizations.id)').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').find(
  40. :all,
  41. :limit => limit,
  42. :conditions => ['users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"],
  43. :order => 'organizations.name'
  44. )
  45. organizations_by_user.each {|organization_by_user|
  46. organization_exists = false
  47. organizations.each {|organization|
  48. if organization.id == organization_by_user.id
  49. organization_exists = true
  50. end
  51. }
  52. # get model with full data
  53. if !organization_exists
  54. organizations.push Organization.find(organization_by_user)
  55. end
  56. }
  57. end
  58. organizations
  59. end
  60. end