search_knowledge_base_backend.rb 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class SearchKnowledgeBaseBackend
  3. attr_reader :knowledge_base
  4. # @param [Hash] params the paramsused to initialize search instance
  5. # @option params [KnowledgeBase, <KnowledgeBase>] :knowledge_base (nil) knowledge base instance
  6. # @option params [KnowledgeBase::Locale, <KnowledgeBase::Locale>, String] :locale (nil) KB Locale or string identifier
  7. # @option params [KnowledgeBase::Category] :scope (nil) optional search scope
  8. # @option params [Symbol] :flavor (:public) agent or public to indicate source and narrow down to internal or public answers accordingly
  9. # @option params [String, Array<String>] :index (nil) indexes to limit search to, searches all indexes if nil
  10. # @option params [Integer] :limit per page param for paginatin
  11. # @option params [Boolean] :highlight_enabled (true) highlight matching text
  12. # @option params [Hash<String=>String>, Hash<Symbol=>Symbol>] :order_by hash with column => asc/desc
  13. def initialize(params)
  14. @params = params.compact
  15. prepare_scope_ids
  16. end
  17. def search(query, user: nil, pagination: nil)
  18. raw_results = raw_results(query, user, pagination: pagination)
  19. filtered = filter_results raw_results, user
  20. if pagination
  21. filtered = filtered.slice pagination.offset, pagination.limit
  22. elsif @params[:limit]
  23. filtered = filtered.slice 0, @params[:limit]
  24. end
  25. filtered
  26. end
  27. def search_fallback(query, indexes, options)
  28. indexes
  29. .map { |index| search_fallback_for_index(query, index, options) }
  30. .flatten
  31. end
  32. def search_fallback_for_index(query, index, options)
  33. index
  34. .constantize
  35. .search_fallback("%#{query}%", @cached_scope_ids, options: options)
  36. .where(kb_locale: kb_locales)
  37. .order(**search_fallback_order)
  38. .pluck(:id)
  39. .map { |id| { id: id, type: index } }
  40. end
  41. def search_fallback_order
  42. @params[:order_by].presence || { updated_at: :desc }
  43. end
  44. def raw_results(query, user, pagination: nil)
  45. return search_fallback(query, indexes, { user: user }) if !SearchIndexBackend.enabled?
  46. SearchIndexBackend
  47. .search(query, indexes, options(pagination: pagination))
  48. .map do |hash|
  49. hash[:id] = hash[:id].to_i
  50. hash
  51. end
  52. end
  53. def filter_results(raw_results, user)
  54. raw_results
  55. .group_by { |result| result[:type] }
  56. .map { |group_name, grouped_results| filter_type(group_name, grouped_results, user) }
  57. .flatten
  58. end
  59. def filter_type(type, grouped_results, user)
  60. translation_ids = translation_ids_for_type(type, user)
  61. if !translation_ids
  62. return []
  63. end
  64. grouped_results.select { |result| translation_ids&.include? result[:id].to_i }
  65. end
  66. def translation_ids_for_type(type, user)
  67. case type
  68. when KnowledgeBase::Answer::Translation.name
  69. translation_ids_for_answers(user)
  70. when KnowledgeBase::Category::Translation.name
  71. translation_ids_for_categories(user)
  72. when KnowledgeBase::Translation.name
  73. translation_ids_for_kbs(user)
  74. end
  75. end
  76. def translation_ids_for_answers(user)
  77. scope = KnowledgeBase::Answer
  78. .joins(:category)
  79. .where(knowledge_base_categories: { knowledge_base_id: knowledge_bases })
  80. scope = if user&.permissions?('knowledge_base.editor')
  81. scope
  82. elsif user&.permissions?('knowledge_base.reader') && flavor == :agent
  83. scope.internal
  84. else
  85. scope.published
  86. end
  87. flatten_translation_ids(scope)
  88. end
  89. def translation_ids_for_categories(user)
  90. scope = KnowledgeBase::Category.where knowledge_base_id: knowledge_bases
  91. if user&.permissions?('knowledge_base.editor')
  92. flatten_translation_ids scope
  93. elsif user&.permissions?('knowledge_base.reader') && flavor == :agent
  94. flatten_answer_translation_ids(scope, :internal)
  95. else
  96. flatten_answer_translation_ids(scope, :public)
  97. end
  98. end
  99. def translation_ids_for_kbs(_user)
  100. flatten_translation_ids KnowledgeBase.active.where(id: knowledge_bases)
  101. end
  102. def indexes
  103. return Array(@params.fetch(:index)) if @params.key?(:index)
  104. %w[
  105. KnowledgeBase::Answer::Translation
  106. KnowledgeBase::Category::Translation
  107. KnowledgeBase::Translation
  108. ]
  109. end
  110. def kb_locales
  111. @kb_locales ||= begin
  112. case @params.fetch(:locale, nil)
  113. when KnowledgeBase::Locale
  114. Array(@params.fetch(:locale))
  115. when String
  116. KnowledgeBase::Locale
  117. .joins(:system_locale)
  118. .where(knowledge_base_id: knowledge_bases, locales: { locale: @params.fetch(:locale) })
  119. else
  120. KnowledgeBase::Locale
  121. .where(knowledge_base_id: knowledge_bases)
  122. end
  123. end
  124. end
  125. def kb_locales_in(knowledge_base_id)
  126. @kb_locales_in ||= {}
  127. @kb_locales_in[knowledge_base_id] ||= @kb_locales.select { |locale| locale.knowledge_base_id == knowledge_base_id }
  128. end
  129. def kb_locale_ids
  130. @kb_locale_ids ||= kb_locales.pluck(:id)
  131. end
  132. def knowledge_bases
  133. @knowledge_bases ||= begin
  134. if @params.key? :knowledge_base
  135. Array(@params.fetch(:knowledge_base))
  136. else
  137. KnowledgeBase.active
  138. end
  139. end
  140. end
  141. def flavor
  142. @params.fetch(:flavor, :public).to_sym
  143. end
  144. def base_options
  145. {
  146. query_extension: {
  147. bool: {
  148. must: [ { terms: { kb_locale_id: kb_locale_ids } } ]
  149. }
  150. }
  151. }
  152. end
  153. def options_apply_highlight(hash)
  154. return if !@params.fetch(:highlight_enabled, true)
  155. hash[:highlight_fields_by_indexes] = {
  156. 'KnowledgeBase::Answer::Translation': %w[title content.body attachment.content tags],
  157. 'KnowledgeBase::Category::Translation': %w[title],
  158. 'KnowledgeBase::Translation': %w[title]
  159. }
  160. end
  161. def options_apply_scope(hash)
  162. return if !@params.fetch(:scope, nil)
  163. hash[:query_extension][:bool][:must].push({ terms: { scope_id: @cached_scope_ids } })
  164. end
  165. def options_apply_pagination(hash, pagination)
  166. if @params[:from] && @params[:limit]
  167. hash[:from] = @params[:from]
  168. hash[:limit] = @params[:limit]
  169. elsif pagination
  170. hash[:from] = 0
  171. hash[:limit] = pagination.limit * 99
  172. end
  173. end
  174. def options_apply_order(hash)
  175. return if @params[:order_by].blank?
  176. hash[:sort_by] = @params[:order_by].keys
  177. hash[:order_by] = @params[:order_by].values
  178. end
  179. def options(pagination: nil)
  180. output = base_options
  181. options_apply_highlight(output)
  182. options_apply_scope(output)
  183. options_apply_pagination(output, pagination)
  184. options_apply_order(output)
  185. output
  186. end
  187. def flatten_translation_ids(collection)
  188. collection
  189. .eager_load(:translations)
  190. .map { |elem| elem.translations.pluck(:id) }
  191. .flatten
  192. end
  193. def flatten_answer_translation_ids(collection, visibility)
  194. collection
  195. .eager_load(:translations)
  196. .map { |elem| visible_category_translation_ids(elem, visibility) }
  197. .flatten
  198. end
  199. def visible_category_translation_ids(category, visibility)
  200. category
  201. .translations
  202. .to_a
  203. .select { |elem| visible_translation?(elem, visibility) }
  204. .pluck(:id)
  205. end
  206. def visible_translation?(translation, visibility)
  207. if kb_locales_in(translation.category.knowledge_base_id).exclude?(translation.kb_locale)
  208. return false
  209. end
  210. translation.category.send("#{visibility}_content?", translation.kb_locale)
  211. end
  212. def prepare_scope_ids
  213. return if !@params.key? :scope
  214. @cached_scope_ids = @params.fetch(:scope).self_with_children_ids
  215. end
  216. end