From 3e54697c5ae919720162b672bb9e90b839ba79ea Mon Sep 17 00:00:00 2001 From: Bianca Nenciu Date: Mon, 15 Apr 2024 02:31:07 +0300 Subject: [PATCH] FIX: Load categories for related topics (#570) This is necessary when "lazy load categories" feature is enabled to make sure the categories are rendered for all related topics. --- lib/embeddings/entry_point.rb | 18 ++++++++++++------ spec/requests/topic_spec.rb | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/lib/embeddings/entry_point.rb b/lib/embeddings/entry_point.rb index 1fd15b7a..2ee65376 100644 --- a/lib/embeddings/entry_point.rb +++ b/lib/embeddings/entry_point.rb @@ -9,7 +9,7 @@ module DiscourseAi :topic_view_suggested_topics_options, ) do |suggested_options, topic_view| related_topics = topic_view.related_topics - include_random = related_topics.nil? || related_topics.length == 0 + include_random = !related_topics || related_topics.topics.length == 0 suggested_options.merge(include_random: include_random) end @@ -20,10 +20,16 @@ module DiscourseAi end @related_topics ||= - ::DiscourseAi::Embeddings::SemanticTopicQuery - .new(@user) - .list_semantic_related_topics(topic) - .topics + ::DiscourseAi::Embeddings::SemanticTopicQuery.new(@user).list_semantic_related_topics( + topic, + ) + end + + # define_method must be used (instead of add_to_class) to make sure + # that method still works when plugin is disabled too + TopicView.alias_method(:categories_old, :categories) + TopicView.define_method(:categories) do + @categories ||= [*categories_old, *related_topics&.categories].flatten.uniq.compact end %i[topic_view TopicViewPosts].each do |serializer| @@ -33,7 +39,7 @@ module DiscourseAi include_condition: -> { SiteSetting.ai_embeddings_semantic_related_topics_enabled }, ) do if object.next_page.nil? && !object.topic.private_message? - object.related_topics.map do |t| + object.related_topics.topics.map do |t| SuggestedTopicSerializer.new(t, scope: scope, root: false) end end diff --git a/spec/requests/topic_spec.rb b/spec/requests/topic_spec.rb index b3cd8851..479ef02b 100644 --- a/spec/requests/topic_spec.rb +++ b/spec/requests/topic_spec.rb @@ -34,6 +34,23 @@ describe ::TopicsController do expect(json["suggested_topics"].length).to eq(0) expect(json["related_topics"].length).to eq(2) end + + it "includes related topics in payload when configured" do + SiteSetting.lazy_load_categories_groups = "#{Group::AUTO_GROUPS[:everyone]}" + category = Fabricate(:category) + topic.update!(category: category) + + get("#{topic.relative_url}.json") + expect(response.status).to eq(200) + json = response.parsed_body + + expect(json["suggested_topics"].length).to eq(0) + expect(json["related_topics"].length).to eq(2) + expect(json["categories"].map { |c| c["id"] }).to contain_exactly( + SiteSetting.uncategorized_category_id, + category.id, + ) + end end describe "crawler" do