translation.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase::Answer::Translation < ApplicationModel
  3. include HasDefaultModelUserRelations
  4. include HasAgentAllowedParams
  5. include HasLinks
  6. include HasSearchIndexBackend
  7. include KnowledgeBase::HasUniqueTitle
  8. include KnowledgeBase::Answer::Translation::Search
  9. AGENT_ALLOWED_ATTRIBUTES = %i[title kb_locale_id].freeze
  10. AGENT_ALLOWED_NESTED_RELATIONS = %i[content].freeze
  11. belongs_to :kb_locale, class_name: 'KnowledgeBase::Locale', inverse_of: :answer_translations
  12. belongs_to :answer, class_name: 'KnowledgeBase::Answer', inverse_of: :translations, touch: true
  13. belongs_to :content, class_name: 'KnowledgeBase::Answer::Translation::Content', inverse_of: :translation, dependent: :destroy
  14. accepts_nested_attributes_for :content, update_only: true
  15. validates :title, presence: true, length: { maximum: 250 }
  16. validates :kb_locale_id, uniqueness: { case_sensitive: true, scope: :answer_id }
  17. scope :neighbours_of, ->(translation) { joins(:answer).where(knowledge_base_answers: { category_id: translation.answer&.category_id }) }
  18. alias assets_essential assets
  19. def assets(data = {})
  20. return data if assets_added_to?(data)
  21. data = super
  22. answer.assets(data)
  23. ApplicationModel::CanAssets.reduce inline_linked_objects, data
  24. end
  25. def to_param
  26. [answer_id, title.parameterize].join('-')
  27. end
  28. def search_index_attribute_lookup(include_references: true)
  29. attrs = super
  30. attrs.merge('title' => ActionController::Base.helpers.strip_tags(attrs['title']),
  31. 'content' => content&.search_index_attribute_lookup,
  32. 'scope_id' => answer.category_id,
  33. 'attachment' => answer.attachments_for_search_index_attribute_lookup,
  34. 'tags' => answer.tag_list)
  35. end
  36. def inline_linked_objects
  37. output = []
  38. scrubber = Loofah::Scrubber.new do |node|
  39. next if node.name != 'a'
  40. next if !node.key? 'data-target-type'
  41. case node['data-target-type']
  42. when 'knowledge-base-answer'
  43. if (translation = KnowledgeBase::Answer::Translation.find_by(id: node['data-target-id']))
  44. output.push translation
  45. end
  46. end
  47. end
  48. Loofah.scrub_fragment(content.body, scrubber)
  49. output
  50. end
  51. scope :search_sql_text_fallback, lambda { |query|
  52. fields = %w[title]
  53. fields << KnowledgeBase::Answer::Translation::Content.arel_table[:body]
  54. where_or_cis(fields, query).joins(:content)
  55. }
  56. scope :apply_kb_scope, lambda { |scope|
  57. if scope.present?
  58. output
  59. .joins(:answer)
  60. .where(knowledge_base_answers: { category_id: scope })
  61. end
  62. }
  63. end