search.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Chat::Session
  3. module Search
  4. extend ActiveSupport::Concern
  5. # methods defined here are going to extend the class, not the instance of it
  6. class_methods do
  7. =begin
  8. search organizations preferences
  9. result = Chat::Session.search_preferences(user_model)
  10. returns if user has permissions to search
  11. result = {
  12. prio: 1000,
  13. direct_search_index: true
  14. }
  15. returns if user has no permissions to search
  16. result = false
  17. =end
  18. def search_preferences(current_user)
  19. return false if Setting.get('chat') != true || !current_user.permissions?('chat.agent')
  20. {
  21. prio: 900,
  22. direct_search_index: true,
  23. }
  24. end
  25. =begin
  26. search organizations
  27. result = Chat::Session.search(
  28. current_user: User.find(123),
  29. query: 'search something',
  30. limit: 15,
  31. offset: 100,
  32. )
  33. returns
  34. result = [organization_model1, organization_model2]
  35. =end
  36. def search(params)
  37. # get params
  38. query = params[:query]
  39. limit = params[:limit] || 10
  40. offset = params[:offset] || 0
  41. current_user = params[:current_user]
  42. # enable search only for agents and admins
  43. return [] if !search_preferences(current_user)
  44. # try search index backend
  45. if SearchIndexBackend.enabled?
  46. items = SearchIndexBackend.search(query, 'Chat::Session', limit: limit, from: offset)
  47. chat_sessions = []
  48. items.each do |item|
  49. chat_session = Chat::Session.lookup(id: item[:id])
  50. next if !chat_session
  51. chat_sessions.push chat_session
  52. end
  53. return chat_sessions
  54. end
  55. # fallback do sql query
  56. # - stip out * we already search for *query* -
  57. query.delete! '*'
  58. Chat::Session.where(
  59. 'name LIKE ?', "%#{query}%"
  60. ).order('name').offset(offset).limit(limit).to_a
  61. end
  62. end
  63. end
  64. end